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
xcltapestry/XCL-Charts
lib/src/main/java/org/xclcharts/renderer/RdChart.java
// Path: lib/src/main/java/org/xclcharts/common/IFormatterDoubleCallBack.java // public interface IFormatterDoubleCallBack { // // public String doubleFormatter(Double value); // // // } // // Path: lib/src/main/java/org/xclcharts/event/click/PointPosition.java // public class PointPosition extends RectPosition { // // protected PointF mPoint = null; // // public PointPosition() // { // } // // public PointF getPosition() // { // return mPoint; // } // // // public String getPointInfo() // { // if(null == mPoint)return ""; // String info = "x:"+Float.toString(mPoint.x)+" y:"+Float.toString(mPoint.y); // return info; // } // // }
import org.xclcharts.common.IFormatterDoubleCallBack; import org.xclcharts.event.click.PointPosition; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.util.Log;
/** * Copyright 2014 XCL-Charts * * 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. * * @Project XCL-Charts * @Description Android图表基类库 * @author XiongChuanLiang<br/>(xcl_168@aliyun.com) * @license http://www.apache.org/licenses/ Apache v2 License * @version 1.0 */ package org.xclcharts.renderer; /** * @ClassName RdChart * @Description 这是雷达图,极限图等图的基类 * @author XiongChuanLiang<br/>(xcl_168@aliyun.com) * */ public class RdChart extends EventChart { private String TAG = "RdChart"; //半径 private float mRadius=0.0f; //初始偏移角度 private int mOffsetAngle = 0;//180; //格式化线中点的标签显示 private IFormatterDoubleCallBack mDotLabelFormatter; //开放标签和线画笔让用户设置 private Paint mPaintLabel = null; private Paint mPaintLine = null; public RdChart() { //初始化图例 if(null != plotLegend) { plotLegend.show(); plotLegend.setType(XEnum.LegendType.ROW); plotLegend.setHorizontalAlign(XEnum.HorizontalAlign.CENTER); plotLegend.setVerticalAlign(XEnum.VerticalAlign.BOTTOM); plotLegend.showBox(); plotLegend.hideBackground(); } } @Override protected void calcPlotRange() { super.calcPlotRange(); this.mRadius = Math.min( div(this.plotArea.getWidth() ,2f) , div(this.plotArea.getHeight(),2f) ); } /** * 返回当前点击点的信息 * @param x 点击点X坐标 * @param y 点击点Y坐标 * @return 返回对应的位置记录 */
// Path: lib/src/main/java/org/xclcharts/common/IFormatterDoubleCallBack.java // public interface IFormatterDoubleCallBack { // // public String doubleFormatter(Double value); // // // } // // Path: lib/src/main/java/org/xclcharts/event/click/PointPosition.java // public class PointPosition extends RectPosition { // // protected PointF mPoint = null; // // public PointPosition() // { // } // // public PointF getPosition() // { // return mPoint; // } // // // public String getPointInfo() // { // if(null == mPoint)return ""; // String info = "x:"+Float.toString(mPoint.x)+" y:"+Float.toString(mPoint.y); // return info; // } // // } // Path: lib/src/main/java/org/xclcharts/renderer/RdChart.java import org.xclcharts.common.IFormatterDoubleCallBack; import org.xclcharts.event.click.PointPosition; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.util.Log; /** * Copyright 2014 XCL-Charts * * 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. * * @Project XCL-Charts * @Description Android图表基类库 * @author XiongChuanLiang<br/>(xcl_168@aliyun.com) * @license http://www.apache.org/licenses/ Apache v2 License * @version 1.0 */ package org.xclcharts.renderer; /** * @ClassName RdChart * @Description 这是雷达图,极限图等图的基类 * @author XiongChuanLiang<br/>(xcl_168@aliyun.com) * */ public class RdChart extends EventChart { private String TAG = "RdChart"; //半径 private float mRadius=0.0f; //初始偏移角度 private int mOffsetAngle = 0;//180; //格式化线中点的标签显示 private IFormatterDoubleCallBack mDotLabelFormatter; //开放标签和线画笔让用户设置 private Paint mPaintLabel = null; private Paint mPaintLine = null; public RdChart() { //初始化图例 if(null != plotLegend) { plotLegend.show(); plotLegend.setType(XEnum.LegendType.ROW); plotLegend.setHorizontalAlign(XEnum.HorizontalAlign.CENTER); plotLegend.setVerticalAlign(XEnum.VerticalAlign.BOTTOM); plotLegend.showBox(); plotLegend.hideBackground(); } } @Override protected void calcPlotRange() { super.calcPlotRange(); this.mRadius = Math.min( div(this.plotArea.getWidth() ,2f) , div(this.plotArea.getHeight(),2f) ); } /** * 返回当前点击点的信息 * @param x 点击点X坐标 * @param y 点击点Y坐标 * @return 返回对应的位置记录 */
public PointPosition getPositionRecord(float x,float y)
xcltapestry/XCL-Charts
lib/src/main/java/org/xclcharts/view/GraphicalView.java
// Path: lib/src/main/java/org/xclcharts/common/SysinfoHelper.java // public class SysinfoHelper { // // private static SysinfoHelper instance = null; // // public SysinfoHelper() // { // } // // public static synchronized SysinfoHelper getInstance(){ // if(instance == null){ // instance = new SysinfoHelper(); // } // return instance; // } // // // /** // * android自3.0引入了硬件加速,即使用GPU进行绘图.但低版本的Android不支持这个类, // * 为了兼容性,在低版本中将其硬件加速相关的代码设为不可用。 // * @return 系统是否包含硬件加速类 // */ // public boolean supportHardwareAccelerated() // { // boolean result = true; // int currentVersion = android.os.Build.VERSION.SDK_INT; // //android 3.0 == android.os.Build.VERSION_CODES.HONEYCOMB // if(currentVersion < 11) result = false; // return result; // } // // }
import org.xclcharts.common.SysinfoHelper; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.util.Log; import android.view.View;
result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { //wrap_content result = Math.min(result, specSize); } return result; } private int measureHeight(int measureSpec) { int result = 100; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { //fill_parent result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { //wrap_content result = Math.min(result, specSize); } return result; } /** * 禁用硬件加速. * 原因:android自3.0引入了硬件加速,即使用GPU进行绘图,但它并不能完善的支持所有的绘图, * 通常表现为内容(如Rect或Path)不可见,异常或渲染错误。所以类了保证图表的正常显示,强制禁用掉. */ protected void disableHardwareAccelerated() { //View.isHardwareAccelerated() //Canvas.isHardwareAccelerated()
// Path: lib/src/main/java/org/xclcharts/common/SysinfoHelper.java // public class SysinfoHelper { // // private static SysinfoHelper instance = null; // // public SysinfoHelper() // { // } // // public static synchronized SysinfoHelper getInstance(){ // if(instance == null){ // instance = new SysinfoHelper(); // } // return instance; // } // // // /** // * android自3.0引入了硬件加速,即使用GPU进行绘图.但低版本的Android不支持这个类, // * 为了兼容性,在低版本中将其硬件加速相关的代码设为不可用。 // * @return 系统是否包含硬件加速类 // */ // public boolean supportHardwareAccelerated() // { // boolean result = true; // int currentVersion = android.os.Build.VERSION.SDK_INT; // //android 3.0 == android.os.Build.VERSION_CODES.HONEYCOMB // if(currentVersion < 11) result = false; // return result; // } // // } // Path: lib/src/main/java/org/xclcharts/view/GraphicalView.java import org.xclcharts.common.SysinfoHelper; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.util.Log; import android.view.View; result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { //wrap_content result = Math.min(result, specSize); } return result; } private int measureHeight(int measureSpec) { int result = 100; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { //fill_parent result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { //wrap_content result = Math.min(result, specSize); } return result; } /** * 禁用硬件加速. * 原因:android自3.0引入了硬件加速,即使用GPU进行绘图,但它并不能完善的支持所有的绘图, * 通常表现为内容(如Rect或Path)不可见,异常或渲染错误。所以类了保证图表的正常显示,强制禁用掉. */ protected void disableHardwareAccelerated() { //View.isHardwareAccelerated() //Canvas.isHardwareAccelerated()
if(SysinfoHelper.getInstance().supportHardwareAccelerated())
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/MessageAck.java
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.calls; /** * @author Xperimental */ public class MessageAck extends LiveViewCall { private final byte ackMsgId; public MessageAck(byte ackMsgId) {
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/calls/MessageAck.java import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.calls; /** * @author Xperimental */ public class MessageAck extends LiveViewCall { private final byte ackMsgId; public MessageAck(byte ackMsgId) {
super(MessageConstants.MSG_ACK);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/NavigationResponse.java
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.calls; /** * @author Xperimental */ public class NavigationResponse extends LiveViewCall { private byte response; public NavigationResponse(byte response) {
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/calls/NavigationResponse.java import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.calls; /** * @author Xperimental */ public class NavigationResponse extends LiveViewCall { private byte response; public NavigationResponse(byte response) {
super(MessageConstants.MSG_NAVIGATION_RESP);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/MenuItem.java
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // // Path: src/net/sourcewalker/olv/messages/UShort.java // public class UShort { // // private int value; // // public short getValue() { // return (short) (value & 0xFFFF); // } // // public void setValue(short value) { // this.value = (int) (value & 0xFFFF); // } // // public UShort(short value) { // setValue(value); // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return Integer.toString(value); // } // }
import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; import net.sourcewalker.olv.messages.UShort;
package net.sourcewalker.olv.messages.calls; public class MenuItem extends LiveViewCall { private byte itemId; private boolean alertItem;
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // // Path: src/net/sourcewalker/olv/messages/UShort.java // public class UShort { // // private int value; // // public short getValue() { // return (short) (value & 0xFFFF); // } // // public void setValue(short value) { // this.value = (int) (value & 0xFFFF); // } // // public UShort(short value) { // setValue(value); // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return Integer.toString(value); // } // } // Path: src/net/sourcewalker/olv/messages/calls/MenuItem.java import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; import net.sourcewalker.olv.messages.UShort; package net.sourcewalker.olv.messages.calls; public class MenuItem extends LiveViewCall { private byte itemId; private boolean alertItem;
private UShort unreadCount;
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/MenuItem.java
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // // Path: src/net/sourcewalker/olv/messages/UShort.java // public class UShort { // // private int value; // // public short getValue() { // return (short) (value & 0xFFFF); // } // // public void setValue(short value) { // this.value = (int) (value & 0xFFFF); // } // // public UShort(short value) { // setValue(value); // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return Integer.toString(value); // } // }
import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; import net.sourcewalker.olv.messages.UShort;
package net.sourcewalker.olv.messages.calls; public class MenuItem extends LiveViewCall { private byte itemId; private boolean alertItem; private UShort unreadCount; private String text; private byte[] image; public MenuItem(byte itemId, boolean alertItem, UShort unreadCount, String text, byte[] image) {
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // // Path: src/net/sourcewalker/olv/messages/UShort.java // public class UShort { // // private int value; // // public short getValue() { // return (short) (value & 0xFFFF); // } // // public void setValue(short value) { // this.value = (int) (value & 0xFFFF); // } // // public UShort(short value) { // setValue(value); // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return Integer.toString(value); // } // } // Path: src/net/sourcewalker/olv/messages/calls/MenuItem.java import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; import net.sourcewalker.olv.messages.UShort; package net.sourcewalker.olv.messages.calls; public class MenuItem extends LiveViewCall { private byte itemId; private boolean alertItem; private UShort unreadCount; private String text; private byte[] image; public MenuItem(byte itemId, boolean alertItem, UShort unreadCount, String text, byte[] image) {
super(MessageConstants.MSG_GETMENUITEM_RESP);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/GetTimeResponse.java
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import java.nio.ByteBuffer; import java.util.Date; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.calls; public class GetTimeResponse extends LiveViewCall { private int time; public GetTimeResponse(Date time) {
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/calls/GetTimeResponse.java import java.nio.ByteBuffer; import java.util.Date; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.calls; public class GetTimeResponse extends LiveViewCall { private int time; public GetTimeResponse(Date time) {
super(MessageConstants.MSG_GETTIME_RESP);
xperimental/OpenLiveView
src/net/sourcewalker/olv/service/BTReceiver.java
// Path: src/net/sourcewalker/olv/data/Prefs.java // public class Prefs { // // private final SharedPreferences preferences; // private final String keyDeviceAddress; // // public Prefs(Context context) { // preferences = PreferenceManager.getDefaultSharedPreferences(context); // keyDeviceAddress = context.getString(R.string.prefs_deviceaddress_key); // } // // public String getDeviceAddress() { // return preferences.getString("device.address", null); // } // // public void setDeviceAddress(String address) { // Editor editor = preferences.edit(); // editor.putString(keyDeviceAddress, address); // editor.commit(); // } // }
import net.sourcewalker.olv.data.Prefs; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log;
package net.sourcewalker.olv.service; /** * This receiver listens for system broadcasts related to the bluetooth device * and controls the LiveView service. It is also used for starting the service * on boot (if bluetooth is available). * * @author Robert &lt;xperimental@solidproject.de&gt; */ public class BTReceiver extends BroadcastReceiver { private static final String TAG = "BTReceiver"; /* * (non-Javadoc) * @see android.content.BroadcastReceiver#onReceive(android.content.Context, * android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) {
// Path: src/net/sourcewalker/olv/data/Prefs.java // public class Prefs { // // private final SharedPreferences preferences; // private final String keyDeviceAddress; // // public Prefs(Context context) { // preferences = PreferenceManager.getDefaultSharedPreferences(context); // keyDeviceAddress = context.getString(R.string.prefs_deviceaddress_key); // } // // public String getDeviceAddress() { // return preferences.getString("device.address", null); // } // // public void setDeviceAddress(String address) { // Editor editor = preferences.edit(); // editor.putString(keyDeviceAddress, address); // editor.commit(); // } // } // Path: src/net/sourcewalker/olv/service/BTReceiver.java import net.sourcewalker.olv.data.Prefs; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; package net.sourcewalker.olv.service; /** * This receiver listens for system broadcasts related to the bluetooth device * and controls the LiveView service. It is also used for starting the service * on boot (if bluetooth is available). * * @author Robert &lt;xperimental@solidproject.de&gt; */ public class BTReceiver extends BroadcastReceiver { private static final String TAG = "BTReceiver"; /* * (non-Javadoc) * @see android.content.BroadcastReceiver#onReceive(android.content.Context, * android.content.Intent) */ @Override public void onReceive(Context context, Intent intent) {
Prefs prefs = new Prefs(context);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/events/CapsResponse.java
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // // Path: src/net/sourcewalker/olv/messages/UByte.java // public class UByte { // // private short value; // // public byte getValue() { // return (byte) (value & 0xFF); // } // // public void setValue(byte value) { // this.value = (short) (value & 0xFF); // } // // public UByte(byte value) { // setValue(value); // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return Short.toString(value); // } // // }
import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants; import net.sourcewalker.olv.messages.UByte;
public void setAnnounceHeight(byte announceHeight) { this.announceHeight = announceHeight; } public byte getTextChunkSize() { return textChunkSize; } public void setTextChunkSize(byte textChunkSize) { this.textChunkSize = textChunkSize; } public byte getIdleTimer() { return idleTimer; } public void setIdleTimer(byte idleTimer) { this.idleTimer = idleTimer; } public String getSoftwareVersion() { return softwareVersion; } public void setSoftwareVersion(String softwareVersion) { this.softwareVersion = softwareVersion; } public CapsResponse() {
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // // Path: src/net/sourcewalker/olv/messages/UByte.java // public class UByte { // // private short value; // // public byte getValue() { // return (byte) (value & 0xFF); // } // // public void setValue(byte value) { // this.value = (short) (value & 0xFF); // } // // public UByte(byte value) { // setValue(value); // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return Short.toString(value); // } // // } // Path: src/net/sourcewalker/olv/messages/events/CapsResponse.java import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants; import net.sourcewalker.olv.messages.UByte; public void setAnnounceHeight(byte announceHeight) { this.announceHeight = announceHeight; } public byte getTextChunkSize() { return textChunkSize; } public void setTextChunkSize(byte textChunkSize) { this.textChunkSize = textChunkSize; } public byte getIdleTimer() { return idleTimer; } public void setIdleTimer(byte idleTimer) { this.idleTimer = idleTimer; } public String getSoftwareVersion() { return softwareVersion; } public void setSoftwareVersion(String softwareVersion) { this.softwareVersion = softwareVersion; } public CapsResponse() {
super(MessageConstants.MSG_GETCAPS_RESP);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/DeviceStatusAck.java
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.calls; public class DeviceStatusAck extends LiveViewCall { public DeviceStatusAck() {
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/calls/DeviceStatusAck.java import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.calls; public class DeviceStatusAck extends LiveViewCall { public DeviceStatusAck() {
super(MessageConstants.MSG_DEVICESTATUS_ACK);
xperimental/OpenLiveView
src/net/sourcewalker/olv/service/EventReader.java
// Path: src/net/sourcewalker/olv/messages/DecodeException.java // public class DecodeException extends Exception { // // private static final long serialVersionUID = 1102616192132639136L; // // public DecodeException() { // super(); // } // // public DecodeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public DecodeException(String detailMessage) { // super(detailMessage); // } // // public DecodeException(Throwable throwable) { // super(throwable); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageDecoder.java // public final class MessageDecoder { // // private static final String TAG = "MessageDecoder"; // // private static LiveViewEvent newInstanceForId(byte id) // throws DecodeException { // switch (id) { // case MessageConstants.MSG_GETCAPS_RESP: // return new CapsResponse(); // case MessageConstants.MSG_SETVIBRATE_ACK: // case MessageConstants.MSG_SETLED_ACK: // return new ResultEvent(id); // case MessageConstants.MSG_GETTIME: // return new GetTime(); // case MessageConstants.MSG_GETMENUITEMS: // return new GetMenuItems(); // case MessageConstants.MSG_DEVICESTATUS: // return new DeviceStatus(); // case MessageConstants.MSG_NAVIGATION: // return new Navigation(); // default: // throw new DecodeException("No message found matching ID: " + id); // } // } // // public static final LiveViewEvent decode(byte[] message, int length) // throws DecodeException { // if (length < 4) { // Log.w(TAG, "Got empty message!"); // throw new DecodeException("Can't decode empty message!"); // } else { // ByteBuffer buffer = ByteBuffer.wrap(message, 0, length); // byte msgId = buffer.get(); // buffer.get(); // int payloadLen = buffer.getInt(); // if (payloadLen + 6 == length) { // LiveViewEvent result = newInstanceForId(msgId); // result.readData(buffer); // return result; // } else { // throw new DecodeException("Invalid message length: " // + message.length + " (should be " + (payloadLen + 6) // + ")"); // } // } // } // // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.DecodeException; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageDecoder;
package net.sourcewalker.olv.service; /** * This reader reads an input stream and extracts LiveViewMessages from it. * * @author Robert &lt;xperimental@solidproject.de&gt; */ public class EventReader { private final InputStream stream; /** * Construct a MessageReader using the {@link InputStream} provided. * * @param inputStream * Stream to read messages from. */ public EventReader(InputStream inputStream) { super(); this.stream = inputStream; } /** * Closes the underlying input stream. */ public void close() throws IOException { stream.close(); } /** * Try to read a single {@link LiveViewEvent} from the stream. If there is * more than one event available on the stream then subsequent calls to this * method will return them. * * @return Event read from the stream. * @throws IOException * If there is an error reading from the underlying stream. * @throws DecodeException * If an invalid message was read. */
// Path: src/net/sourcewalker/olv/messages/DecodeException.java // public class DecodeException extends Exception { // // private static final long serialVersionUID = 1102616192132639136L; // // public DecodeException() { // super(); // } // // public DecodeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public DecodeException(String detailMessage) { // super(detailMessage); // } // // public DecodeException(Throwable throwable) { // super(throwable); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageDecoder.java // public final class MessageDecoder { // // private static final String TAG = "MessageDecoder"; // // private static LiveViewEvent newInstanceForId(byte id) // throws DecodeException { // switch (id) { // case MessageConstants.MSG_GETCAPS_RESP: // return new CapsResponse(); // case MessageConstants.MSG_SETVIBRATE_ACK: // case MessageConstants.MSG_SETLED_ACK: // return new ResultEvent(id); // case MessageConstants.MSG_GETTIME: // return new GetTime(); // case MessageConstants.MSG_GETMENUITEMS: // return new GetMenuItems(); // case MessageConstants.MSG_DEVICESTATUS: // return new DeviceStatus(); // case MessageConstants.MSG_NAVIGATION: // return new Navigation(); // default: // throw new DecodeException("No message found matching ID: " + id); // } // } // // public static final LiveViewEvent decode(byte[] message, int length) // throws DecodeException { // if (length < 4) { // Log.w(TAG, "Got empty message!"); // throw new DecodeException("Can't decode empty message!"); // } else { // ByteBuffer buffer = ByteBuffer.wrap(message, 0, length); // byte msgId = buffer.get(); // buffer.get(); // int payloadLen = buffer.getInt(); // if (payloadLen + 6 == length) { // LiveViewEvent result = newInstanceForId(msgId); // result.readData(buffer); // return result; // } else { // throw new DecodeException("Invalid message length: " // + message.length + " (should be " + (payloadLen + 6) // + ")"); // } // } // } // // } // Path: src/net/sourcewalker/olv/service/EventReader.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.DecodeException; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageDecoder; package net.sourcewalker.olv.service; /** * This reader reads an input stream and extracts LiveViewMessages from it. * * @author Robert &lt;xperimental@solidproject.de&gt; */ public class EventReader { private final InputStream stream; /** * Construct a MessageReader using the {@link InputStream} provided. * * @param inputStream * Stream to read messages from. */ public EventReader(InputStream inputStream) { super(); this.stream = inputStream; } /** * Closes the underlying input stream. */ public void close() throws IOException { stream.close(); } /** * Try to read a single {@link LiveViewEvent} from the stream. If there is * more than one event available on the stream then subsequent calls to this * method will return them. * * @return Event read from the stream. * @throws IOException * If there is an error reading from the underlying stream. * @throws DecodeException * If an invalid message was read. */
public LiveViewEvent readMessage() throws IOException, DecodeException {
xperimental/OpenLiveView
src/net/sourcewalker/olv/service/EventReader.java
// Path: src/net/sourcewalker/olv/messages/DecodeException.java // public class DecodeException extends Exception { // // private static final long serialVersionUID = 1102616192132639136L; // // public DecodeException() { // super(); // } // // public DecodeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public DecodeException(String detailMessage) { // super(detailMessage); // } // // public DecodeException(Throwable throwable) { // super(throwable); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageDecoder.java // public final class MessageDecoder { // // private static final String TAG = "MessageDecoder"; // // private static LiveViewEvent newInstanceForId(byte id) // throws DecodeException { // switch (id) { // case MessageConstants.MSG_GETCAPS_RESP: // return new CapsResponse(); // case MessageConstants.MSG_SETVIBRATE_ACK: // case MessageConstants.MSG_SETLED_ACK: // return new ResultEvent(id); // case MessageConstants.MSG_GETTIME: // return new GetTime(); // case MessageConstants.MSG_GETMENUITEMS: // return new GetMenuItems(); // case MessageConstants.MSG_DEVICESTATUS: // return new DeviceStatus(); // case MessageConstants.MSG_NAVIGATION: // return new Navigation(); // default: // throw new DecodeException("No message found matching ID: " + id); // } // } // // public static final LiveViewEvent decode(byte[] message, int length) // throws DecodeException { // if (length < 4) { // Log.w(TAG, "Got empty message!"); // throw new DecodeException("Can't decode empty message!"); // } else { // ByteBuffer buffer = ByteBuffer.wrap(message, 0, length); // byte msgId = buffer.get(); // buffer.get(); // int payloadLen = buffer.getInt(); // if (payloadLen + 6 == length) { // LiveViewEvent result = newInstanceForId(msgId); // result.readData(buffer); // return result; // } else { // throw new DecodeException("Invalid message length: " // + message.length + " (should be " + (payloadLen + 6) // + ")"); // } // } // } // // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.DecodeException; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageDecoder;
package net.sourcewalker.olv.service; /** * This reader reads an input stream and extracts LiveViewMessages from it. * * @author Robert &lt;xperimental@solidproject.de&gt; */ public class EventReader { private final InputStream stream; /** * Construct a MessageReader using the {@link InputStream} provided. * * @param inputStream * Stream to read messages from. */ public EventReader(InputStream inputStream) { super(); this.stream = inputStream; } /** * Closes the underlying input stream. */ public void close() throws IOException { stream.close(); } /** * Try to read a single {@link LiveViewEvent} from the stream. If there is * more than one event available on the stream then subsequent calls to this * method will return them. * * @return Event read from the stream. * @throws IOException * If there is an error reading from the underlying stream. * @throws DecodeException * If an invalid message was read. */
// Path: src/net/sourcewalker/olv/messages/DecodeException.java // public class DecodeException extends Exception { // // private static final long serialVersionUID = 1102616192132639136L; // // public DecodeException() { // super(); // } // // public DecodeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public DecodeException(String detailMessage) { // super(detailMessage); // } // // public DecodeException(Throwable throwable) { // super(throwable); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageDecoder.java // public final class MessageDecoder { // // private static final String TAG = "MessageDecoder"; // // private static LiveViewEvent newInstanceForId(byte id) // throws DecodeException { // switch (id) { // case MessageConstants.MSG_GETCAPS_RESP: // return new CapsResponse(); // case MessageConstants.MSG_SETVIBRATE_ACK: // case MessageConstants.MSG_SETLED_ACK: // return new ResultEvent(id); // case MessageConstants.MSG_GETTIME: // return new GetTime(); // case MessageConstants.MSG_GETMENUITEMS: // return new GetMenuItems(); // case MessageConstants.MSG_DEVICESTATUS: // return new DeviceStatus(); // case MessageConstants.MSG_NAVIGATION: // return new Navigation(); // default: // throw new DecodeException("No message found matching ID: " + id); // } // } // // public static final LiveViewEvent decode(byte[] message, int length) // throws DecodeException { // if (length < 4) { // Log.w(TAG, "Got empty message!"); // throw new DecodeException("Can't decode empty message!"); // } else { // ByteBuffer buffer = ByteBuffer.wrap(message, 0, length); // byte msgId = buffer.get(); // buffer.get(); // int payloadLen = buffer.getInt(); // if (payloadLen + 6 == length) { // LiveViewEvent result = newInstanceForId(msgId); // result.readData(buffer); // return result; // } else { // throw new DecodeException("Invalid message length: " // + message.length + " (should be " + (payloadLen + 6) // + ")"); // } // } // } // // } // Path: src/net/sourcewalker/olv/service/EventReader.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.DecodeException; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageDecoder; package net.sourcewalker.olv.service; /** * This reader reads an input stream and extracts LiveViewMessages from it. * * @author Robert &lt;xperimental@solidproject.de&gt; */ public class EventReader { private final InputStream stream; /** * Construct a MessageReader using the {@link InputStream} provided. * * @param inputStream * Stream to read messages from. */ public EventReader(InputStream inputStream) { super(); this.stream = inputStream; } /** * Closes the underlying input stream. */ public void close() throws IOException { stream.close(); } /** * Try to read a single {@link LiveViewEvent} from the stream. If there is * more than one event available on the stream then subsequent calls to this * method will return them. * * @return Event read from the stream. * @throws IOException * If there is an error reading from the underlying stream. * @throws DecodeException * If an invalid message was read. */
public LiveViewEvent readMessage() throws IOException, DecodeException {
xperimental/OpenLiveView
src/net/sourcewalker/olv/service/EventReader.java
// Path: src/net/sourcewalker/olv/messages/DecodeException.java // public class DecodeException extends Exception { // // private static final long serialVersionUID = 1102616192132639136L; // // public DecodeException() { // super(); // } // // public DecodeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public DecodeException(String detailMessage) { // super(detailMessage); // } // // public DecodeException(Throwable throwable) { // super(throwable); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageDecoder.java // public final class MessageDecoder { // // private static final String TAG = "MessageDecoder"; // // private static LiveViewEvent newInstanceForId(byte id) // throws DecodeException { // switch (id) { // case MessageConstants.MSG_GETCAPS_RESP: // return new CapsResponse(); // case MessageConstants.MSG_SETVIBRATE_ACK: // case MessageConstants.MSG_SETLED_ACK: // return new ResultEvent(id); // case MessageConstants.MSG_GETTIME: // return new GetTime(); // case MessageConstants.MSG_GETMENUITEMS: // return new GetMenuItems(); // case MessageConstants.MSG_DEVICESTATUS: // return new DeviceStatus(); // case MessageConstants.MSG_NAVIGATION: // return new Navigation(); // default: // throw new DecodeException("No message found matching ID: " + id); // } // } // // public static final LiveViewEvent decode(byte[] message, int length) // throws DecodeException { // if (length < 4) { // Log.w(TAG, "Got empty message!"); // throw new DecodeException("Can't decode empty message!"); // } else { // ByteBuffer buffer = ByteBuffer.wrap(message, 0, length); // byte msgId = buffer.get(); // buffer.get(); // int payloadLen = buffer.getInt(); // if (payloadLen + 6 == length) { // LiveViewEvent result = newInstanceForId(msgId); // result.readData(buffer); // return result; // } else { // throw new DecodeException("Invalid message length: " // + message.length + " (should be " + (payloadLen + 6) // + ")"); // } // } // } // // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.DecodeException; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageDecoder;
ByteArrayOutputStream msgStream = new ByteArrayOutputStream(); int needRead = 1; ReaderState state = ReaderState.ID; do { byte read = (byte) stream.read(); if (read == -1) { throw new DecodeException("Invalid message received (length=" + msgStream.size() + ")"); } needRead--; msgStream.write(read); if (needRead == 0) { switch (state) { case ID: state = ReaderState.HEADER_LEN; needRead = 1; break; case HEADER_LEN: state = ReaderState.HEADER; needRead = read; break; case HEADER: int payloadSize = getLastInt(msgStream); state = ReaderState.PAYLOAD; needRead = payloadSize; break; } } } while (needRead > 0); byte[] msgArray = msgStream.toByteArray();
// Path: src/net/sourcewalker/olv/messages/DecodeException.java // public class DecodeException extends Exception { // // private static final long serialVersionUID = 1102616192132639136L; // // public DecodeException() { // super(); // } // // public DecodeException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public DecodeException(String detailMessage) { // super(detailMessage); // } // // public DecodeException(Throwable throwable) { // super(throwable); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageDecoder.java // public final class MessageDecoder { // // private static final String TAG = "MessageDecoder"; // // private static LiveViewEvent newInstanceForId(byte id) // throws DecodeException { // switch (id) { // case MessageConstants.MSG_GETCAPS_RESP: // return new CapsResponse(); // case MessageConstants.MSG_SETVIBRATE_ACK: // case MessageConstants.MSG_SETLED_ACK: // return new ResultEvent(id); // case MessageConstants.MSG_GETTIME: // return new GetTime(); // case MessageConstants.MSG_GETMENUITEMS: // return new GetMenuItems(); // case MessageConstants.MSG_DEVICESTATUS: // return new DeviceStatus(); // case MessageConstants.MSG_NAVIGATION: // return new Navigation(); // default: // throw new DecodeException("No message found matching ID: " + id); // } // } // // public static final LiveViewEvent decode(byte[] message, int length) // throws DecodeException { // if (length < 4) { // Log.w(TAG, "Got empty message!"); // throw new DecodeException("Can't decode empty message!"); // } else { // ByteBuffer buffer = ByteBuffer.wrap(message, 0, length); // byte msgId = buffer.get(); // buffer.get(); // int payloadLen = buffer.getInt(); // if (payloadLen + 6 == length) { // LiveViewEvent result = newInstanceForId(msgId); // result.readData(buffer); // return result; // } else { // throw new DecodeException("Invalid message length: " // + message.length + " (should be " + (payloadLen + 6) // + ")"); // } // } // } // // } // Path: src/net/sourcewalker/olv/service/EventReader.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.DecodeException; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageDecoder; ByteArrayOutputStream msgStream = new ByteArrayOutputStream(); int needRead = 1; ReaderState state = ReaderState.ID; do { byte read = (byte) stream.read(); if (read == -1) { throw new DecodeException("Invalid message received (length=" + msgStream.size() + ")"); } needRead--; msgStream.write(read); if (needRead == 0) { switch (state) { case ID: state = ReaderState.HEADER_LEN; needRead = 1; break; case HEADER_LEN: state = ReaderState.HEADER; needRead = read; break; case HEADER: int payloadSize = getLastInt(msgStream); state = ReaderState.PAYLOAD; needRead = payloadSize; break; } } } while (needRead > 0); byte[] msgArray = msgStream.toByteArray();
return MessageDecoder.decode(msgArray, msgArray.length);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/SetVibrate.java
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // // Path: src/net/sourcewalker/olv/messages/UShort.java // public class UShort { // // private int value; // // public short getValue() { // return (short) (value & 0xFFFF); // } // // public void setValue(short value) { // this.value = (int) (value & 0xFFFF); // } // // public UShort(short value) { // setValue(value); // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return Integer.toString(value); // } // }
import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; import net.sourcewalker.olv.messages.UShort;
package net.sourcewalker.olv.messages.calls; public class SetVibrate extends LiveViewCall { private final UShort delay; private final UShort time; public SetVibrate(int delay, int time) {
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // // Path: src/net/sourcewalker/olv/messages/UShort.java // public class UShort { // // private int value; // // public short getValue() { // return (short) (value & 0xFFFF); // } // // public void setValue(short value) { // this.value = (int) (value & 0xFFFF); // } // // public UShort(short value) { // setValue(value); // } // // /* // * (non-Javadoc) // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return Integer.toString(value); // } // } // Path: src/net/sourcewalker/olv/messages/calls/SetVibrate.java import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; import net.sourcewalker.olv.messages.UShort; package net.sourcewalker.olv.messages.calls; public class SetVibrate extends LiveViewCall { private final UShort delay; private final UShort time; public SetVibrate(int delay, int time) {
super(MessageConstants.MSG_SETVIBRATE);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/SetMenuSize.java
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.calls; public class SetMenuSize extends LiveViewCall { private final byte menuSize; public SetMenuSize(byte menuSize) {
// Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/calls/SetMenuSize.java import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.calls; public class SetMenuSize extends LiveViewCall { private final byte menuSize; public SetMenuSize(byte menuSize) {
super(MessageConstants.MSG_SETMENUSIZE);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/events/Navigation.java
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants; import android.util.Log;
package net.sourcewalker.olv.messages.events; public class Navigation extends LiveViewEvent { private static final String TAG = "Navigation"; private byte menuItemId; private byte navAction; private byte navType; private boolean inAlert; public byte getMenuItemId() { return menuItemId; } public byte getNavAction() { return navAction; } public byte getNavType() { return navType; } public boolean isInAlert() { return inAlert; } public Navigation() {
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/events/Navigation.java import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants; import android.util.Log; package net.sourcewalker.olv.messages.events; public class Navigation extends LiveViewEvent { private static final String TAG = "Navigation"; private byte menuItemId; private byte navAction; private byte navType; private boolean inAlert; public byte getMenuItemId() { return menuItemId; } public byte getNavAction() { return navAction; } public byte getNavType() { return navType; } public boolean isInAlert() { return inAlert; } public Navigation() {
super(MessageConstants.MSG_NAVIGATION);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/CapsRequest.java
// Path: src/net/sourcewalker/olv/messages/EncodingException.java // public class EncodingException extends RuntimeException { // // private static final long serialVersionUID = -7148079841490219145L; // // public EncodingException(Exception cause) { // super("Error while encoding message: " + cause.getMessage(), cause); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.EncodingException; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.calls; public class CapsRequest extends LiveViewCall { public CapsRequest() {
// Path: src/net/sourcewalker/olv/messages/EncodingException.java // public class EncodingException extends RuntimeException { // // private static final long serialVersionUID = -7148079841490219145L; // // public EncodingException(Exception cause) { // super("Error while encoding message: " + cause.getMessage(), cause); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/calls/CapsRequest.java import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.EncodingException; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.calls; public class CapsRequest extends LiveViewCall { public CapsRequest() {
super(MessageConstants.MSG_GETCAPS);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/calls/CapsRequest.java
// Path: src/net/sourcewalker/olv/messages/EncodingException.java // public class EncodingException extends RuntimeException { // // private static final long serialVersionUID = -7148079841490219145L; // // public EncodingException(Exception cause) { // super("Error while encoding message: " + cause.getMessage(), cause); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.EncodingException; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.calls; public class CapsRequest extends LiveViewCall { public CapsRequest() { super(MessageConstants.MSG_GETCAPS); } /* * (non-Javadoc) * @see net.sourcewalker.olv.LiveViewMessage#getPayload() */ @Override protected byte[] getPayload() { try { byte[] version = MessageConstants.CLIENT_SOFTWARE_VERSION .getBytes("iso-8859-1"); byte msgLength = (byte) version.length; ByteBuffer buffer = ByteBuffer.allocate(msgLength + 1); buffer.order(ByteOrder.BIG_ENDIAN); buffer.put(msgLength); buffer.put(version); return buffer.array(); } catch (UnsupportedEncodingException e) {
// Path: src/net/sourcewalker/olv/messages/EncodingException.java // public class EncodingException extends RuntimeException { // // private static final long serialVersionUID = -7148079841490219145L; // // public EncodingException(Exception cause) { // super("Error while encoding message: " + cause.getMessage(), cause); // } // // } // // Path: src/net/sourcewalker/olv/messages/LiveViewCall.java // public abstract class LiveViewCall extends LiveViewMessage { // // /** // * Header consists of two bytes and a int value (4 bytes). // */ // private static final int HEADER_LENGTH = 6; // // public LiveViewCall(byte id) { // super(id); // } // // protected abstract byte[] getPayload(); // // public byte[] getEncoded() { // byte[] payload = getPayload(); // int msgLength = payload.length + HEADER_LENGTH; // ByteBuffer msgBuffer = ByteBuffer.allocate(msgLength); // msgBuffer.order(ByteOrder.BIG_ENDIAN); // msgBuffer.put(getId()); // msgBuffer.put((byte) 4); // msgBuffer.putInt(payload.length); // msgBuffer.put(payload); // return msgBuffer.array(); // } // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/calls/CapsRequest.java import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import net.sourcewalker.olv.messages.EncodingException; import net.sourcewalker.olv.messages.LiveViewCall; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.calls; public class CapsRequest extends LiveViewCall { public CapsRequest() { super(MessageConstants.MSG_GETCAPS); } /* * (non-Javadoc) * @see net.sourcewalker.olv.LiveViewMessage#getPayload() */ @Override protected byte[] getPayload() { try { byte[] version = MessageConstants.CLIENT_SOFTWARE_VERSION .getBytes("iso-8859-1"); byte msgLength = (byte) version.length; ByteBuffer buffer = ByteBuffer.allocate(msgLength + 1); buffer.order(ByteOrder.BIG_ENDIAN); buffer.put(msgLength); buffer.put(version); return buffer.array(); } catch (UnsupportedEncodingException e) {
throw new EncodingException(e);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/events/GetTime.java
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.events; public class GetTime extends LiveViewEvent { public GetTime() {
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/events/GetTime.java import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.events; public class GetTime extends LiveViewEvent { public GetTime() {
super(MessageConstants.MSG_GETTIME);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/events/DeviceStatus.java
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.events; public class DeviceStatus extends LiveViewEvent { private byte status; public byte getStatus() { return status; } public DeviceStatus() {
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/events/DeviceStatus.java import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.events; public class DeviceStatus extends LiveViewEvent { private byte status; public byte getStatus() { return status; } public DeviceStatus() {
super(MessageConstants.MSG_DEVICESTATUS);
xperimental/OpenLiveView
src/net/sourcewalker/olv/messages/events/GetMenuItems.java
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // }
import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants;
package net.sourcewalker.olv.messages.events; public class GetMenuItems extends LiveViewEvent { public GetMenuItems() {
// Path: src/net/sourcewalker/olv/messages/LiveViewEvent.java // public abstract class LiveViewEvent extends LiveViewMessage { // // public LiveViewEvent(byte id) { // super(id); // } // // public abstract void readData(ByteBuffer buffer); // // } // // Path: src/net/sourcewalker/olv/messages/MessageConstants.java // public final class MessageConstants { // // public static final byte MSG_GETCAPS = 1; // public static final byte MSG_GETCAPS_RESP = 2; // // public static final byte MSG_DISPLAYTEXT = 3; // public static final byte MSG_DISPLAYTEXT_ACK = 4; // // public static final byte MSG_DISPLAYPANEL = 5; // public static final byte MSG_DISPLAYPANEL_ACK = 6; // // public static final byte MSG_DEVICESTATUS = 7; // public static final byte MSG_DEVICESTATUS_ACK = 8; // // public static final byte MSG_DISPLAYBITMAP = 19; // public static final byte MSG_DISPLAYBITMAP_ACK = 20; // // public static final byte MSG_CLEARDISPLAY = 21; // public static final byte MSG_CLEARDISPLAY_ACK = 22; // // public static final byte MSG_SETMENUSIZE = 23; // public static final byte MSG_SETMENUSIZE_ACK = 24; // // public static final byte MSG_GETMENUITEM = 25; // public static final byte MSG_GETMENUITEM_RESP = 26; // // public static final byte MSG_GETALERT = 27; // public static final byte MSG_GETALERT_RESP = 28; // // public static final byte MSG_NAVIGATION = 29; // public static final byte MSG_NAVIGATION_RESP = 30; // // public static final byte MSG_SETSTATUSBAR = 33; // public static final byte MSG_SETSTATUSBAR_ACK = 34; // // public static final byte MSG_GETMENUITEMS = 35; // // public static final byte MSG_SETMENUSETTINGS = 36; // public static final byte MSG_SETMENUSETTINGS_ACK = 37; // // public static final byte MSG_GETTIME = 38; // public static final byte MSG_GETTIME_RESP = 39; // // public static final byte MSG_SETLED = 40; // public static final byte MSG_SETLED_ACK = 41; // // public static final byte MSG_SETVIBRATE = 42; // public static final byte MSG_SETVIBRATE_ACK = 43; // // public static final byte MSG_ACK = 44; // // public static final byte MSG_SETSCREENMODE = 64; // public static final byte MSG_SETSCREENMODE_ACK = 65; // // public static final byte MSG_GETSCREENMODE = 66; // public static final byte MSG_GETSCREENMODE_RESP = 67; // // public static final int DEVICESTATUS_OFF = 0; // public static final int DEVICESTATUS_ON = 1; // public static final int DEVICESTATUS_MENU = 2; // // public static final byte RESULT_OK = 0; // public static final byte RESULT_ERROR = 1; // public static final byte RESULT_OOM = 2; // public static final byte RESULT_EXIT = 3; // public static final byte RESULT_CANCEL = 4; // // public static final int NAVACTION_PRESS = 0; // public static final int NAVACTION_LONGPRESS = 1; // public static final int NAVACTION_DOUBLEPRESS = 2; // // public static final int NAVTYPE_UP = 0; // public static final int NAVTYPE_DOWN = 1; // public static final int NAVTYPE_LEFT = 2; // public static final int NAVTYPE_RIGHT = 3; // public static final int NAVTYPE_SELECT = 4; // public static final int NAVTYPE_MENUSELECT = 5; // // public static final int ALERTACTION_CURRENT = 0; // public static final int ALERTACTION_FIRST = 1; // public static final int ALERTACTION_LAST = 2; // public static final int ALERTACTION_NEXT = 3; // public static final int ALERTACTION_PREV = 4; // // public static final int BRIGHTNESS_OFF = 48; // public static final int BRIGHTNESS_DIM = 49; // public static final int BRIGHTNESS_MAX = 50; // // public static final String CLIENT_SOFTWARE_VERSION = "0.0.3"; // // } // Path: src/net/sourcewalker/olv/messages/events/GetMenuItems.java import java.nio.ByteBuffer; import net.sourcewalker.olv.messages.LiveViewEvent; import net.sourcewalker.olv.messages.MessageConstants; package net.sourcewalker.olv.messages.events; public class GetMenuItems extends LiveViewEvent { public GetMenuItems() {
super(MessageConstants.MSG_GETMENUITEMS);
xperimental/OpenLiveView
src/net/sourcewalker/olv/LogViewActivity.java
// Path: src/net/sourcewalker/olv/data/LiveViewData.java // public final class LiveViewData { // // public static final String AUTHORITY = "net.sourcewalker.olv"; // // /** // * The "log" database contains a persistent log for the application. // * // * @author Xperimental // */ // public static final class Log implements BaseColumns { // // public static final Uri CONTENT_URI = Uri.parse("content://" // + AUTHORITY + "/log"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/net.sourcewalker.olv.log"; // // public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/net.sourcewalker.olv.log"; // // public static final String TABLE = "log"; // // public static final String TIMESTAMP = "time"; // // public static final String MESSAGE = "message"; // // public static final String DATETIME = "datetime"; // // public static final String SCHEMA = "CREATE TABLE " + TABLE + " (" // + _ID + " INTEGER PRIMARY KEY, " + TIMESTAMP + " INTEGER, " // + MESSAGE + " TEXT)"; // // public static final String[] DEFAULT_PROJECTION = new String[] { // _ID, // TIMESTAMP, // "DATETIME(" + TIMESTAMP // + " / 1000, 'unixepoch', 'localtime') AS " + DATETIME, // MESSAGE }; // // public static final String DEFAULT_ORDER = TIMESTAMP + " DESC, " + _ID // + " ASC"; // // } // // }
import net.sourcewalker.olv.data.LiveViewData; import android.app.ListActivity; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.widget.SimpleCursorAdapter;
package net.sourcewalker.olv; /** * Displays the log from the database to the user. * * @author Xperimental */ public class LogViewActivity extends ListActivity { /* * (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { super.onResume();
// Path: src/net/sourcewalker/olv/data/LiveViewData.java // public final class LiveViewData { // // public static final String AUTHORITY = "net.sourcewalker.olv"; // // /** // * The "log" database contains a persistent log for the application. // * // * @author Xperimental // */ // public static final class Log implements BaseColumns { // // public static final Uri CONTENT_URI = Uri.parse("content://" // + AUTHORITY + "/log"); // // public static final String CONTENT_TYPE = "vnd.android.cursor.dir/net.sourcewalker.olv.log"; // // public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/net.sourcewalker.olv.log"; // // public static final String TABLE = "log"; // // public static final String TIMESTAMP = "time"; // // public static final String MESSAGE = "message"; // // public static final String DATETIME = "datetime"; // // public static final String SCHEMA = "CREATE TABLE " + TABLE + " (" // + _ID + " INTEGER PRIMARY KEY, " + TIMESTAMP + " INTEGER, " // + MESSAGE + " TEXT)"; // // public static final String[] DEFAULT_PROJECTION = new String[] { // _ID, // TIMESTAMP, // "DATETIME(" + TIMESTAMP // + " / 1000, 'unixepoch', 'localtime') AS " + DATETIME, // MESSAGE }; // // public static final String DEFAULT_ORDER = TIMESTAMP + " DESC, " + _ID // + " ASC"; // // } // // } // Path: src/net/sourcewalker/olv/LogViewActivity.java import net.sourcewalker.olv.data.LiveViewData; import android.app.ListActivity; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.widget.SimpleCursorAdapter; package net.sourcewalker.olv; /** * Displays the log from the database to the user. * * @author Xperimental */ public class LogViewActivity extends ListActivity { /* * (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { super.onResume();
Cursor cursor = managedQuery(LiveViewData.Log.CONTENT_URI, null, null,
followwwind/javautils
src/main/java/com/wind/media/opencv/v3/HighGuiUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.wind.common.Constants; import org.opencv.core.*; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.objdetect.CascadeClassifier;
package com.wind.media.opencv.v3; /** * opencv HighGui工具类 * @author wind */ public class HighGuiUtil { static {
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/main/java/com/wind/media/opencv/v3/HighGuiUtil.java import com.wind.common.Constants; import org.opencv.core.*; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.objdetect.CascadeClassifier; package com.wind.media.opencv.v3; /** * opencv HighGui工具类 * @author wind */ public class HighGuiUtil { static {
System.loadLibrary(Constants.OPENCV_LIB_NAME_330);
followwwind/javautils
src/main/java/com/wind/media/code/ZxingUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.wind.common.Constants; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.HashMap; import java.util.Map;
package com.wind.media.code; /** * @Title: ZxingUtil * @Package com.wind.media * @Description: google zxing二维码工具类 * @author wind * @date 2018/9/15 15:29 * @version V1.0 */ public class ZxingUtil { /** * 设置二维码的参数 * @param content * @param width * @param height * @return */ private static BitMatrix getBitMatrix(String content, int width, int height){ /** * 设置二维码的参数 */ BitMatrix bitMatrix = null; try { Map<EncodeHintType, Object> hints = new HashMap<>(3); // 指定纠错等级 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/main/java/com/wind/media/code/ZxingUtil.java import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.wind.common.Constants; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; package com.wind.media.code; /** * @Title: ZxingUtil * @Package com.wind.media * @Description: google zxing二维码工具类 * @author wind * @date 2018/9/15 15:29 * @version V1.0 */ public class ZxingUtil { /** * 设置二维码的参数 * @param content * @param width * @param height * @return */ private static BitMatrix getBitMatrix(String content, int width, int height){ /** * 设置二维码的参数 */ BitMatrix bitMatrix = null; try { Map<EncodeHintType, Object> hints = new HashMap<>(3); // 指定纠错等级 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hints.put(EncodeHintType.CHARACTER_SET, Constants.UTF8);
followwwind/javautils
src/test/java/com/wind/media/Tess4jTest.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.wind.common.Constants; import org.junit.Test;
package com.wind.media; public class Tess4jTest { @Test public void test(){ /*String path = "src/main/resources/image/text.png"; System.out.println(take(path));*/ String ch = "src/main/resources/image/ch.png";
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/test/java/com/wind/media/Tess4jTest.java import com.wind.common.Constants; import org.junit.Test; package com.wind.media; public class Tess4jTest { @Test public void test(){ /*String path = "src/main/resources/image/text.png"; System.out.println(take(path));*/ String ch = "src/main/resources/image/ch.png";
System.out.println(Tess4jUtil.take(ch, "src/main/resources/tessdata", Constants.CHI_SIM));
followwwind/javautils
src/main/java/com/wind/network/http/ResourceUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.wind.common.Constants; import java.io.InputStream; import java.net.URL;
package com.wind.network.http; /** * @Title: ResourceUtil * @Package com.wind.resource * @Description: 资源文件加载工具类 * @author wind * @date 2018/10/11 10:46 * @version V1.0 */ public class ResourceUtil { /** * 获取资源文件的输入流 * @param fileName * @return */ public static InputStream getResFile(String fileName){ InputStream in = null; if(fileName != null){
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/main/java/com/wind/network/http/ResourceUtil.java import com.wind.common.Constants; import java.io.InputStream; import java.net.URL; package com.wind.network.http; /** * @Title: ResourceUtil * @Package com.wind.resource * @Description: 资源文件加载工具类 * @author wind * @date 2018/10/11 10:46 * @version V1.0 */ public class ResourceUtil { /** * 获取资源文件的输入流 * @param fileName * @return */ public static InputStream getResFile(String fileName){ InputStream in = null; if(fileName != null){
if(fileName.startsWith(Constants.FILE_SEPARATOR)){
followwwind/javautils
src/main/java/com/wind/ftl/FtlUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.wind.common.Constants; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import java.io.*; import java.util.HashMap; import java.util.Map;
package com.wind.ftl; /** * freeMarker工具生成类 * @author wind */ public class FtlUtil { /** * 生成文件 * @param freeMarker */ public static void genCode(FreeMarker freeMarker){ String fileDir = freeMarker.getFileDir(); String fileName = freeMarker.getFileName(); try( OutputStream fos = new FileOutputStream( new File(fileDir, fileName)); Writer out = new OutputStreamWriter(fos) ) { File dir = new File(fileDir); boolean sign = true; if(!dir.exists()){ sign = dir.mkdirs(); } if(sign){ Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(new File(freeMarker.getCfgDir()));
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/main/java/com/wind/ftl/FtlUtil.java import com.wind.common.Constants; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import java.io.*; import java.util.HashMap; import java.util.Map; package com.wind.ftl; /** * freeMarker工具生成类 * @author wind */ public class FtlUtil { /** * 生成文件 * @param freeMarker */ public static void genCode(FreeMarker freeMarker){ String fileDir = freeMarker.getFileDir(); String fileName = freeMarker.getFileName(); try( OutputStream fos = new FileOutputStream( new File(fileDir, fileName)); Writer out = new OutputStreamWriter(fos) ) { File dir = new File(fileDir); boolean sign = true; if(!dir.exists()){ sign = dir.mkdirs(); } if(sign){ Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(new File(freeMarker.getCfgDir()));
cfg.setDefaultEncoding(Constants.UTF8);
followwwind/javautils
src/main/java/com/wind/media/Tess4jUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.wind.common.Constants; import net.sourceforge.tess4j.ITesseract; import net.sourceforge.tess4j.Tesseract; import net.sourceforge.tess4j.TesseractException; import net.sourceforge.tess4j.util.LoadLibs; import java.io.File;
package com.wind.media; /** * @Title: Tess4jUtil * @Package com.wind.image.ocr.tesseract * @Description: tesseract for java, ocr(Optical Character Recognition,光学字符识别) * @author huanghy * @date 2018/10/12 18:28 * @version V1.0 */ public class Tess4jUtil { /** * 从图片中提取文字,默认设置英文字库,使用classpath目录下的训练库 * @param path * @return */ public static String take(String path){ // JNA Interface Mapping ITesseract instance = new Tesseract(); // JNA Direct Mapping // ITesseract instance = new Tesseract1(); File imageFile = new File(path); //In case you don't have your own tessdata, let it also be extracted for you //这样就能使用classpath目录下的训练库了 File tessDataFolder = LoadLibs.extractTessResources("tessdata"); //Set the tessdata path instance.setDatapath(tessDataFolder.getAbsolutePath()); //英文库识别数字比较准确
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/main/java/com/wind/media/Tess4jUtil.java import com.wind.common.Constants; import net.sourceforge.tess4j.ITesseract; import net.sourceforge.tess4j.Tesseract; import net.sourceforge.tess4j.TesseractException; import net.sourceforge.tess4j.util.LoadLibs; import java.io.File; package com.wind.media; /** * @Title: Tess4jUtil * @Package com.wind.image.ocr.tesseract * @Description: tesseract for java, ocr(Optical Character Recognition,光学字符识别) * @author huanghy * @date 2018/10/12 18:28 * @version V1.0 */ public class Tess4jUtil { /** * 从图片中提取文字,默认设置英文字库,使用classpath目录下的训练库 * @param path * @return */ public static String take(String path){ // JNA Interface Mapping ITesseract instance = new Tesseract(); // JNA Direct Mapping // ITesseract instance = new Tesseract1(); File imageFile = new File(path); //In case you don't have your own tessdata, let it also be extracted for you //这样就能使用classpath目录下的训练库了 File tessDataFolder = LoadLibs.extractTessResources("tessdata"); //Set the tessdata path instance.setDatapath(tessDataFolder.getAbsolutePath()); //英文库识别数字比较准确
instance.setLanguage(Constants.ENG);
followwwind/javautils
src/main/java/com/wind/xml/XmlUtil.java
// Path: src/main/java/com/wind/common/IoUtil.java // public class IoUtil { // // /** // * 关闭字节输入流 // * @param in // */ // public static void close(InputStream in){ // if(in != null){ // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // // /** // * 关闭字节输入输出流 // * @param in // * @param out // */ // public static void close(InputStream in, OutputStream out){ // close(in); // close(out); // } // // /** // * 关闭字符输入流 // * @param reader // */ // public static void close(Reader reader){ // if(reader != null){ // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭字符输出流 // * @param writer // */ // public static void close(Writer writer){ // if(writer != null){ // try { // writer.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭image输入流 // * @param iis // */ // public static void close(ImageInputStream iis){ // if(iis != null){ // try { // iis.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 批量关闭字节输入流 // * @param ins // */ // public static void close(InputStream... ins){ // Arrays.asList(ins).parallelStream().forEach(IoUtil::close); // } // // /** // * 批量关闭字节输出流 // * @param outs // */ // public static void close(OutputStream... outs){ // Arrays.asList(outs).parallelStream().forEach(IoUtil::close); // } // // /** // * 关闭字节输出流 // * @param out // */ // public static void close(OutputStream out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭XMLWriter输出流 // * @param out // */ // public static void close(XMLWriter out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // }
import com.wind.common.IoUtil; import org.dom4j.*; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import java.io.*; import java.util.Iterator; import java.util.List;
reader.read(new BufferedInputStream(new FileInputStream(new File(filePath)))); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void writeXml(String filePath, Document doc){ // 设置XML文档格式 OutputFormat outputFormat = OutputFormat.createPrettyPrint(); // 设置XML编码方式,即是用指定的编码方式保存XML文档到字符串(String),这里也可以指定为GBK或是ISO8859-1 outputFormat.setEncoding("UTF-8"); //是否生产xml头 outputFormat.setSuppressDeclaration(true); //设置是否缩进 outputFormat.setIndent(true); //以四个空格方式实现缩进 outputFormat.setIndent(" "); //设置是否换行 outputFormat.setNewlines(true); XMLWriter out = null; try{ out = new XMLWriter(new FileWriter(new File(filePath)), outputFormat); out.write(doc); }catch(IOException e){ e.printStackTrace(); } finally{
// Path: src/main/java/com/wind/common/IoUtil.java // public class IoUtil { // // /** // * 关闭字节输入流 // * @param in // */ // public static void close(InputStream in){ // if(in != null){ // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // // /** // * 关闭字节输入输出流 // * @param in // * @param out // */ // public static void close(InputStream in, OutputStream out){ // close(in); // close(out); // } // // /** // * 关闭字符输入流 // * @param reader // */ // public static void close(Reader reader){ // if(reader != null){ // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭字符输出流 // * @param writer // */ // public static void close(Writer writer){ // if(writer != null){ // try { // writer.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭image输入流 // * @param iis // */ // public static void close(ImageInputStream iis){ // if(iis != null){ // try { // iis.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 批量关闭字节输入流 // * @param ins // */ // public static void close(InputStream... ins){ // Arrays.asList(ins).parallelStream().forEach(IoUtil::close); // } // // /** // * 批量关闭字节输出流 // * @param outs // */ // public static void close(OutputStream... outs){ // Arrays.asList(outs).parallelStream().forEach(IoUtil::close); // } // // /** // * 关闭字节输出流 // * @param out // */ // public static void close(OutputStream out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭XMLWriter输出流 // * @param out // */ // public static void close(XMLWriter out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // Path: src/main/java/com/wind/xml/XmlUtil.java import com.wind.common.IoUtil; import org.dom4j.*; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import java.io.*; import java.util.Iterator; import java.util.List; reader.read(new BufferedInputStream(new FileInputStream(new File(filePath)))); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void writeXml(String filePath, Document doc){ // 设置XML文档格式 OutputFormat outputFormat = OutputFormat.createPrettyPrint(); // 设置XML编码方式,即是用指定的编码方式保存XML文档到字符串(String),这里也可以指定为GBK或是ISO8859-1 outputFormat.setEncoding("UTF-8"); //是否生产xml头 outputFormat.setSuppressDeclaration(true); //设置是否缩进 outputFormat.setIndent(true); //以四个空格方式实现缩进 outputFormat.setIndent(" "); //设置是否换行 outputFormat.setNewlines(true); XMLWriter out = null; try{ out = new XMLWriter(new FileWriter(new File(filePath)), outputFormat); out.write(doc); }catch(IOException e){ e.printStackTrace(); } finally{
IoUtil.close(out);
followwwind/javautils
src/main/java/com/wind/encrypt/AesUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.wind.common.Constants; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom;
package com.wind.encrypt; /** * AES加密工具类 * AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据 * @author wind */ public class AesUtil { public static final String AES_KEY = "AES"; /** * des加密 * @param str 待加密对象 * @param key 密钥 长度为8的倍数 * @return */ public static byte[] encrypt(String str, String key) { byte[] bytes = null; try { Cipher cipher = init(Cipher.ENCRYPT_MODE, key); if(cipher == null){ return new byte[]{}; }
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/main/java/com/wind/encrypt/AesUtil.java import com.wind.common.Constants; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; package com.wind.encrypt; /** * AES加密工具类 * AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据 * @author wind */ public class AesUtil { public static final String AES_KEY = "AES"; /** * des加密 * @param str 待加密对象 * @param key 密钥 长度为8的倍数 * @return */ public static byte[] encrypt(String str, String key) { byte[] bytes = null; try { Cipher cipher = init(Cipher.ENCRYPT_MODE, key); if(cipher == null){ return new byte[]{}; }
bytes = cipher.doFinal(str.getBytes(Constants.UTF8));
followwwind/javautils
src/main/java/com/wind/encrypt/CryptoUtil.java
// Path: src/main/java/com/wind/common/StringUtil.java // public class StringUtil { // // /** // * 判断字符串是否为null或空字符串 // * @param str // * @return // */ // public static boolean isNotBlank(String str){ // return str != null && !"".equals(str.trim()); // } // // // /** // * url编码 // * @param str // * @return // */ // public static String encodeUrl(String str){ // String s = null; // try { // s = URLEncoder.encode(str, Constants.UTF8); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // // return s; // } // // /** // * url解码 // * @param str // * @return // */ // public static String decodeUrl(String str){ // String s = null; // try { // s = URLDecoder.decode(str, Constants.UTF8); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return s; // } // // // /** // * 字符串分隔 StringTokenizer效率是三种分隔方法中最快的 // * @param str // * @param sign // * @return // */ // public static String[] split(String str, String sign){ // if(str == null){ // return new String[]{}; // } // StringTokenizer token = new StringTokenizer(str,sign); // String[] strArr = new String[token.countTokens()]; // int i = 0; // while(token.hasMoreElements()){ // strArr[i] = token.nextElement().toString(); // i++; // } // return strArr; // } // // /** // * 字符串拼接 // * @param sign // * @param strArr // * @return // */ // public static String joinStr(String sign, String... strArr){ // Optional<String> optional = Arrays.stream(strArr).filter(Objects::nonNull // ).reduce((a, b) -> a + sign + b); // return optional.orElse(""); // } // }
import com.wind.common.StringUtil; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException;
package com.wind.encrypt; /** * @Title: CryptoUtil * @Package com.wind.encrypt * @Description: PBKDF2 * @author wind * @date 2018/10/11 10:12 * @version V1.0 */ public class CryptoUtil { public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; /** * The following constants may be changed without breaking existing hashes. */ public static final int SALT_BYTE_SIZE = 24; public static final int HASH_BYTE_SIZE = 24; public static final int PBKDF2_ITERATIONS = 1000; public static final int ITERATION_INDEX = 0; public static final int SALT_INDEX = 1; public static final int PBKDF2_INDEX = 2; public static final int PWD_SALT_LEN = 2; /** * Returns a salted PBKDF2 hash of the password. * * @param password * the password to hash * @return a salted PBKDF2 hash of the password 数组第一个元素是密码,第二个元素是hash次数和随机盐 */ public static String[] createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Path: src/main/java/com/wind/common/StringUtil.java // public class StringUtil { // // /** // * 判断字符串是否为null或空字符串 // * @param str // * @return // */ // public static boolean isNotBlank(String str){ // return str != null && !"".equals(str.trim()); // } // // // /** // * url编码 // * @param str // * @return // */ // public static String encodeUrl(String str){ // String s = null; // try { // s = URLEncoder.encode(str, Constants.UTF8); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // // return s; // } // // /** // * url解码 // * @param str // * @return // */ // public static String decodeUrl(String str){ // String s = null; // try { // s = URLDecoder.decode(str, Constants.UTF8); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return s; // } // // // /** // * 字符串分隔 StringTokenizer效率是三种分隔方法中最快的 // * @param str // * @param sign // * @return // */ // public static String[] split(String str, String sign){ // if(str == null){ // return new String[]{}; // } // StringTokenizer token = new StringTokenizer(str,sign); // String[] strArr = new String[token.countTokens()]; // int i = 0; // while(token.hasMoreElements()){ // strArr[i] = token.nextElement().toString(); // i++; // } // return strArr; // } // // /** // * 字符串拼接 // * @param sign // * @param strArr // * @return // */ // public static String joinStr(String sign, String... strArr){ // Optional<String> optional = Arrays.stream(strArr).filter(Objects::nonNull // ).reduce((a, b) -> a + sign + b); // return optional.orElse(""); // } // } // Path: src/main/java/com/wind/encrypt/CryptoUtil.java import com.wind.common.StringUtil; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; package com.wind.encrypt; /** * @Title: CryptoUtil * @Package com.wind.encrypt * @Description: PBKDF2 * @author wind * @date 2018/10/11 10:12 * @version V1.0 */ public class CryptoUtil { public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; /** * The following constants may be changed without breaking existing hashes. */ public static final int SALT_BYTE_SIZE = 24; public static final int HASH_BYTE_SIZE = 24; public static final int PBKDF2_ITERATIONS = 1000; public static final int ITERATION_INDEX = 0; public static final int SALT_INDEX = 1; public static final int PBKDF2_INDEX = 2; public static final int PWD_SALT_LEN = 2; /** * Returns a salted PBKDF2 hash of the password. * * @param password * the password to hash * @return a salted PBKDF2 hash of the password 数组第一个元素是密码,第二个元素是hash次数和随机盐 */ public static String[] createHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
if (!StringUtil.isNotBlank(password)) {
followwwind/javautils
src/main/java/com/wind/media/opencv/v2/HighGuiUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.wind.common.Constants; import org.opencv.core.*; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier;
package com.wind.media.opencv.v2; /** * opencv HighGui工具类 * @author wind */ public class HighGuiUtil { static {
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/main/java/com/wind/media/opencv/v2/HighGuiUtil.java import com.wind.common.Constants; import org.opencv.core.*; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; import org.opencv.objdetect.CascadeClassifier; package com.wind.media.opencv.v2; /** * opencv HighGui工具类 * @author wind */ public class HighGuiUtil { static {
System.loadLibrary(Constants.OPENCV_LIB_NAME_246);
followwwind/javautils
src/main/java/com/wind/compress/GZipUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // // Path: src/main/java/com/wind/common/IoUtil.java // public class IoUtil { // // /** // * 关闭字节输入流 // * @param in // */ // public static void close(InputStream in){ // if(in != null){ // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // // /** // * 关闭字节输入输出流 // * @param in // * @param out // */ // public static void close(InputStream in, OutputStream out){ // close(in); // close(out); // } // // /** // * 关闭字符输入流 // * @param reader // */ // public static void close(Reader reader){ // if(reader != null){ // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭字符输出流 // * @param writer // */ // public static void close(Writer writer){ // if(writer != null){ // try { // writer.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭image输入流 // * @param iis // */ // public static void close(ImageInputStream iis){ // if(iis != null){ // try { // iis.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 批量关闭字节输入流 // * @param ins // */ // public static void close(InputStream... ins){ // Arrays.asList(ins).parallelStream().forEach(IoUtil::close); // } // // /** // * 批量关闭字节输出流 // * @param outs // */ // public static void close(OutputStream... outs){ // Arrays.asList(outs).parallelStream().forEach(IoUtil::close); // } // // /** // * 关闭字节输出流 // * @param out // */ // public static void close(OutputStream out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭XMLWriter输出流 // * @param out // */ // public static void close(XMLWriter out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // }
import com.wind.common.Constants; import com.wind.common.IoUtil; import java.io.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream;
package com.wind.compress; /** * @Title: GZipUtil * @Package com.wind.compress * @Description: GZIP压缩工具类 * @author wind * @date 2018/10/12 17:47 * @version V1.0 */ public class GZipUtil { /** * 文件压缩 * @param source 待压缩文件路径 * @param target */ public static void compress(String source, String target){ compress(new File(source), target); } /** * 文件压缩 * @param source File 待压缩 * @param target */ public static void compress(File source, String target){ FileInputStream fis = null; try { fis = new FileInputStream(source); File targetFile = new File(target); if(targetFile.isFile()){ System.err.println("target不能是文件,否则压缩失败"); return; }
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // // Path: src/main/java/com/wind/common/IoUtil.java // public class IoUtil { // // /** // * 关闭字节输入流 // * @param in // */ // public static void close(InputStream in){ // if(in != null){ // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // // /** // * 关闭字节输入输出流 // * @param in // * @param out // */ // public static void close(InputStream in, OutputStream out){ // close(in); // close(out); // } // // /** // * 关闭字符输入流 // * @param reader // */ // public static void close(Reader reader){ // if(reader != null){ // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭字符输出流 // * @param writer // */ // public static void close(Writer writer){ // if(writer != null){ // try { // writer.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭image输入流 // * @param iis // */ // public static void close(ImageInputStream iis){ // if(iis != null){ // try { // iis.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 批量关闭字节输入流 // * @param ins // */ // public static void close(InputStream... ins){ // Arrays.asList(ins).parallelStream().forEach(IoUtil::close); // } // // /** // * 批量关闭字节输出流 // * @param outs // */ // public static void close(OutputStream... outs){ // Arrays.asList(outs).parallelStream().forEach(IoUtil::close); // } // // /** // * 关闭字节输出流 // * @param out // */ // public static void close(OutputStream out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭XMLWriter输出流 // * @param out // */ // public static void close(XMLWriter out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // Path: src/main/java/com/wind/compress/GZipUtil.java import com.wind.common.Constants; import com.wind.common.IoUtil; import java.io.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; package com.wind.compress; /** * @Title: GZipUtil * @Package com.wind.compress * @Description: GZIP压缩工具类 * @author wind * @date 2018/10/12 17:47 * @version V1.0 */ public class GZipUtil { /** * 文件压缩 * @param source 待压缩文件路径 * @param target */ public static void compress(String source, String target){ compress(new File(source), target); } /** * 文件压缩 * @param source File 待压缩 * @param target */ public static void compress(File source, String target){ FileInputStream fis = null; try { fis = new FileInputStream(source); File targetFile = new File(target); if(targetFile.isFile()){ System.err.println("target不能是文件,否则压缩失败"); return; }
target += (source.getName() + Constants.FILE_GZ);
followwwind/javautils
src/test/java/com/wind/resource/ResourceTest.java
// Path: src/main/java/com/wind/network/http/ResourceUtil.java // public class ResourceUtil { // // /** // * 获取资源文件的输入流 // * @param fileName // * @return // */ // public static InputStream getResFile(String fileName){ // InputStream in = null; // if(fileName != null){ // if(fileName.startsWith(Constants.FILE_SEPARATOR)){ // in = ResourceUtil.class.getResourceAsStream(fileName); // }else{ // in = ClassLoader.getSystemClassLoader().getResourceAsStream(fileName); // } // } // return in; // } // // /** // * 获取资源文件的url // * @param fileName // * @return // */ // public static URL getUrlFile(String fileName){ // URL url = null; // if(fileName != null){ // if(fileName.startsWith(Constants.FILE_SEPARATOR)){ // url = ResourceUtil.class.getResource(fileName); // }else{ // url = ClassLoader.getSystemClassLoader().getResource(fileName); // } // } // return url; // } // // // /** // * 获取class类的编译路径 // * @return // */ // public static String getClassPath(){ // URL url = Thread.currentThread().getContextClassLoader().getResource(Constants.BLANK_STR); // return url != null ? url.getPath() : ""; // } // // /** // * 获取项目的路径 // * @return // */ // public static String getProjectPath(){ // return System.getProperty(Constants.USER_DIR); // } // }
import com.wind.network.http.ResourceUtil; import org.junit.Test; import java.net.URL;
package com.wind.resource; public class ResourceTest { @Test public void test(){
// Path: src/main/java/com/wind/network/http/ResourceUtil.java // public class ResourceUtil { // // /** // * 获取资源文件的输入流 // * @param fileName // * @return // */ // public static InputStream getResFile(String fileName){ // InputStream in = null; // if(fileName != null){ // if(fileName.startsWith(Constants.FILE_SEPARATOR)){ // in = ResourceUtil.class.getResourceAsStream(fileName); // }else{ // in = ClassLoader.getSystemClassLoader().getResourceAsStream(fileName); // } // } // return in; // } // // /** // * 获取资源文件的url // * @param fileName // * @return // */ // public static URL getUrlFile(String fileName){ // URL url = null; // if(fileName != null){ // if(fileName.startsWith(Constants.FILE_SEPARATOR)){ // url = ResourceUtil.class.getResource(fileName); // }else{ // url = ClassLoader.getSystemClassLoader().getResource(fileName); // } // } // return url; // } // // // /** // * 获取class类的编译路径 // * @return // */ // public static String getClassPath(){ // URL url = Thread.currentThread().getContextClassLoader().getResource(Constants.BLANK_STR); // return url != null ? url.getPath() : ""; // } // // /** // * 获取项目的路径 // * @return // */ // public static String getProjectPath(){ // return System.getProperty(Constants.USER_DIR); // } // } // Path: src/test/java/com/wind/resource/ResourceTest.java import com.wind.network.http.ResourceUtil; import org.junit.Test; import java.net.URL; package com.wind.resource; public class ResourceTest { @Test public void test(){
URL url = ResourceUtil.getUrlFile("image/code.png");
followwwind/javautils
src/test/java/com/wind/media/HighGuiTest.java
// Path: src/main/java/com/wind/media/opencv/v3/HighGuiUtil.java // public class HighGuiUtil { // // static { // System.loadLibrary(Constants.OPENCV_LIB_NAME_330); // } // // /** // * 获取人脸范围 // * @param fileName // * @return // */ // public static MatOfRect takeFace(String fileName) { // CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml"); // Mat image = Imgcodecs.imread(fileName); // MatOfRect faceDetections = new MatOfRect(); // // 指定人脸识别的最大和最小像素范围 // Size minSize = new Size(120, 120); // Size maxSize = new Size(250, 250); // // 参数设置为scaleFactor=1.1f, minNeighbors=4, flags=0 以此来增加识别人脸的正确率 // faceDetector.detectMultiScale(image, faceDetections, 1.1f, 4, 0, // minSize, maxSize); // return faceDetections; // } // // /** // * Detects faces in an image, draws boxes around them, and writes the results // * @param fileName // * @param destName // */ // public static void drawRect(String fileName, String destName){ // Mat image = Imgcodecs.imread(fileName); // // Create a face detector from the cascade file in the resources // // directory. // CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml"); // // Detect faces in the image. // // MatOfRect is a special container class for Rect. // MatOfRect faceDetections = new MatOfRect(); // faceDetector.detectMultiScale(image, faceDetections); // // Draw a bounding box around each face. // for (Rect rect : faceDetections.toArray()) { // Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, // rect.y + rect.height), new Scalar(0, 255, 0)); // } // // Imgcodecs.imwrite(destName, image); // // } // }
import com.wind.media.opencv.v3.HighGuiUtil; import org.junit.Test;
package com.wind.media; public class HighGuiTest { @Test public void test(){ String fileName = "src/main/resources/image/face.jpg"; String destName = "src/main/resources/image/face2.jpg";
// Path: src/main/java/com/wind/media/opencv/v3/HighGuiUtil.java // public class HighGuiUtil { // // static { // System.loadLibrary(Constants.OPENCV_LIB_NAME_330); // } // // /** // * 获取人脸范围 // * @param fileName // * @return // */ // public static MatOfRect takeFace(String fileName) { // CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml"); // Mat image = Imgcodecs.imread(fileName); // MatOfRect faceDetections = new MatOfRect(); // // 指定人脸识别的最大和最小像素范围 // Size minSize = new Size(120, 120); // Size maxSize = new Size(250, 250); // // 参数设置为scaleFactor=1.1f, minNeighbors=4, flags=0 以此来增加识别人脸的正确率 // faceDetector.detectMultiScale(image, faceDetections, 1.1f, 4, 0, // minSize, maxSize); // return faceDetections; // } // // /** // * Detects faces in an image, draws boxes around them, and writes the results // * @param fileName // * @param destName // */ // public static void drawRect(String fileName, String destName){ // Mat image = Imgcodecs.imread(fileName); // // Create a face detector from the cascade file in the resources // // directory. // CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml"); // // Detect faces in the image. // // MatOfRect is a special container class for Rect. // MatOfRect faceDetections = new MatOfRect(); // faceDetector.detectMultiScale(image, faceDetections); // // Draw a bounding box around each face. // for (Rect rect : faceDetections.toArray()) { // Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, // rect.y + rect.height), new Scalar(0, 255, 0)); // } // // Imgcodecs.imwrite(destName, image); // // } // } // Path: src/test/java/com/wind/media/HighGuiTest.java import com.wind.media.opencv.v3.HighGuiUtil; import org.junit.Test; package com.wind.media; public class HighGuiTest { @Test public void test(){ String fileName = "src/main/resources/image/face.jpg"; String destName = "src/main/resources/image/face2.jpg";
HighGuiUtil.drawRect(fileName, destName);
followwwind/javautils
src/main/java/com/wind/encrypt/RsaUtil.java
// Path: src/main/java/com/wind/common/StringUtil.java // public class StringUtil { // // /** // * 判断字符串是否为null或空字符串 // * @param str // * @return // */ // public static boolean isNotBlank(String str){ // return str != null && !"".equals(str.trim()); // } // // // /** // * url编码 // * @param str // * @return // */ // public static String encodeUrl(String str){ // String s = null; // try { // s = URLEncoder.encode(str, Constants.UTF8); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // // return s; // } // // /** // * url解码 // * @param str // * @return // */ // public static String decodeUrl(String str){ // String s = null; // try { // s = URLDecoder.decode(str, Constants.UTF8); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return s; // } // // // /** // * 字符串分隔 StringTokenizer效率是三种分隔方法中最快的 // * @param str // * @param sign // * @return // */ // public static String[] split(String str, String sign){ // if(str == null){ // return new String[]{}; // } // StringTokenizer token = new StringTokenizer(str,sign); // String[] strArr = new String[token.countTokens()]; // int i = 0; // while(token.hasMoreElements()){ // strArr[i] = token.nextElement().toString(); // i++; // } // return strArr; // } // // /** // * 字符串拼接 // * @param sign // * @param strArr // * @return // */ // public static String joinStr(String sign, String... strArr){ // Optional<String> optional = Arrays.stream(strArr).filter(Objects::nonNull // ).reduce((a, b) -> a + sign + b); // return optional.orElse(""); // } // }
import com.wind.common.StringUtil; import org.apache.commons.codec.binary.Base64; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.*;
Map<String, String> keyMap = new HashMap<>(2); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGenerator.initialize(size); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded())); keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded())); return keyMap; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return keyMap; } /** * 生成签名 * @param privateKey * @param content * @return */ public static String genSign(String privateKey, String content, String signType, String charset){ String sign = ""; try { PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey key = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Signature signature = Signature.getInstance(signType); signature.initSign(key);
// Path: src/main/java/com/wind/common/StringUtil.java // public class StringUtil { // // /** // * 判断字符串是否为null或空字符串 // * @param str // * @return // */ // public static boolean isNotBlank(String str){ // return str != null && !"".equals(str.trim()); // } // // // /** // * url编码 // * @param str // * @return // */ // public static String encodeUrl(String str){ // String s = null; // try { // s = URLEncoder.encode(str, Constants.UTF8); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // // return s; // } // // /** // * url解码 // * @param str // * @return // */ // public static String decodeUrl(String str){ // String s = null; // try { // s = URLDecoder.decode(str, Constants.UTF8); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return s; // } // // // /** // * 字符串分隔 StringTokenizer效率是三种分隔方法中最快的 // * @param str // * @param sign // * @return // */ // public static String[] split(String str, String sign){ // if(str == null){ // return new String[]{}; // } // StringTokenizer token = new StringTokenizer(str,sign); // String[] strArr = new String[token.countTokens()]; // int i = 0; // while(token.hasMoreElements()){ // strArr[i] = token.nextElement().toString(); // i++; // } // return strArr; // } // // /** // * 字符串拼接 // * @param sign // * @param strArr // * @return // */ // public static String joinStr(String sign, String... strArr){ // Optional<String> optional = Arrays.stream(strArr).filter(Objects::nonNull // ).reduce((a, b) -> a + sign + b); // return optional.orElse(""); // } // } // Path: src/main/java/com/wind/encrypt/RsaUtil.java import com.wind.common.StringUtil; import org.apache.commons.codec.binary.Base64; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.*; Map<String, String> keyMap = new HashMap<>(2); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGenerator.initialize(size); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded())); keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded())); return keyMap; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return keyMap; } /** * 生成签名 * @param privateKey * @param content * @return */ public static String genSign(String privateKey, String content, String signType, String charset){ String sign = ""; try { PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey key = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Signature signature = Signature.getInstance(signType); signature.initSign(key);
if(StringUtil.isNotBlank(charset)){
followwwind/javautils
src/main/java/com/wind/encrypt/Md5Util.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.wind.common.Constants; import org.apache.commons.codec.binary.Hex; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;
package com.wind.encrypt; /** * md5加密工具类 * MD5的全称是Message-Digest Algorithm 5(信息-摘要算法) * 默认为128bit * @author wind */ public class Md5Util { public static final String MD5_KEY = "MD5"; public static final String SHA_KEY = "SHA1"; /** * md5加密 * @param str * @param key MD5 SHA1 * @return */ public static String getMD5Str(String str, String key){ String s = ""; try { MessageDigest md = MessageDigest.getInstance(key);
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/main/java/com/wind/encrypt/Md5Util.java import com.wind.common.Constants; import org.apache.commons.codec.binary.Hex; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; package com.wind.encrypt; /** * md5加密工具类 * MD5的全称是Message-Digest Algorithm 5(信息-摘要算法) * 默认为128bit * @author wind */ public class Md5Util { public static final String MD5_KEY = "MD5"; public static final String SHA_KEY = "SHA1"; /** * md5加密 * @param str * @param key MD5 SHA1 * @return */ public static String getMD5Str(String str, String key){ String s = ""; try { MessageDigest md = MessageDigest.getInstance(key);
s = Hex.encodeHexString(md.digest(str.getBytes(Constants.UTF8)));
followwwind/javautils
src/main/java/com/wind/media/ImageUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // }
import com.wind.common.Constants; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator;
package com.wind.media; /** * opencv图像处理工具类 * @author wind */ public class ImageUtil { /** * 读取图片,获取BufferedImage对象 * @param fileName * @return */ public static BufferedImage getImage(String fileName){ File picture = new File(fileName); BufferedImage sourceImg = null; try { sourceImg = ImageIO.read(new FileInputStream(picture)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sourceImg; } /** * 读取图片,获取ImageReader对象 * @param fileName * @return */ public static ImageReader getImageReader(String fileName){ if(fileName != null){ String suffix = ""; for(String str : ImageIO.getReaderFormatNames()){
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // Path: src/main/java/com/wind/media/ImageUtil.java import com.wind.common.Constants; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; package com.wind.media; /** * opencv图像处理工具类 * @author wind */ public class ImageUtil { /** * 读取图片,获取BufferedImage对象 * @param fileName * @return */ public static BufferedImage getImage(String fileName){ File picture = new File(fileName); BufferedImage sourceImg = null; try { sourceImg = ImageIO.read(new FileInputStream(picture)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sourceImg; } /** * 读取图片,获取ImageReader对象 * @param fileName * @return */ public static ImageReader getImageReader(String fileName){ if(fileName != null){ String suffix = ""; for(String str : ImageIO.getReaderFormatNames()){
if(fileName.lastIndexOf(Constants.POINT_STR + str) > 0){
followwwind/javautils
src/test/java/com/wind/reflect/AsmTest.java
// Path: src/test/java/com/wind/AAA.java // public class AAA { // /** // * 状态码 // */ // @Resource // private Integer code; // /** // * 消息说明 // */ // private String msg; // // /** // * 系统当前时间,GTM时间戳 // */ // private Long timestamp; // // public Integer getCode() { // return code; // } // // public void setCode(Integer code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Long getTimestamp() { // return timestamp; // } // // public void setTimestamp(Long timestamp) { // this.timestamp = timestamp; // } // }
import com.wind.AAA; import org.junit.Test; import org.objectweb.asm.*; import java.io.IOException;
return null; } public void visitAttribute(Attribute attribute) { } public void visitInnerClass(String name, String outerName, String innerName, int access) { } public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { System.out.println(name + "-" + desc + "-" + signature + "-" + value); return null; } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { // System.out.println(name); return null; } public void visitEnd() { System.out.println("-------------end------------"); } }, 0); } @Test public void write() throws IOException {
// Path: src/test/java/com/wind/AAA.java // public class AAA { // /** // * 状态码 // */ // @Resource // private Integer code; // /** // * 消息说明 // */ // private String msg; // // /** // * 系统当前时间,GTM时间戳 // */ // private Long timestamp; // // public Integer getCode() { // return code; // } // // public void setCode(Integer code) { // this.code = code; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public Long getTimestamp() { // return timestamp; // } // // public void setTimestamp(Long timestamp) { // this.timestamp = timestamp; // } // } // Path: src/test/java/com/wind/reflect/AsmTest.java import com.wind.AAA; import org.junit.Test; import org.objectweb.asm.*; import java.io.IOException; return null; } public void visitAttribute(Attribute attribute) { } public void visitInnerClass(String name, String outerName, String innerName, int access) { } public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { System.out.println(name + "-" + desc + "-" + signature + "-" + value); return null; } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { // System.out.println(name); return null; } public void visitEnd() { System.out.println("-------------end------------"); } }, 0); } @Test public void write() throws IOException {
AAA a = new AAA();
followwwind/javautils
src/main/java/com/wind/compress/ZipUtil.java
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // // Path: src/main/java/com/wind/common/IoUtil.java // public class IoUtil { // // /** // * 关闭字节输入流 // * @param in // */ // public static void close(InputStream in){ // if(in != null){ // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // // /** // * 关闭字节输入输出流 // * @param in // * @param out // */ // public static void close(InputStream in, OutputStream out){ // close(in); // close(out); // } // // /** // * 关闭字符输入流 // * @param reader // */ // public static void close(Reader reader){ // if(reader != null){ // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭字符输出流 // * @param writer // */ // public static void close(Writer writer){ // if(writer != null){ // try { // writer.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭image输入流 // * @param iis // */ // public static void close(ImageInputStream iis){ // if(iis != null){ // try { // iis.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 批量关闭字节输入流 // * @param ins // */ // public static void close(InputStream... ins){ // Arrays.asList(ins).parallelStream().forEach(IoUtil::close); // } // // /** // * 批量关闭字节输出流 // * @param outs // */ // public static void close(OutputStream... outs){ // Arrays.asList(outs).parallelStream().forEach(IoUtil::close); // } // // /** // * 关闭字节输出流 // * @param out // */ // public static void close(OutputStream out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭XMLWriter输出流 // * @param out // */ // public static void close(XMLWriter out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // }
import com.wind.common.Constants; import com.wind.common.IoUtil; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream;
package com.wind.compress; /** * 通过Java的Zip输入输出流实现压缩和解压文件 * @author wind */ public class ZipUtil { /** * 压缩文件 * 若压缩文件,请指定目标文件目录和目标文件名 * @param source 源文件路径 * @param target 目标文件路径 */ public static void zip(String source, String target) { File sourceFile = new File(source); if (sourceFile.exists()) { File targetFile = new File(target); if(targetFile.isDirectory()){
// Path: src/main/java/com/wind/common/Constants.java // public interface Constants { // // /**********************************************分隔符常量************************************************/ // // String POINT_STR = "."; // // String BLANK_STR = ""; // // String SPACE_STR = " "; // // String NEWLINE_STR = "\n"; // // String SYS_SEPARATOR = File.separator; // // String FILE_SEPARATOR = "/"; // // String BRACKET_LEFT = "["; // // String BRACKET_RIGHT = "]"; // // String UNDERLINE = "_"; // // String MINUS_STR = "-"; // // // // /**********************************************编码格式************************************************/ // // String UTF8 = "UTF-8"; // // // /**********************************************文件后缀************************************************/ // // String EXCEL_XLS = ".xls"; // // String EXCEL_XLSX = ".xlsx"; // // String IMAGE_PNG = "png"; // // String IMAGE_JPG = "jpg"; // // String FILE_ZIP = ".zip"; // String FILE_GZ = ".gz"; // // // /**********************************************io流************************************************/ // // int BUFFER_1024 = 1024; // // int BUFFER_512 = 512; // // String USER_DIR = "user.dir"; // // /**********************************************tesseract for java语言字库************************************************/ // // String ENG = "eng"; // // String CHI_SIM = "chi_sim"; // // // /**********************************************opencv************************************************/ // String OPENCV_LIB_NAME_246 = "libs/x64/opencv_java246"; // // String OPENCV_LIB_NAME_330 = "libs/x64/opencv_java330"; // } // // Path: src/main/java/com/wind/common/IoUtil.java // public class IoUtil { // // /** // * 关闭字节输入流 // * @param in // */ // public static void close(InputStream in){ // if(in != null){ // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // // /** // * 关闭字节输入输出流 // * @param in // * @param out // */ // public static void close(InputStream in, OutputStream out){ // close(in); // close(out); // } // // /** // * 关闭字符输入流 // * @param reader // */ // public static void close(Reader reader){ // if(reader != null){ // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭字符输出流 // * @param writer // */ // public static void close(Writer writer){ // if(writer != null){ // try { // writer.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭image输入流 // * @param iis // */ // public static void close(ImageInputStream iis){ // if(iis != null){ // try { // iis.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 批量关闭字节输入流 // * @param ins // */ // public static void close(InputStream... ins){ // Arrays.asList(ins).parallelStream().forEach(IoUtil::close); // } // // /** // * 批量关闭字节输出流 // * @param outs // */ // public static void close(OutputStream... outs){ // Arrays.asList(outs).parallelStream().forEach(IoUtil::close); // } // // /** // * 关闭字节输出流 // * @param out // */ // public static void close(OutputStream out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭XMLWriter输出流 // * @param out // */ // public static void close(XMLWriter out){ // if(out != null){ // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // Path: src/main/java/com/wind/compress/ZipUtil.java import com.wind.common.Constants; import com.wind.common.IoUtil; import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; package com.wind.compress; /** * 通过Java的Zip输入输出流实现压缩和解压文件 * @author wind */ public class ZipUtil { /** * 压缩文件 * 若压缩文件,请指定目标文件目录和目标文件名 * @param source 源文件路径 * @param target 目标文件路径 */ public static void zip(String source, String target) { File sourceFile = new File(source); if (sourceFile.exists()) { File targetFile = new File(target); if(targetFile.isDirectory()){
String zipName = sourceFile.getName() + Constants.FILE_ZIP;
wequick/Small
Android/Sample/app.mine/src/main/java/net/wequick/example/small/app/mine/MainFragment.java
// Path: Android/Sample/jni_plugin/src/main/java/com/example/hellojni/HelloPluginJni.java // public final class HelloPluginJni // { // /* A native method that is implemented by the // * 'hello-jni' native library, which is packaged // * with this application. // */ // public static native String stringFromJNI(); // // static { // System.loadLibrary("hello-plugin-jni"); // } // } // // Path: Android/Sample/lib.utils/src/main/java/net/wequick/example/small/lib/utils/UIUtils.java // public class UIUtils { // public static void showToast(Context context, String tips) { // Toast toast = Toast.makeText(context, "lib.utils: " + tips, Toast.LENGTH_SHORT); // toast.show(); // } // // public static void alert(Context context, String tips) { // AlertDialog dlg = new AlertDialog.Builder(context) // .setMessage("lib.utils: " + tips) // .setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }) // .create(); // dlg.show(); // } // }
import android.app.Activity; import android.content.Intent; import android.support.annotation.Keep; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.hellojni.HelloPluginJni; import com.example.mylib.Greet; import net.wequick.example.small.lib.utils.UIUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import butterknife.BindView; import butterknife.ButterKnife;
try { InputStream is = getResources().getAssets().open("greet.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String greet = br.readLine(); is.close(); TextView tvAssets = (TextView) rootView.findViewById(R.id.assets_label); tvAssets.setText("assets/greet.txt: " + greet); is = getResources().openRawResource(R.raw.greet); br = new BufferedReader(new InputStreamReader(is)); greet = br.readLine(); is.close(); TextView tvRaw = (TextView) rootView.findViewById(R.id.raw_label); tvRaw.setText("res/raw/greet.txt: " + greet); is = getResources().openRawResource(R.raw.mq_new_message); System.out.println("### " + is.available()); is.close(); } catch (IOException e) { e.printStackTrace(); } // TextView tvLib = (TextView) rootView.findViewById(R.id.lib_label); tvLib.setText(Greet.hello() + " (ButterKnife 8)"); TextView tvJni = (TextView) rootView.findViewById(R.id.jni_label);
// Path: Android/Sample/jni_plugin/src/main/java/com/example/hellojni/HelloPluginJni.java // public final class HelloPluginJni // { // /* A native method that is implemented by the // * 'hello-jni' native library, which is packaged // * with this application. // */ // public static native String stringFromJNI(); // // static { // System.loadLibrary("hello-plugin-jni"); // } // } // // Path: Android/Sample/lib.utils/src/main/java/net/wequick/example/small/lib/utils/UIUtils.java // public class UIUtils { // public static void showToast(Context context, String tips) { // Toast toast = Toast.makeText(context, "lib.utils: " + tips, Toast.LENGTH_SHORT); // toast.show(); // } // // public static void alert(Context context, String tips) { // AlertDialog dlg = new AlertDialog.Builder(context) // .setMessage("lib.utils: " + tips) // .setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }) // .create(); // dlg.show(); // } // } // Path: Android/Sample/app.mine/src/main/java/net/wequick/example/small/app/mine/MainFragment.java import android.app.Activity; import android.content.Intent; import android.support.annotation.Keep; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.hellojni.HelloPluginJni; import com.example.mylib.Greet; import net.wequick.example.small.lib.utils.UIUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import butterknife.BindView; import butterknife.ButterKnife; try { InputStream is = getResources().getAssets().open("greet.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String greet = br.readLine(); is.close(); TextView tvAssets = (TextView) rootView.findViewById(R.id.assets_label); tvAssets.setText("assets/greet.txt: " + greet); is = getResources().openRawResource(R.raw.greet); br = new BufferedReader(new InputStreamReader(is)); greet = br.readLine(); is.close(); TextView tvRaw = (TextView) rootView.findViewById(R.id.raw_label); tvRaw.setText("res/raw/greet.txt: " + greet); is = getResources().openRawResource(R.raw.mq_new_message); System.out.println("### " + is.available()); is.close(); } catch (IOException e) { e.printStackTrace(); } // TextView tvLib = (TextView) rootView.findViewById(R.id.lib_label); tvLib.setText(Greet.hello() + " (ButterKnife 8)"); TextView tvJni = (TextView) rootView.findViewById(R.id.jni_label);
tvJni.setText(HelloPluginJni.stringFromJNI());
wequick/Small
Android/Sample/app.mine/src/main/java/net/wequick/example/small/app/mine/MainFragment.java
// Path: Android/Sample/jni_plugin/src/main/java/com/example/hellojni/HelloPluginJni.java // public final class HelloPluginJni // { // /* A native method that is implemented by the // * 'hello-jni' native library, which is packaged // * with this application. // */ // public static native String stringFromJNI(); // // static { // System.loadLibrary("hello-plugin-jni"); // } // } // // Path: Android/Sample/lib.utils/src/main/java/net/wequick/example/small/lib/utils/UIUtils.java // public class UIUtils { // public static void showToast(Context context, String tips) { // Toast toast = Toast.makeText(context, "lib.utils: " + tips, Toast.LENGTH_SHORT); // toast.show(); // } // // public static void alert(Context context, String tips) { // AlertDialog dlg = new AlertDialog.Builder(context) // .setMessage("lib.utils: " + tips) // .setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }) // .create(); // dlg.show(); // } // }
import android.app.Activity; import android.content.Intent; import android.support.annotation.Keep; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.hellojni.HelloPluginJni; import com.example.mylib.Greet; import net.wequick.example.small.lib.utils.UIUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import butterknife.BindView; import butterknife.ButterKnife;
// TextView tvLib = (TextView) rootView.findViewById(R.id.lib_label); tvLib.setText(Greet.hello() + " (ButterKnife 8)"); TextView tvJni = (TextView) rootView.findViewById(R.id.jni_label); tvJni.setText(HelloPluginJni.stringFromJNI()); button = (Button) rootView.findViewById(R.id.play_video_button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainFragment.this.getContext(), VideoActivity.class); startActivity(intent); } }); return rootView; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != Activity.RESULT_OK) return; switch (requestCode) { case REQUEST_CODE_COLOR: Button button = (Button) getView().findViewById(R.id.inter_start_button); button.setText(getText(R.string.inter_start) + ": " + data.getStringExtra("color")); break; case REQUEST_CODE_CONTACTS:
// Path: Android/Sample/jni_plugin/src/main/java/com/example/hellojni/HelloPluginJni.java // public final class HelloPluginJni // { // /* A native method that is implemented by the // * 'hello-jni' native library, which is packaged // * with this application. // */ // public static native String stringFromJNI(); // // static { // System.loadLibrary("hello-plugin-jni"); // } // } // // Path: Android/Sample/lib.utils/src/main/java/net/wequick/example/small/lib/utils/UIUtils.java // public class UIUtils { // public static void showToast(Context context, String tips) { // Toast toast = Toast.makeText(context, "lib.utils: " + tips, Toast.LENGTH_SHORT); // toast.show(); // } // // public static void alert(Context context, String tips) { // AlertDialog dlg = new AlertDialog.Builder(context) // .setMessage("lib.utils: " + tips) // .setPositiveButton("OK", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // dialog.dismiss(); // } // }) // .create(); // dlg.show(); // } // } // Path: Android/Sample/app.mine/src/main/java/net/wequick/example/small/app/mine/MainFragment.java import android.app.Activity; import android.content.Intent; import android.support.annotation.Keep; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.hellojni.HelloPluginJni; import com.example.mylib.Greet; import net.wequick.example.small.lib.utils.UIUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import butterknife.BindView; import butterknife.ButterKnife; // TextView tvLib = (TextView) rootView.findViewById(R.id.lib_label); tvLib.setText(Greet.hello() + " (ButterKnife 8)"); TextView tvJni = (TextView) rootView.findViewById(R.id.jni_label); tvJni.setText(HelloPluginJni.stringFromJNI()); button = (Button) rootView.findViewById(R.id.play_video_button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainFragment.this.getContext(), VideoActivity.class); startActivity(intent); } }); return rootView; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode != Activity.RESULT_OK) return; switch (requestCode) { case REQUEST_CODE_COLOR: Button button = (Button) getView().findViewById(R.id.inter_start_button); button.setText(getText(R.string.inter_start) + ": " + data.getStringExtra("color")); break; case REQUEST_CODE_CONTACTS:
UIUtils.showToast(getContext(), "contact: " + data);
wequick/Small
Android/DevSample/small/src/main/java/net/wequick/small/Bundle.java
// Path: Android/DevSample/small/src/main/java/net/wequick/small/util/FileUtils.java // public final class FileUtils { // private static final String DOWNLOAD_PATH = "small_patch"; // private static final String INTERNAL_PATH = "small_base"; // // public static File getInternalFilesPath(String dir) { // File file = Small.getContext().getDir(dir, Context.MODE_PRIVATE); // if (!file.exists()) { // file.mkdirs(); // } // return file; // } // // public static File getDownloadBundlePath() { // return getInternalFilesPath(DOWNLOAD_PATH); // } // // public static File getInternalBundlePath() { // return getInternalFilesPath(INTERNAL_PATH); // } // }
import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Handler; import android.os.Message; import net.wequick.small.util.FileUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit;
} out = new FileOutputStream(outFile); } else { out = new FileOutputStream(outFile); } // Extract left data byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.flush(); out.close(); in.close(); } private void initWithMap(JSONObject map) throws JSONException { if (sUserBundlesPath == null) { // Lazy init sUserBundlesPath = Small.getContext().getApplicationInfo().nativeLibraryDir; sIs64bit = sUserBundlesPath.contains("64"); } if (map.has("pkg")) { String pkg = map.getString("pkg"); if (pkg != null && !pkg.equals(HOST_PACKAGE)) { mPackageName = pkg; if (Small.isLoadFromAssets()) { mBuiltinAssetName = pkg + ".apk";
// Path: Android/DevSample/small/src/main/java/net/wequick/small/util/FileUtils.java // public final class FileUtils { // private static final String DOWNLOAD_PATH = "small_patch"; // private static final String INTERNAL_PATH = "small_base"; // // public static File getInternalFilesPath(String dir) { // File file = Small.getContext().getDir(dir, Context.MODE_PRIVATE); // if (!file.exists()) { // file.mkdirs(); // } // return file; // } // // public static File getDownloadBundlePath() { // return getInternalFilesPath(DOWNLOAD_PATH); // } // // public static File getInternalBundlePath() { // return getInternalFilesPath(INTERNAL_PATH); // } // } // Path: Android/DevSample/small/src/main/java/net/wequick/small/Bundle.java import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Handler; import android.os.Message; import net.wequick.small.util.FileUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; } out = new FileOutputStream(outFile); } else { out = new FileOutputStream(outFile); } // Extract left data byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.flush(); out.close(); in.close(); } private void initWithMap(JSONObject map) throws JSONException { if (sUserBundlesPath == null) { // Lazy init sUserBundlesPath = Small.getContext().getApplicationInfo().nativeLibraryDir; sIs64bit = sUserBundlesPath.contains("64"); } if (map.has("pkg")) { String pkg = map.getString("pkg"); if (pkg != null && !pkg.equals(HOST_PACKAGE)) { mPackageName = pkg; if (Small.isLoadFromAssets()) { mBuiltinAssetName = pkg + ".apk";
mBuiltinFile = new File(FileUtils.getInternalBundlePath(), mBuiltinAssetName);
retomeier/android-protips-location
app/src/main/java/com/radioactiveyak/location_best_practices/PlacesApplication.java
// Path: app/src/main/java/com/radioactiveyak/location_best_practices/utils/PlatformSpecificImplementationFactory.java // public class PlatformSpecificImplementationFactory { // // /** // * Create a new LastLocationFinder instance // * @param context Context // * @return LastLocationFinder // */ // public static ILastLocationFinder getLastLocationFinder(Context context) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? new GingerbreadLastLocationFinder(context) : new LegacyLastLocationFinder(context); // } // // /** // * Create a new StrictMode instance. // * @return StrictMode // */ // public static IStrictMode getStrictMode() { // if (PlacesConstants.SUPPORTS_HONEYCOMB) // return new HoneycombStrictMode(); // else if (PlacesConstants.SUPPORTS_GINGERBREAD) // return new LegacyStrictMode(); // else // return null; // } // // /** // * Create a new LocationUpdateRequester // * @param locationManager Location Manager // * @return LocationUpdateRequester // */ // public static LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? new GingerbreadLocationUpdateRequester(locationManager) : new FroyoLocationUpdateRequester(locationManager); // } // // /** // * Create a new SharedPreferenceSaver // * @param context Context // * @return SharedPreferenceSaver // */ // public static SharedPreferenceSaver getSharedPreferenceSaver(Context context) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? // new GingerbreadSharedPreferenceSaver(context) : // PlacesConstants.SUPPORTS_FROYO ? // new FroyoSharedPreferenceSaver(context) : // new LegacySharedPreferenceSaver(context); // } // } // // Path: app/src/main/java/com/radioactiveyak/location_best_practices/utils/base/IStrictMode.java // public interface IStrictMode { // /** // * Enable {@link StrictMode} using whichever platform-specific flags you wish. // */ // public void enableStrictMode(); // }
import android.app.Application; import com.radioactiveyak.location_best_practices.utils.PlatformSpecificImplementationFactory; import com.radioactiveyak.location_best_practices.utils.base.IStrictMode;
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.radioactiveyak.location_best_practices; public class PlacesApplication extends Application { // TODO Please Insert your Google Places API into MY_API_KEY in PlacesConstants.java // TODO Insert your Backup Manager API into res/values/strings.xml : backup_manager_key @Override public final void onCreate() { super.onCreate(); if (PlacesConstants.DEVELOPER_MODE) {
// Path: app/src/main/java/com/radioactiveyak/location_best_practices/utils/PlatformSpecificImplementationFactory.java // public class PlatformSpecificImplementationFactory { // // /** // * Create a new LastLocationFinder instance // * @param context Context // * @return LastLocationFinder // */ // public static ILastLocationFinder getLastLocationFinder(Context context) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? new GingerbreadLastLocationFinder(context) : new LegacyLastLocationFinder(context); // } // // /** // * Create a new StrictMode instance. // * @return StrictMode // */ // public static IStrictMode getStrictMode() { // if (PlacesConstants.SUPPORTS_HONEYCOMB) // return new HoneycombStrictMode(); // else if (PlacesConstants.SUPPORTS_GINGERBREAD) // return new LegacyStrictMode(); // else // return null; // } // // /** // * Create a new LocationUpdateRequester // * @param locationManager Location Manager // * @return LocationUpdateRequester // */ // public static LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? new GingerbreadLocationUpdateRequester(locationManager) : new FroyoLocationUpdateRequester(locationManager); // } // // /** // * Create a new SharedPreferenceSaver // * @param context Context // * @return SharedPreferenceSaver // */ // public static SharedPreferenceSaver getSharedPreferenceSaver(Context context) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? // new GingerbreadSharedPreferenceSaver(context) : // PlacesConstants.SUPPORTS_FROYO ? // new FroyoSharedPreferenceSaver(context) : // new LegacySharedPreferenceSaver(context); // } // } // // Path: app/src/main/java/com/radioactiveyak/location_best_practices/utils/base/IStrictMode.java // public interface IStrictMode { // /** // * Enable {@link StrictMode} using whichever platform-specific flags you wish. // */ // public void enableStrictMode(); // } // Path: app/src/main/java/com/radioactiveyak/location_best_practices/PlacesApplication.java import android.app.Application; import com.radioactiveyak.location_best_practices.utils.PlatformSpecificImplementationFactory; import com.radioactiveyak.location_best_practices.utils.base.IStrictMode; /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.radioactiveyak.location_best_practices; public class PlacesApplication extends Application { // TODO Please Insert your Google Places API into MY_API_KEY in PlacesConstants.java // TODO Insert your Backup Manager API into res/values/strings.xml : backup_manager_key @Override public final void onCreate() { super.onCreate(); if (PlacesConstants.DEVELOPER_MODE) {
IStrictMode strictMode = PlatformSpecificImplementationFactory.getStrictMode();
retomeier/android-protips-location
app/src/main/java/com/radioactiveyak/location_best_practices/PlacesApplication.java
// Path: app/src/main/java/com/radioactiveyak/location_best_practices/utils/PlatformSpecificImplementationFactory.java // public class PlatformSpecificImplementationFactory { // // /** // * Create a new LastLocationFinder instance // * @param context Context // * @return LastLocationFinder // */ // public static ILastLocationFinder getLastLocationFinder(Context context) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? new GingerbreadLastLocationFinder(context) : new LegacyLastLocationFinder(context); // } // // /** // * Create a new StrictMode instance. // * @return StrictMode // */ // public static IStrictMode getStrictMode() { // if (PlacesConstants.SUPPORTS_HONEYCOMB) // return new HoneycombStrictMode(); // else if (PlacesConstants.SUPPORTS_GINGERBREAD) // return new LegacyStrictMode(); // else // return null; // } // // /** // * Create a new LocationUpdateRequester // * @param locationManager Location Manager // * @return LocationUpdateRequester // */ // public static LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? new GingerbreadLocationUpdateRequester(locationManager) : new FroyoLocationUpdateRequester(locationManager); // } // // /** // * Create a new SharedPreferenceSaver // * @param context Context // * @return SharedPreferenceSaver // */ // public static SharedPreferenceSaver getSharedPreferenceSaver(Context context) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? // new GingerbreadSharedPreferenceSaver(context) : // PlacesConstants.SUPPORTS_FROYO ? // new FroyoSharedPreferenceSaver(context) : // new LegacySharedPreferenceSaver(context); // } // } // // Path: app/src/main/java/com/radioactiveyak/location_best_practices/utils/base/IStrictMode.java // public interface IStrictMode { // /** // * Enable {@link StrictMode} using whichever platform-specific flags you wish. // */ // public void enableStrictMode(); // }
import android.app.Application; import com.radioactiveyak.location_best_practices.utils.PlatformSpecificImplementationFactory; import com.radioactiveyak.location_best_practices.utils.base.IStrictMode;
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.radioactiveyak.location_best_practices; public class PlacesApplication extends Application { // TODO Please Insert your Google Places API into MY_API_KEY in PlacesConstants.java // TODO Insert your Backup Manager API into res/values/strings.xml : backup_manager_key @Override public final void onCreate() { super.onCreate(); if (PlacesConstants.DEVELOPER_MODE) {
// Path: app/src/main/java/com/radioactiveyak/location_best_practices/utils/PlatformSpecificImplementationFactory.java // public class PlatformSpecificImplementationFactory { // // /** // * Create a new LastLocationFinder instance // * @param context Context // * @return LastLocationFinder // */ // public static ILastLocationFinder getLastLocationFinder(Context context) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? new GingerbreadLastLocationFinder(context) : new LegacyLastLocationFinder(context); // } // // /** // * Create a new StrictMode instance. // * @return StrictMode // */ // public static IStrictMode getStrictMode() { // if (PlacesConstants.SUPPORTS_HONEYCOMB) // return new HoneycombStrictMode(); // else if (PlacesConstants.SUPPORTS_GINGERBREAD) // return new LegacyStrictMode(); // else // return null; // } // // /** // * Create a new LocationUpdateRequester // * @param locationManager Location Manager // * @return LocationUpdateRequester // */ // public static LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? new GingerbreadLocationUpdateRequester(locationManager) : new FroyoLocationUpdateRequester(locationManager); // } // // /** // * Create a new SharedPreferenceSaver // * @param context Context // * @return SharedPreferenceSaver // */ // public static SharedPreferenceSaver getSharedPreferenceSaver(Context context) { // return PlacesConstants.SUPPORTS_GINGERBREAD ? // new GingerbreadSharedPreferenceSaver(context) : // PlacesConstants.SUPPORTS_FROYO ? // new FroyoSharedPreferenceSaver(context) : // new LegacySharedPreferenceSaver(context); // } // } // // Path: app/src/main/java/com/radioactiveyak/location_best_practices/utils/base/IStrictMode.java // public interface IStrictMode { // /** // * Enable {@link StrictMode} using whichever platform-specific flags you wish. // */ // public void enableStrictMode(); // } // Path: app/src/main/java/com/radioactiveyak/location_best_practices/PlacesApplication.java import android.app.Application; import com.radioactiveyak.location_best_practices.utils.PlatformSpecificImplementationFactory; import com.radioactiveyak.location_best_practices.utils.base.IStrictMode; /* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.radioactiveyak.location_best_practices; public class PlacesApplication extends Application { // TODO Please Insert your Google Places API into MY_API_KEY in PlacesConstants.java // TODO Insert your Backup Manager API into res/values/strings.xml : backup_manager_key @Override public final void onCreate() { super.onCreate(); if (PlacesConstants.DEVELOPER_MODE) {
IStrictMode strictMode = PlatformSpecificImplementationFactory.getStrictMode();
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/ClusterStatusTest.java
// Path: src/test/java/com/officedrop/redis/failover/utils/JsonBinderTest.java // public class JsonBinderTest { // // public static final HostConfiguration configuration7000 = new HostConfiguration("localhost", 7000); // public static final HostConfiguration configuration7001 = new HostConfiguration("localhost", 7001); // public static final HostConfiguration configuration7002 = new HostConfiguration("localhost", 7002); // public static final HostConfiguration configuration7003 = new HostConfiguration("localhost", 7003); // // private static final String MASTER_DATA = "{\"master\":\"localhost:7000\",\"slaves\":[\"localhost:7001\",\"localhost:7002\"],\"unavailable\":[ \"localhost:7003\" ]}"; // private static final String WITHOUT_MASTER_DATA = "{\"slaves\":[\"localhost:7001\",\"localhost:7002\"],\"unavailable\":[ \"localhost:7003\" ]}"; // // // JsonBinder binder = new JacksonJsonBinder(); // // @Test // public void testParseJson() throws Exception { // // byte[] data = IOUtils.toByteArray(this.getClass().getClassLoader().getResource("sample_node_data.json")); // // Map<HostConfiguration,NodeState> nodes = binder.toNodeState(data); // // Assert.assertEquals(500, nodes.get(configuration7000).getLatency()); // Assert.assertFalse(nodes.get(configuration7000).isOffline()); // // Assert.assertEquals(600, nodes.get(configuration7001).getLatency()); // Assert.assertFalse(nodes.get(configuration7001).isOffline()); // // Assert.assertEquals(-1, nodes.get(configuration7002).getLatency()); // Assert.assertTrue(nodes.get(configuration7002).isOffline()); // } // // @Test // public void testGenerateJson() throws Exception { // // Map<HostConfiguration,NodeState> nodes = new HashMap<HostConfiguration, NodeState>(); // // nodes.put(configuration7000, new NodeState(500)); // nodes.put(configuration7001, new NodeState(600)); // nodes.put(configuration7002, NodeState.OFFLINE_STATE); // // byte[] data = binder.toBytes(nodes); // // String file = IOUtils.toString(this.getClass().getClassLoader().getResource("sample_node_data.json")); // // Assert.assertEquals( file, new String(data) ); // } // // @Test // public void testParseMasterData() { // // ClusterStatus status = binder.toClusterStatus(MASTER_DATA.getBytes()); // // Assert.assertEquals( configuration7000, status.getMaster() ); // // Assert.assertEquals( 2, status.getSlaves().size() ); // Assert.assertTrue( status.getSlaves().contains(configuration7001) ); // Assert.assertTrue( status.getSlaves().contains(configuration7002) ); // // Assert.assertEquals( 1, status.getUnavailables().size() ); // Assert.assertTrue( status.getUnavailables().contains(configuration7003) ); // } // // @Test // public void testWithoutMaster() { // ClusterStatus status = binder.toClusterStatus(WITHOUT_MASTER_DATA.getBytes()); // // Assert.assertNull( status.getMaster() ); // // Assert.assertEquals( 2, status.getSlaves().size() ); // Assert.assertTrue( status.getSlaves().contains(configuration7001) ); // Assert.assertTrue( status.getSlaves().contains(configuration7002) ); // // Assert.assertEquals( 1, status.getUnavailables().size() ); // Assert.assertTrue( status.getUnavailables().contains(configuration7003) ); // } // // @Test // public void testGenerateJsonData() { // ClusterStatus status = new ClusterStatus( // configuration7000, // Arrays.asList( configuration7001, configuration7002 ), // Arrays.asList(configuration7003)); // // Assert.assertEquals( // "{\"unavailable\":[\"localhost:7003\"],\"slaves\":[\"localhost:7002\",\"localhost:7001\"],\"master\":\"localhost:7000\"}", // new String( binder.toBytes(status) ) ); // } // // }
import com.officedrop.redis.failover.utils.JsonBinderTest; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 7:08 PM */ public class ClusterStatusTest { @Test public void testClusterStatusNoDifference() {
// Path: src/test/java/com/officedrop/redis/failover/utils/JsonBinderTest.java // public class JsonBinderTest { // // public static final HostConfiguration configuration7000 = new HostConfiguration("localhost", 7000); // public static final HostConfiguration configuration7001 = new HostConfiguration("localhost", 7001); // public static final HostConfiguration configuration7002 = new HostConfiguration("localhost", 7002); // public static final HostConfiguration configuration7003 = new HostConfiguration("localhost", 7003); // // private static final String MASTER_DATA = "{\"master\":\"localhost:7000\",\"slaves\":[\"localhost:7001\",\"localhost:7002\"],\"unavailable\":[ \"localhost:7003\" ]}"; // private static final String WITHOUT_MASTER_DATA = "{\"slaves\":[\"localhost:7001\",\"localhost:7002\"],\"unavailable\":[ \"localhost:7003\" ]}"; // // // JsonBinder binder = new JacksonJsonBinder(); // // @Test // public void testParseJson() throws Exception { // // byte[] data = IOUtils.toByteArray(this.getClass().getClassLoader().getResource("sample_node_data.json")); // // Map<HostConfiguration,NodeState> nodes = binder.toNodeState(data); // // Assert.assertEquals(500, nodes.get(configuration7000).getLatency()); // Assert.assertFalse(nodes.get(configuration7000).isOffline()); // // Assert.assertEquals(600, nodes.get(configuration7001).getLatency()); // Assert.assertFalse(nodes.get(configuration7001).isOffline()); // // Assert.assertEquals(-1, nodes.get(configuration7002).getLatency()); // Assert.assertTrue(nodes.get(configuration7002).isOffline()); // } // // @Test // public void testGenerateJson() throws Exception { // // Map<HostConfiguration,NodeState> nodes = new HashMap<HostConfiguration, NodeState>(); // // nodes.put(configuration7000, new NodeState(500)); // nodes.put(configuration7001, new NodeState(600)); // nodes.put(configuration7002, NodeState.OFFLINE_STATE); // // byte[] data = binder.toBytes(nodes); // // String file = IOUtils.toString(this.getClass().getClassLoader().getResource("sample_node_data.json")); // // Assert.assertEquals( file, new String(data) ); // } // // @Test // public void testParseMasterData() { // // ClusterStatus status = binder.toClusterStatus(MASTER_DATA.getBytes()); // // Assert.assertEquals( configuration7000, status.getMaster() ); // // Assert.assertEquals( 2, status.getSlaves().size() ); // Assert.assertTrue( status.getSlaves().contains(configuration7001) ); // Assert.assertTrue( status.getSlaves().contains(configuration7002) ); // // Assert.assertEquals( 1, status.getUnavailables().size() ); // Assert.assertTrue( status.getUnavailables().contains(configuration7003) ); // } // // @Test // public void testWithoutMaster() { // ClusterStatus status = binder.toClusterStatus(WITHOUT_MASTER_DATA.getBytes()); // // Assert.assertNull( status.getMaster() ); // // Assert.assertEquals( 2, status.getSlaves().size() ); // Assert.assertTrue( status.getSlaves().contains(configuration7001) ); // Assert.assertTrue( status.getSlaves().contains(configuration7002) ); // // Assert.assertEquals( 1, status.getUnavailables().size() ); // Assert.assertTrue( status.getUnavailables().contains(configuration7003) ); // } // // @Test // public void testGenerateJsonData() { // ClusterStatus status = new ClusterStatus( // configuration7000, // Arrays.asList( configuration7001, configuration7002 ), // Arrays.asList(configuration7003)); // // Assert.assertEquals( // "{\"unavailable\":[\"localhost:7003\"],\"slaves\":[\"localhost:7002\",\"localhost:7001\"],\"master\":\"localhost:7000\"}", // new String( binder.toBytes(status) ) ); // } // // } // Path: src/test/java/com/officedrop/redis/failover/ClusterStatusTest.java import com.officedrop.redis.failover.utils.JsonBinderTest; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 7:08 PM */ public class ClusterStatusTest { @Test public void testClusterStatusNoDifference() {
HostConfiguration master = JsonBinderTest.configuration7000;
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/jedis/GenericJedisClientFactory.java
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // }
import com.officedrop.redis.failover.HostConfiguration;
package com.officedrop.redis.failover.jedis; /** * User: Maurício Linhares * Date: 1/3/13 * Time: 9:24 AM */ public class GenericJedisClientFactory implements JedisClientFactory { public static final GenericJedisClientFactory INSTANCE = new GenericJedisClientFactory(); @Override
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // Path: src/main/java/com/officedrop/redis/failover/jedis/GenericJedisClientFactory.java import com.officedrop.redis.failover.HostConfiguration; package com.officedrop.redis.failover.jedis; /** * User: Maurício Linhares * Date: 1/3/13 * Time: 9:24 AM */ public class GenericJedisClientFactory implements JedisClientFactory { public static final GenericJedisClientFactory INSTANCE = new GenericJedisClientFactory(); @Override
public JedisClient create(final HostConfiguration configuration) {
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/ClientTest.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // }
import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.mockito.Mockito.*;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/21/12 * Time: 11:26 AM */ public class ClientTest { @Test public void testCreateClient() throws Exception { ClusterChangeEventSource nodeManager = mock(ClusterChangeEventSource.class );
// Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // Path: src/test/java/com/officedrop/redis/failover/ClientTest.java import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.mockito.Mockito.*; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/21/12 * Time: 11:26 AM */ public class ClientTest { @Test public void testCreateClient() throws Exception { ClusterChangeEventSource nodeManager = mock(ClusterChangeEventSource.class );
JedisClient masterClient = mock(JedisClient.class);
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/ClientTest.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // }
import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.mockito.Mockito.*;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/21/12 * Time: 11:26 AM */ public class ClientTest { @Test public void testCreateClient() throws Exception { ClusterChangeEventSource nodeManager = mock(ClusterChangeEventSource.class ); JedisClient masterClient = mock(JedisClient.class); JedisClient slaveClient1 = mock(JedisClient.class); JedisClient slaveClient2 = mock(JedisClient.class);
// Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // Path: src/test/java/com/officedrop/redis/failover/ClientTest.java import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.mockito.Mockito.*; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/21/12 * Time: 11:26 AM */ public class ClientTest { @Test public void testCreateClient() throws Exception { ClusterChangeEventSource nodeManager = mock(ClusterChangeEventSource.class ); JedisClient masterClient = mock(JedisClient.class); JedisClient slaveClient1 = mock(JedisClient.class); JedisClient slaveClient2 = mock(JedisClient.class);
JedisClientFactory factory = mock(JedisClientFactory.class);
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/strategy/SimpleMajorityStrategyTest.java
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // }
import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays;
package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:03 PM */ public class SimpleMajorityStrategyTest { SimpleMajorityStrategy strategy = new SimpleMajorityStrategy();
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // } // Path: src/test/java/com/officedrop/redis/failover/strategy/SimpleMajorityStrategyTest.java import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays; package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:03 PM */ public class SimpleMajorityStrategyTest { SimpleMajorityStrategy strategy = new SimpleMajorityStrategy();
HostConfiguration configuration = new HostConfiguration("localhost", 1);
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/strategy/SimpleMajorityStrategyTest.java
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // }
import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays;
package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:03 PM */ public class SimpleMajorityStrategyTest { SimpleMajorityStrategy strategy = new SimpleMajorityStrategy(); HostConfiguration configuration = new HostConfiguration("localhost", 1); @Test public void testSimpleMajorityUnavailableDecision() { boolean result = strategy.isAvailable(configuration, Arrays.asList(
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // } // Path: src/test/java/com/officedrop/redis/failover/strategy/SimpleMajorityStrategyTest.java import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import junit.framework.Assert; import org.junit.Test; import java.util.Arrays; package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:03 PM */ public class SimpleMajorityStrategyTest { SimpleMajorityStrategy strategy = new SimpleMajorityStrategy(); HostConfiguration configuration = new HostConfiguration("localhost", 1); @Test public void testSimpleMajorityUnavailableDecision() { boolean result = strategy.isAvailable(configuration, Arrays.asList(
new NodeState(400),
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/Node.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/ConnectionException.java // public class ConnectionException extends RuntimeException { // // public ConnectionException(final Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisActions.java // public interface JedisActions extends JedisCommands { // // public Long del(final String... keys); // // public String quit(); // // public String ping(); // // public String slaveof(final String host, final int port); // // public String slaveofNoOne(); // // public String info(); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // }
import com.officedrop.redis.failover.jedis.ConnectionException; import com.officedrop.redis.failover.jedis.JedisActions; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.StringReader; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/24/12 * Time: 6:22 PM */ public class Node { private static final Logger log = LoggerFactory.getLogger(Node.class);
// Path: src/main/java/com/officedrop/redis/failover/jedis/ConnectionException.java // public class ConnectionException extends RuntimeException { // // public ConnectionException(final Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisActions.java // public interface JedisActions extends JedisCommands { // // public Long del(final String... keys); // // public String quit(); // // public String ping(); // // public String slaveof(final String host, final int port); // // public String slaveofNoOne(); // // public String info(); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // Path: src/main/java/com/officedrop/redis/failover/Node.java import com.officedrop.redis.failover.jedis.ConnectionException; import com.officedrop.redis.failover.jedis.JedisActions; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.StringReader; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/24/12 * Time: 6:22 PM */ public class Node { private static final Logger log = LoggerFactory.getLogger(Node.class);
private JedisActions client;
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/Node.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/ConnectionException.java // public class ConnectionException extends RuntimeException { // // public ConnectionException(final Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisActions.java // public interface JedisActions extends JedisCommands { // // public Long del(final String... keys); // // public String quit(); // // public String ping(); // // public String slaveof(final String host, final int port); // // public String slaveofNoOne(); // // public String info(); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // }
import com.officedrop.redis.failover.jedis.ConnectionException; import com.officedrop.redis.failover.jedis.JedisActions; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.StringReader; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/24/12 * Time: 6:22 PM */ public class Node { private static final Logger log = LoggerFactory.getLogger(Node.class); private JedisActions client; private volatile int currentErrorCount = 0; private volatile boolean shutdown; private final long sleepDelay; private final List<NodeListener> listeners = new CopyOnWriteArrayList<NodeListener>(); private final int maxErrors; private final HostConfiguration hostConfiguration;
// Path: src/main/java/com/officedrop/redis/failover/jedis/ConnectionException.java // public class ConnectionException extends RuntimeException { // // public ConnectionException(final Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisActions.java // public interface JedisActions extends JedisCommands { // // public Long del(final String... keys); // // public String quit(); // // public String ping(); // // public String slaveof(final String host, final int port); // // public String slaveofNoOne(); // // public String info(); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // Path: src/main/java/com/officedrop/redis/failover/Node.java import com.officedrop.redis.failover.jedis.ConnectionException; import com.officedrop.redis.failover.jedis.JedisActions; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.StringReader; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/24/12 * Time: 6:22 PM */ public class Node { private static final Logger log = LoggerFactory.getLogger(Node.class); private JedisActions client; private volatile int currentErrorCount = 0; private volatile boolean shutdown; private final long sleepDelay; private final List<NodeListener> listeners = new CopyOnWriteArrayList<NodeListener>(); private final int maxErrors; private final HostConfiguration hostConfiguration;
private final JedisClientFactory factory;
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/Node.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/ConnectionException.java // public class ConnectionException extends RuntimeException { // // public ConnectionException(final Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisActions.java // public interface JedisActions extends JedisCommands { // // public Long del(final String... keys); // // public String quit(); // // public String ping(); // // public String slaveof(final String host, final int port); // // public String slaveofNoOne(); // // public String info(); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // }
import com.officedrop.redis.failover.jedis.ConnectionException; import com.officedrop.redis.failover.jedis.JedisActions; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.StringReader; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock;
log.error(String.format("Failed to signal offline event to listener %s", listener), exception); } } } } } private void nodeAction(final Action1<JedisActions> action) { this.nodeFunction(new Function1<JedisActions, Object>() { @Override public Object apply(final JedisActions parameter) { action.apply(parameter); return null; } }); } private <OUT> OUT nodeFunction(Function1<JedisActions, OUT> function) { try { this.lock.lock(); if (this.client == null) { this.client = this.factory.create(this.hostConfiguration); } return function.apply(this.client); } catch (Exception e) { this.client = null; this.fireErrorEvent(e);
// Path: src/main/java/com/officedrop/redis/failover/jedis/ConnectionException.java // public class ConnectionException extends RuntimeException { // // public ConnectionException(final Throwable cause) { // super(cause); // } // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisActions.java // public interface JedisActions extends JedisCommands { // // public Long del(final String... keys); // // public String quit(); // // public String ping(); // // public String slaveof(final String host, final int port); // // public String slaveofNoOne(); // // public String info(); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // Path: src/main/java/com/officedrop/redis/failover/Node.java import com.officedrop.redis.failover.jedis.ConnectionException; import com.officedrop.redis.failover.jedis.JedisActions; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.StringReader; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; log.error(String.format("Failed to signal offline event to listener %s", listener), exception); } } } } } private void nodeAction(final Action1<JedisActions> action) { this.nodeFunction(new Function1<JedisActions, Object>() { @Override public Object apply(final JedisActions parameter) { action.apply(parameter); return null; } }); } private <OUT> OUT nodeFunction(Function1<JedisActions, OUT> function) { try { this.lock.lock(); if (this.client == null) { this.client = this.factory.create(this.hostConfiguration); } return function.apply(this.client); } catch (Exception e) { this.client = null; this.fireErrorEvent(e);
throw new ConnectionException(e);
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/NodeTest.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/GenericJedisClientFactory.java // public class GenericJedisClientFactory implements JedisClientFactory { // // public static final GenericJedisClientFactory INSTANCE = new GenericJedisClientFactory(); // // @Override // public JedisClient create(final HostConfiguration configuration) { // return new GenericJedisClient( // configuration.getHost(), // configuration.getPort(), // configuration.getTimeout(), // configuration.getDatabase() // ); // } // // } // // Path: src/test/java/com/officedrop/redis/failover/redis/RedisServer.java // public class RedisServer implements Closeable { // // private static final AtomicInteger PORT = new AtomicInteger(10000); // private static final Logger log = LoggerFactory.getLogger(RedisServer.class); // // private final String address; // private final int port; // private final ServerSocket server; // private final ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>(); // private String masterHost; // private String masterPort; // private volatile boolean running; // private boolean alwaysTimeout; // private final List<RedisClientHandler> handlers = new CopyOnWriteArrayList<RedisClientHandler>(); // // public RedisServer(String address, int port) { // try { // this.address = address; // this.port = port; // this.server = new ServerSocket(); // this.server.bind(new InetSocketAddress(address, port)); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // public void set(String key, String value) { // this.map.put(key, value); // } // // public String get(String key) { // return this.map.get(key); // } // // public boolean isAlwaysTimeout() { // return this.alwaysTimeout; // } // // public String getAddress() { // return this.address; // } // // public int getPort() { // return this.port; // } // // public void setAlwaysTimeout(boolean value) { // this.alwaysTimeout = value; // } // // public String getMasterHost() { // return masterHost; // } // // public void setMasterHost(final String masterHost) { // this.masterHost = masterHost; // } // // public String getMasterPort() { // return masterPort; // } // // public void setMasterPort(final String masterPort) { // this.masterPort = masterPort; // } // // public void setMasterPort(final int masterPort) { // this.masterPort = String.valueOf(masterPort); // } // // public void start() { // // this.running = true; // // log.info("started server - {}:{}", this.getAddress(), this.getPort()); // // Thread acceptor = new Thread(new Runnable() { // @Override // public void run() { // // while (isRunning()) { // try { // final Socket socket = getServer().accept(); // // log.info("Accepted client {}:{}", socket.getInetAddress(), getPort()); // // RedisClientHandler handler = new RedisClientHandler(RedisServer.this, socket); // // handlers.add(handler); // // handler.start(); // // } catch (Exception e) { // log.error("Failed to accept socket connection", e); // } // } // // } // }); // // acceptor.start(); // // } // // public ServerSocket getServer() { // return this.server; // } // // public boolean isRunning() { // return this.running; // } // // public void close() { // this.stop(); // } // // public void stop() { // if (this.running) { // this.running = false; // try { // getServer().close(); // } catch (Exception e) { // log.error("Failed to close socket server", e); // throw new IllegalStateException(e); // } // } // } // // public HostConfiguration getHostConfiguration() { // return new HostConfiguration(this.address, this.port); // } // // public HostConfiguration getMasterConfiguration() { // return new HostConfiguration( this.masterHost, Integer.valueOf(this.masterPort) ); // } // // public static void withServer(Action1<RedisServer> action) { // RedisServer server = new RedisServer("localhost", PORT.incrementAndGet()); // // server.start(); // // try { // action.apply(server); // } finally { // server.stop(); // } // } // // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // } // // Path: src/test/java/com/officedrop/redis/failover/utils/ThreadPool.java // public class ThreadPool { // // public static final ExecutorService POOL = Executors.newCachedThreadPool(); // // public static void submit( Runnable r ) { // POOL.submit(r); // } // // }
import com.officedrop.redis.failover.jedis.GenericJedisClientFactory; import com.officedrop.redis.failover.redis.RedisServer; import com.officedrop.redis.failover.utils.Action1; import com.officedrop.redis.failover.utils.ThreadPool; import junit.framework.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 1/3/13 * Time: 9:23 AM */ public class NodeTest { private static final Logger log = LoggerFactory.getLogger(NodeTest.class); @Test public void testPingNode() {
// Path: src/main/java/com/officedrop/redis/failover/jedis/GenericJedisClientFactory.java // public class GenericJedisClientFactory implements JedisClientFactory { // // public static final GenericJedisClientFactory INSTANCE = new GenericJedisClientFactory(); // // @Override // public JedisClient create(final HostConfiguration configuration) { // return new GenericJedisClient( // configuration.getHost(), // configuration.getPort(), // configuration.getTimeout(), // configuration.getDatabase() // ); // } // // } // // Path: src/test/java/com/officedrop/redis/failover/redis/RedisServer.java // public class RedisServer implements Closeable { // // private static final AtomicInteger PORT = new AtomicInteger(10000); // private static final Logger log = LoggerFactory.getLogger(RedisServer.class); // // private final String address; // private final int port; // private final ServerSocket server; // private final ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>(); // private String masterHost; // private String masterPort; // private volatile boolean running; // private boolean alwaysTimeout; // private final List<RedisClientHandler> handlers = new CopyOnWriteArrayList<RedisClientHandler>(); // // public RedisServer(String address, int port) { // try { // this.address = address; // this.port = port; // this.server = new ServerSocket(); // this.server.bind(new InetSocketAddress(address, port)); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // public void set(String key, String value) { // this.map.put(key, value); // } // // public String get(String key) { // return this.map.get(key); // } // // public boolean isAlwaysTimeout() { // return this.alwaysTimeout; // } // // public String getAddress() { // return this.address; // } // // public int getPort() { // return this.port; // } // // public void setAlwaysTimeout(boolean value) { // this.alwaysTimeout = value; // } // // public String getMasterHost() { // return masterHost; // } // // public void setMasterHost(final String masterHost) { // this.masterHost = masterHost; // } // // public String getMasterPort() { // return masterPort; // } // // public void setMasterPort(final String masterPort) { // this.masterPort = masterPort; // } // // public void setMasterPort(final int masterPort) { // this.masterPort = String.valueOf(masterPort); // } // // public void start() { // // this.running = true; // // log.info("started server - {}:{}", this.getAddress(), this.getPort()); // // Thread acceptor = new Thread(new Runnable() { // @Override // public void run() { // // while (isRunning()) { // try { // final Socket socket = getServer().accept(); // // log.info("Accepted client {}:{}", socket.getInetAddress(), getPort()); // // RedisClientHandler handler = new RedisClientHandler(RedisServer.this, socket); // // handlers.add(handler); // // handler.start(); // // } catch (Exception e) { // log.error("Failed to accept socket connection", e); // } // } // // } // }); // // acceptor.start(); // // } // // public ServerSocket getServer() { // return this.server; // } // // public boolean isRunning() { // return this.running; // } // // public void close() { // this.stop(); // } // // public void stop() { // if (this.running) { // this.running = false; // try { // getServer().close(); // } catch (Exception e) { // log.error("Failed to close socket server", e); // throw new IllegalStateException(e); // } // } // } // // public HostConfiguration getHostConfiguration() { // return new HostConfiguration(this.address, this.port); // } // // public HostConfiguration getMasterConfiguration() { // return new HostConfiguration( this.masterHost, Integer.valueOf(this.masterPort) ); // } // // public static void withServer(Action1<RedisServer> action) { // RedisServer server = new RedisServer("localhost", PORT.incrementAndGet()); // // server.start(); // // try { // action.apply(server); // } finally { // server.stop(); // } // } // // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // } // // Path: src/test/java/com/officedrop/redis/failover/utils/ThreadPool.java // public class ThreadPool { // // public static final ExecutorService POOL = Executors.newCachedThreadPool(); // // public static void submit( Runnable r ) { // POOL.submit(r); // } // // } // Path: src/test/java/com/officedrop/redis/failover/NodeTest.java import com.officedrop.redis.failover.jedis.GenericJedisClientFactory; import com.officedrop.redis.failover.redis.RedisServer; import com.officedrop.redis.failover.utils.Action1; import com.officedrop.redis.failover.utils.ThreadPool; import junit.framework.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 1/3/13 * Time: 9:23 AM */ public class NodeTest { private static final Logger log = LoggerFactory.getLogger(NodeTest.class); @Test public void testPingNode() {
RedisServer.withServer( new Action1<RedisServer>() {
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/NodeTest.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/GenericJedisClientFactory.java // public class GenericJedisClientFactory implements JedisClientFactory { // // public static final GenericJedisClientFactory INSTANCE = new GenericJedisClientFactory(); // // @Override // public JedisClient create(final HostConfiguration configuration) { // return new GenericJedisClient( // configuration.getHost(), // configuration.getPort(), // configuration.getTimeout(), // configuration.getDatabase() // ); // } // // } // // Path: src/test/java/com/officedrop/redis/failover/redis/RedisServer.java // public class RedisServer implements Closeable { // // private static final AtomicInteger PORT = new AtomicInteger(10000); // private static final Logger log = LoggerFactory.getLogger(RedisServer.class); // // private final String address; // private final int port; // private final ServerSocket server; // private final ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>(); // private String masterHost; // private String masterPort; // private volatile boolean running; // private boolean alwaysTimeout; // private final List<RedisClientHandler> handlers = new CopyOnWriteArrayList<RedisClientHandler>(); // // public RedisServer(String address, int port) { // try { // this.address = address; // this.port = port; // this.server = new ServerSocket(); // this.server.bind(new InetSocketAddress(address, port)); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // public void set(String key, String value) { // this.map.put(key, value); // } // // public String get(String key) { // return this.map.get(key); // } // // public boolean isAlwaysTimeout() { // return this.alwaysTimeout; // } // // public String getAddress() { // return this.address; // } // // public int getPort() { // return this.port; // } // // public void setAlwaysTimeout(boolean value) { // this.alwaysTimeout = value; // } // // public String getMasterHost() { // return masterHost; // } // // public void setMasterHost(final String masterHost) { // this.masterHost = masterHost; // } // // public String getMasterPort() { // return masterPort; // } // // public void setMasterPort(final String masterPort) { // this.masterPort = masterPort; // } // // public void setMasterPort(final int masterPort) { // this.masterPort = String.valueOf(masterPort); // } // // public void start() { // // this.running = true; // // log.info("started server - {}:{}", this.getAddress(), this.getPort()); // // Thread acceptor = new Thread(new Runnable() { // @Override // public void run() { // // while (isRunning()) { // try { // final Socket socket = getServer().accept(); // // log.info("Accepted client {}:{}", socket.getInetAddress(), getPort()); // // RedisClientHandler handler = new RedisClientHandler(RedisServer.this, socket); // // handlers.add(handler); // // handler.start(); // // } catch (Exception e) { // log.error("Failed to accept socket connection", e); // } // } // // } // }); // // acceptor.start(); // // } // // public ServerSocket getServer() { // return this.server; // } // // public boolean isRunning() { // return this.running; // } // // public void close() { // this.stop(); // } // // public void stop() { // if (this.running) { // this.running = false; // try { // getServer().close(); // } catch (Exception e) { // log.error("Failed to close socket server", e); // throw new IllegalStateException(e); // } // } // } // // public HostConfiguration getHostConfiguration() { // return new HostConfiguration(this.address, this.port); // } // // public HostConfiguration getMasterConfiguration() { // return new HostConfiguration( this.masterHost, Integer.valueOf(this.masterPort) ); // } // // public static void withServer(Action1<RedisServer> action) { // RedisServer server = new RedisServer("localhost", PORT.incrementAndGet()); // // server.start(); // // try { // action.apply(server); // } finally { // server.stop(); // } // } // // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // } // // Path: src/test/java/com/officedrop/redis/failover/utils/ThreadPool.java // public class ThreadPool { // // public static final ExecutorService POOL = Executors.newCachedThreadPool(); // // public static void submit( Runnable r ) { // POOL.submit(r); // } // // }
import com.officedrop.redis.failover.jedis.GenericJedisClientFactory; import com.officedrop.redis.failover.redis.RedisServer; import com.officedrop.redis.failover.utils.Action1; import com.officedrop.redis.failover.utils.ThreadPool; import junit.framework.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 1/3/13 * Time: 9:23 AM */ public class NodeTest { private static final Logger log = LoggerFactory.getLogger(NodeTest.class); @Test public void testPingNode() {
// Path: src/main/java/com/officedrop/redis/failover/jedis/GenericJedisClientFactory.java // public class GenericJedisClientFactory implements JedisClientFactory { // // public static final GenericJedisClientFactory INSTANCE = new GenericJedisClientFactory(); // // @Override // public JedisClient create(final HostConfiguration configuration) { // return new GenericJedisClient( // configuration.getHost(), // configuration.getPort(), // configuration.getTimeout(), // configuration.getDatabase() // ); // } // // } // // Path: src/test/java/com/officedrop/redis/failover/redis/RedisServer.java // public class RedisServer implements Closeable { // // private static final AtomicInteger PORT = new AtomicInteger(10000); // private static final Logger log = LoggerFactory.getLogger(RedisServer.class); // // private final String address; // private final int port; // private final ServerSocket server; // private final ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>(); // private String masterHost; // private String masterPort; // private volatile boolean running; // private boolean alwaysTimeout; // private final List<RedisClientHandler> handlers = new CopyOnWriteArrayList<RedisClientHandler>(); // // public RedisServer(String address, int port) { // try { // this.address = address; // this.port = port; // this.server = new ServerSocket(); // this.server.bind(new InetSocketAddress(address, port)); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // public void set(String key, String value) { // this.map.put(key, value); // } // // public String get(String key) { // return this.map.get(key); // } // // public boolean isAlwaysTimeout() { // return this.alwaysTimeout; // } // // public String getAddress() { // return this.address; // } // // public int getPort() { // return this.port; // } // // public void setAlwaysTimeout(boolean value) { // this.alwaysTimeout = value; // } // // public String getMasterHost() { // return masterHost; // } // // public void setMasterHost(final String masterHost) { // this.masterHost = masterHost; // } // // public String getMasterPort() { // return masterPort; // } // // public void setMasterPort(final String masterPort) { // this.masterPort = masterPort; // } // // public void setMasterPort(final int masterPort) { // this.masterPort = String.valueOf(masterPort); // } // // public void start() { // // this.running = true; // // log.info("started server - {}:{}", this.getAddress(), this.getPort()); // // Thread acceptor = new Thread(new Runnable() { // @Override // public void run() { // // while (isRunning()) { // try { // final Socket socket = getServer().accept(); // // log.info("Accepted client {}:{}", socket.getInetAddress(), getPort()); // // RedisClientHandler handler = new RedisClientHandler(RedisServer.this, socket); // // handlers.add(handler); // // handler.start(); // // } catch (Exception e) { // log.error("Failed to accept socket connection", e); // } // } // // } // }); // // acceptor.start(); // // } // // public ServerSocket getServer() { // return this.server; // } // // public boolean isRunning() { // return this.running; // } // // public void close() { // this.stop(); // } // // public void stop() { // if (this.running) { // this.running = false; // try { // getServer().close(); // } catch (Exception e) { // log.error("Failed to close socket server", e); // throw new IllegalStateException(e); // } // } // } // // public HostConfiguration getHostConfiguration() { // return new HostConfiguration(this.address, this.port); // } // // public HostConfiguration getMasterConfiguration() { // return new HostConfiguration( this.masterHost, Integer.valueOf(this.masterPort) ); // } // // public static void withServer(Action1<RedisServer> action) { // RedisServer server = new RedisServer("localhost", PORT.incrementAndGet()); // // server.start(); // // try { // action.apply(server); // } finally { // server.stop(); // } // } // // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // } // // Path: src/test/java/com/officedrop/redis/failover/utils/ThreadPool.java // public class ThreadPool { // // public static final ExecutorService POOL = Executors.newCachedThreadPool(); // // public static void submit( Runnable r ) { // POOL.submit(r); // } // // } // Path: src/test/java/com/officedrop/redis/failover/NodeTest.java import com.officedrop.redis.failover.jedis.GenericJedisClientFactory; import com.officedrop.redis.failover.redis.RedisServer; import com.officedrop.redis.failover.utils.Action1; import com.officedrop.redis.failover.utils.ThreadPool; import junit.framework.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 1/3/13 * Time: 9:23 AM */ public class NodeTest { private static final Logger log = LoggerFactory.getLogger(NodeTest.class); @Test public void testPingNode() {
RedisServer.withServer( new Action1<RedisServer>() {
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/NodeTest.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/GenericJedisClientFactory.java // public class GenericJedisClientFactory implements JedisClientFactory { // // public static final GenericJedisClientFactory INSTANCE = new GenericJedisClientFactory(); // // @Override // public JedisClient create(final HostConfiguration configuration) { // return new GenericJedisClient( // configuration.getHost(), // configuration.getPort(), // configuration.getTimeout(), // configuration.getDatabase() // ); // } // // } // // Path: src/test/java/com/officedrop/redis/failover/redis/RedisServer.java // public class RedisServer implements Closeable { // // private static final AtomicInteger PORT = new AtomicInteger(10000); // private static final Logger log = LoggerFactory.getLogger(RedisServer.class); // // private final String address; // private final int port; // private final ServerSocket server; // private final ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>(); // private String masterHost; // private String masterPort; // private volatile boolean running; // private boolean alwaysTimeout; // private final List<RedisClientHandler> handlers = new CopyOnWriteArrayList<RedisClientHandler>(); // // public RedisServer(String address, int port) { // try { // this.address = address; // this.port = port; // this.server = new ServerSocket(); // this.server.bind(new InetSocketAddress(address, port)); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // public void set(String key, String value) { // this.map.put(key, value); // } // // public String get(String key) { // return this.map.get(key); // } // // public boolean isAlwaysTimeout() { // return this.alwaysTimeout; // } // // public String getAddress() { // return this.address; // } // // public int getPort() { // return this.port; // } // // public void setAlwaysTimeout(boolean value) { // this.alwaysTimeout = value; // } // // public String getMasterHost() { // return masterHost; // } // // public void setMasterHost(final String masterHost) { // this.masterHost = masterHost; // } // // public String getMasterPort() { // return masterPort; // } // // public void setMasterPort(final String masterPort) { // this.masterPort = masterPort; // } // // public void setMasterPort(final int masterPort) { // this.masterPort = String.valueOf(masterPort); // } // // public void start() { // // this.running = true; // // log.info("started server - {}:{}", this.getAddress(), this.getPort()); // // Thread acceptor = new Thread(new Runnable() { // @Override // public void run() { // // while (isRunning()) { // try { // final Socket socket = getServer().accept(); // // log.info("Accepted client {}:{}", socket.getInetAddress(), getPort()); // // RedisClientHandler handler = new RedisClientHandler(RedisServer.this, socket); // // handlers.add(handler); // // handler.start(); // // } catch (Exception e) { // log.error("Failed to accept socket connection", e); // } // } // // } // }); // // acceptor.start(); // // } // // public ServerSocket getServer() { // return this.server; // } // // public boolean isRunning() { // return this.running; // } // // public void close() { // this.stop(); // } // // public void stop() { // if (this.running) { // this.running = false; // try { // getServer().close(); // } catch (Exception e) { // log.error("Failed to close socket server", e); // throw new IllegalStateException(e); // } // } // } // // public HostConfiguration getHostConfiguration() { // return new HostConfiguration(this.address, this.port); // } // // public HostConfiguration getMasterConfiguration() { // return new HostConfiguration( this.masterHost, Integer.valueOf(this.masterPort) ); // } // // public static void withServer(Action1<RedisServer> action) { // RedisServer server = new RedisServer("localhost", PORT.incrementAndGet()); // // server.start(); // // try { // action.apply(server); // } finally { // server.stop(); // } // } // // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // } // // Path: src/test/java/com/officedrop/redis/failover/utils/ThreadPool.java // public class ThreadPool { // // public static final ExecutorService POOL = Executors.newCachedThreadPool(); // // public static void submit( Runnable r ) { // POOL.submit(r); // } // // }
import com.officedrop.redis.failover.jedis.GenericJedisClientFactory; import com.officedrop.redis.failover.redis.RedisServer; import com.officedrop.redis.failover.utils.Action1; import com.officedrop.redis.failover.utils.ThreadPool; import junit.framework.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 1/3/13 * Time: 9:23 AM */ public class NodeTest { private static final Logger log = LoggerFactory.getLogger(NodeTest.class); @Test public void testPingNode() { RedisServer.withServer( new Action1<RedisServer>() { @Override public void apply( RedisServer server) {
// Path: src/main/java/com/officedrop/redis/failover/jedis/GenericJedisClientFactory.java // public class GenericJedisClientFactory implements JedisClientFactory { // // public static final GenericJedisClientFactory INSTANCE = new GenericJedisClientFactory(); // // @Override // public JedisClient create(final HostConfiguration configuration) { // return new GenericJedisClient( // configuration.getHost(), // configuration.getPort(), // configuration.getTimeout(), // configuration.getDatabase() // ); // } // // } // // Path: src/test/java/com/officedrop/redis/failover/redis/RedisServer.java // public class RedisServer implements Closeable { // // private static final AtomicInteger PORT = new AtomicInteger(10000); // private static final Logger log = LoggerFactory.getLogger(RedisServer.class); // // private final String address; // private final int port; // private final ServerSocket server; // private final ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>(); // private String masterHost; // private String masterPort; // private volatile boolean running; // private boolean alwaysTimeout; // private final List<RedisClientHandler> handlers = new CopyOnWriteArrayList<RedisClientHandler>(); // // public RedisServer(String address, int port) { // try { // this.address = address; // this.port = port; // this.server = new ServerSocket(); // this.server.bind(new InetSocketAddress(address, port)); // } catch (Exception e) { // throw new IllegalStateException(e); // } // } // // public void set(String key, String value) { // this.map.put(key, value); // } // // public String get(String key) { // return this.map.get(key); // } // // public boolean isAlwaysTimeout() { // return this.alwaysTimeout; // } // // public String getAddress() { // return this.address; // } // // public int getPort() { // return this.port; // } // // public void setAlwaysTimeout(boolean value) { // this.alwaysTimeout = value; // } // // public String getMasterHost() { // return masterHost; // } // // public void setMasterHost(final String masterHost) { // this.masterHost = masterHost; // } // // public String getMasterPort() { // return masterPort; // } // // public void setMasterPort(final String masterPort) { // this.masterPort = masterPort; // } // // public void setMasterPort(final int masterPort) { // this.masterPort = String.valueOf(masterPort); // } // // public void start() { // // this.running = true; // // log.info("started server - {}:{}", this.getAddress(), this.getPort()); // // Thread acceptor = new Thread(new Runnable() { // @Override // public void run() { // // while (isRunning()) { // try { // final Socket socket = getServer().accept(); // // log.info("Accepted client {}:{}", socket.getInetAddress(), getPort()); // // RedisClientHandler handler = new RedisClientHandler(RedisServer.this, socket); // // handlers.add(handler); // // handler.start(); // // } catch (Exception e) { // log.error("Failed to accept socket connection", e); // } // } // // } // }); // // acceptor.start(); // // } // // public ServerSocket getServer() { // return this.server; // } // // public boolean isRunning() { // return this.running; // } // // public void close() { // this.stop(); // } // // public void stop() { // if (this.running) { // this.running = false; // try { // getServer().close(); // } catch (Exception e) { // log.error("Failed to close socket server", e); // throw new IllegalStateException(e); // } // } // } // // public HostConfiguration getHostConfiguration() { // return new HostConfiguration(this.address, this.port); // } // // public HostConfiguration getMasterConfiguration() { // return new HostConfiguration( this.masterHost, Integer.valueOf(this.masterPort) ); // } // // public static void withServer(Action1<RedisServer> action) { // RedisServer server = new RedisServer("localhost", PORT.incrementAndGet()); // // server.start(); // // try { // action.apply(server); // } finally { // server.stop(); // } // } // // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // } // // Path: src/test/java/com/officedrop/redis/failover/utils/ThreadPool.java // public class ThreadPool { // // public static final ExecutorService POOL = Executors.newCachedThreadPool(); // // public static void submit( Runnable r ) { // POOL.submit(r); // } // // } // Path: src/test/java/com/officedrop/redis/failover/NodeTest.java import com.officedrop.redis.failover.jedis.GenericJedisClientFactory; import com.officedrop.redis.failover.redis.RedisServer; import com.officedrop.redis.failover.utils.Action1; import com.officedrop.redis.failover.utils.ThreadPool; import junit.framework.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 1/3/13 * Time: 9:23 AM */ public class NodeTest { private static final Logger log = LoggerFactory.getLogger(NodeTest.class); @Test public void testPingNode() { RedisServer.withServer( new Action1<RedisServer>() { @Override public void apply( RedisServer server) {
final Node node = new Node(server.getHostConfiguration(), GenericJedisClientFactory.INSTANCE, 500, 3);
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/jedis/CommonsJedisPool.java
// Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // }
import com.officedrop.redis.failover.utils.Action1; import org.apache.commons.pool.PoolableObjectFactory; import org.apache.commons.pool.impl.GenericObjectPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.JedisPoolConfig; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList;
package com.officedrop.redis.failover.jedis; /** * User: Maurício Linhares * Date: 1/8/13 * Time: 4:37 PM */ public class CommonsJedisPool implements PoolableObjectFactory, JedisPool { private static final Logger log = LoggerFactory.getLogger(CommonsJedisPool.class); private final JedisFactory factory; private final GenericObjectPool pool;
// Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // } // Path: src/main/java/com/officedrop/redis/failover/jedis/CommonsJedisPool.java import com.officedrop.redis.failover.utils.Action1; import org.apache.commons.pool.PoolableObjectFactory; import org.apache.commons.pool.impl.GenericObjectPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.JedisPoolConfig; import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; package com.officedrop.redis.failover.jedis; /** * User: Maurício Linhares * Date: 1/8/13 * Time: 4:37 PM */ public class CommonsJedisPool implements PoolableObjectFactory, JedisPool { private static final Logger log = LoggerFactory.getLogger(CommonsJedisPool.class); private final JedisFactory factory; private final GenericObjectPool pool;
private final List<Action1<CommonsJedisPool>> listeners = new CopyOnWriteArrayList<Action1<CommonsJedisPool>>();
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/strategy/SimpleMajorityStrategy.java
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // }
import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import java.util.Collection;
package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:02 PM */ public class SimpleMajorityStrategy implements FailureDetectionStrategy { public static final SimpleMajorityStrategy INSTANCE = new SimpleMajorityStrategy(); @Override
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // } // Path: src/main/java/com/officedrop/redis/failover/strategy/SimpleMajorityStrategy.java import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import java.util.Collection; package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:02 PM */ public class SimpleMajorityStrategy implements FailureDetectionStrategy { public static final SimpleMajorityStrategy INSTANCE = new SimpleMajorityStrategy(); @Override
public boolean isAvailable(final HostConfiguration configuration, final Collection<NodeState> states) {
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/strategy/SimpleMajorityStrategy.java
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // }
import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import java.util.Collection;
package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:02 PM */ public class SimpleMajorityStrategy implements FailureDetectionStrategy { public static final SimpleMajorityStrategy INSTANCE = new SimpleMajorityStrategy(); @Override
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // } // Path: src/main/java/com/officedrop/redis/failover/strategy/SimpleMajorityStrategy.java import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import java.util.Collection; package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:02 PM */ public class SimpleMajorityStrategy implements FailureDetectionStrategy { public static final SimpleMajorityStrategy INSTANCE = new SimpleMajorityStrategy(); @Override
public boolean isAvailable(final HostConfiguration configuration, final Collection<NodeState> states) {
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/redis/RedisServer.java
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // }
import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.utils.Action1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger;
}); acceptor.start(); } public ServerSocket getServer() { return this.server; } public boolean isRunning() { return this.running; } public void close() { this.stop(); } public void stop() { if (this.running) { this.running = false; try { getServer().close(); } catch (Exception e) { log.error("Failed to close socket server", e); throw new IllegalStateException(e); } } }
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // } // Path: src/test/java/com/officedrop/redis/failover/redis/RedisServer.java import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.utils.Action1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; }); acceptor.start(); } public ServerSocket getServer() { return this.server; } public boolean isRunning() { return this.running; } public void close() { this.stop(); } public void stop() { if (this.running) { this.running = false; try { getServer().close(); } catch (Exception e) { log.error("Failed to close socket server", e); throw new IllegalStateException(e); } } }
public HostConfiguration getHostConfiguration() {
officedrop/jedis_failover
src/test/java/com/officedrop/redis/failover/redis/RedisServer.java
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // }
import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.utils.Action1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger;
} public boolean isRunning() { return this.running; } public void close() { this.stop(); } public void stop() { if (this.running) { this.running = false; try { getServer().close(); } catch (Exception e) { log.error("Failed to close socket server", e); throw new IllegalStateException(e); } } } public HostConfiguration getHostConfiguration() { return new HostConfiguration(this.address, this.port); } public HostConfiguration getMasterConfiguration() { return new HostConfiguration( this.masterHost, Integer.valueOf(this.masterPort) ); }
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/Action1.java // public interface Action1<T> { // // public void apply(T parameter); // // } // Path: src/test/java/com/officedrop/redis/failover/redis/RedisServer.java import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.utils.Action1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; } public boolean isRunning() { return this.running; } public void close() { this.stop(); } public void stop() { if (this.running) { this.running = false; try { getServer().close(); } catch (Exception e) { log.error("Failed to close socket server", e); throw new IllegalStateException(e); } } } public HostConfiguration getHostConfiguration() { return new HostConfiguration(this.address, this.port); } public HostConfiguration getMasterConfiguration() { return new HostConfiguration( this.masterHost, Integer.valueOf(this.masterPort) ); }
public static void withServer(Action1<RedisServer> action) {
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/Client.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/ClientFunction.java // public interface ClientFunction <R> { // // public R apply( JedisClient client ); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/CircularList.java // public class CircularList<T> implements Iterable<T> { // // private final ReentrantLock lock = new ReentrantLock(); // private final List<T> collection; // private int currentIndex; // // public CircularList(Collection<T> iterator) { // this.collection = new ArrayList<T>(iterator); // } // // public CircularList( T ... items ) { // this(Arrays.asList(items)); // } // // public int getSize() { // return this.collection.size(); // } // // public boolean isEmpty() { // return this.collection.size() == 0; // } // // public T next() { // // try { // this.lock.lock(); // // T item = this.collection.get(this.currentIndex); // // if ( this.currentIndex >= (this.collection.size() - 1) ) { // this.currentIndex = 0; // } else { // this.currentIndex++; // } // // return item; // // } finally { // this.lock.unlock(); // } // // } // // @Override // public Iterator<T> iterator() { // return this.collection.iterator(); // } // }
import com.officedrop.redis.failover.jedis.ClientFunction; import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.CircularList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.BinaryClient; import redis.clients.jedis.SortingParams; import redis.clients.jedis.Tuple; import java.util.*;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/17/12 * Time: 7:04 PM */ public class Client implements JedisClient, NodeManagerListener { private static final Logger log = LoggerFactory.getLogger(Client.class); private ClusterChangeEventSource nodeManager;
// Path: src/main/java/com/officedrop/redis/failover/jedis/ClientFunction.java // public interface ClientFunction <R> { // // public R apply( JedisClient client ); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/CircularList.java // public class CircularList<T> implements Iterable<T> { // // private final ReentrantLock lock = new ReentrantLock(); // private final List<T> collection; // private int currentIndex; // // public CircularList(Collection<T> iterator) { // this.collection = new ArrayList<T>(iterator); // } // // public CircularList( T ... items ) { // this(Arrays.asList(items)); // } // // public int getSize() { // return this.collection.size(); // } // // public boolean isEmpty() { // return this.collection.size() == 0; // } // // public T next() { // // try { // this.lock.lock(); // // T item = this.collection.get(this.currentIndex); // // if ( this.currentIndex >= (this.collection.size() - 1) ) { // this.currentIndex = 0; // } else { // this.currentIndex++; // } // // return item; // // } finally { // this.lock.unlock(); // } // // } // // @Override // public Iterator<T> iterator() { // return this.collection.iterator(); // } // } // Path: src/main/java/com/officedrop/redis/failover/Client.java import com.officedrop.redis.failover.jedis.ClientFunction; import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.CircularList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.BinaryClient; import redis.clients.jedis.SortingParams; import redis.clients.jedis.Tuple; import java.util.*; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/17/12 * Time: 7:04 PM */ public class Client implements JedisClient, NodeManagerListener { private static final Logger log = LoggerFactory.getLogger(Client.class); private ClusterChangeEventSource nodeManager;
private JedisClientFactory factory;
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/Client.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/ClientFunction.java // public interface ClientFunction <R> { // // public R apply( JedisClient client ); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/CircularList.java // public class CircularList<T> implements Iterable<T> { // // private final ReentrantLock lock = new ReentrantLock(); // private final List<T> collection; // private int currentIndex; // // public CircularList(Collection<T> iterator) { // this.collection = new ArrayList<T>(iterator); // } // // public CircularList( T ... items ) { // this(Arrays.asList(items)); // } // // public int getSize() { // return this.collection.size(); // } // // public boolean isEmpty() { // return this.collection.size() == 0; // } // // public T next() { // // try { // this.lock.lock(); // // T item = this.collection.get(this.currentIndex); // // if ( this.currentIndex >= (this.collection.size() - 1) ) { // this.currentIndex = 0; // } else { // this.currentIndex++; // } // // return item; // // } finally { // this.lock.unlock(); // } // // } // // @Override // public Iterator<T> iterator() { // return this.collection.iterator(); // } // }
import com.officedrop.redis.failover.jedis.ClientFunction; import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.CircularList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.BinaryClient; import redis.clients.jedis.SortingParams; import redis.clients.jedis.Tuple; import java.util.*;
package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/17/12 * Time: 7:04 PM */ public class Client implements JedisClient, NodeManagerListener { private static final Logger log = LoggerFactory.getLogger(Client.class); private ClusterChangeEventSource nodeManager; private JedisClientFactory factory; private JedisClient master;
// Path: src/main/java/com/officedrop/redis/failover/jedis/ClientFunction.java // public interface ClientFunction <R> { // // public R apply( JedisClient client ); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/CircularList.java // public class CircularList<T> implements Iterable<T> { // // private final ReentrantLock lock = new ReentrantLock(); // private final List<T> collection; // private int currentIndex; // // public CircularList(Collection<T> iterator) { // this.collection = new ArrayList<T>(iterator); // } // // public CircularList( T ... items ) { // this(Arrays.asList(items)); // } // // public int getSize() { // return this.collection.size(); // } // // public boolean isEmpty() { // return this.collection.size() == 0; // } // // public T next() { // // try { // this.lock.lock(); // // T item = this.collection.get(this.currentIndex); // // if ( this.currentIndex >= (this.collection.size() - 1) ) { // this.currentIndex = 0; // } else { // this.currentIndex++; // } // // return item; // // } finally { // this.lock.unlock(); // } // // } // // @Override // public Iterator<T> iterator() { // return this.collection.iterator(); // } // } // Path: src/main/java/com/officedrop/redis/failover/Client.java import com.officedrop.redis.failover.jedis.ClientFunction; import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.CircularList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.BinaryClient; import redis.clients.jedis.SortingParams; import redis.clients.jedis.Tuple; import java.util.*; package com.officedrop.redis.failover; /** * User: Maurício Linhares * Date: 12/17/12 * Time: 7:04 PM */ public class Client implements JedisClient, NodeManagerListener { private static final Logger log = LoggerFactory.getLogger(Client.class); private ClusterChangeEventSource nodeManager; private JedisClientFactory factory; private JedisClient master;
private CircularList<JedisClient> slaves;
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/Client.java
// Path: src/main/java/com/officedrop/redis/failover/jedis/ClientFunction.java // public interface ClientFunction <R> { // // public R apply( JedisClient client ); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/CircularList.java // public class CircularList<T> implements Iterable<T> { // // private final ReentrantLock lock = new ReentrantLock(); // private final List<T> collection; // private int currentIndex; // // public CircularList(Collection<T> iterator) { // this.collection = new ArrayList<T>(iterator); // } // // public CircularList( T ... items ) { // this(Arrays.asList(items)); // } // // public int getSize() { // return this.collection.size(); // } // // public boolean isEmpty() { // return this.collection.size() == 0; // } // // public T next() { // // try { // this.lock.lock(); // // T item = this.collection.get(this.currentIndex); // // if ( this.currentIndex >= (this.collection.size() - 1) ) { // this.currentIndex = 0; // } else { // this.currentIndex++; // } // // return item; // // } finally { // this.lock.unlock(); // } // // } // // @Override // public Iterator<T> iterator() { // return this.collection.iterator(); // } // }
import com.officedrop.redis.failover.jedis.ClientFunction; import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.CircularList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.BinaryClient; import redis.clients.jedis.SortingParams; import redis.clients.jedis.Tuple; import java.util.*;
private void updateMaster() { this.quitMaster(); this.master = this.factory.create(this.nodeManager.getLastClusterStatus().getMaster()); } private void updateSlaves() { this.quitSlaves(); List<JedisClient> slaveClients = new ArrayList<JedisClient>(); for ( HostConfiguration configuration : this.nodeManager.getLastClusterStatus().getSlaves() ) { slaveClients.add(this.factory.create(configuration)); } this.slaves = new CircularList<JedisClient>(slaveClients); } private void quitMaster() { if (this.master != null) { try { this.master.quit(); } catch (Exception e) { log.error("Failed while closing the connection to master", e); } } } @Override public Long del(final String... keys) {
// Path: src/main/java/com/officedrop/redis/failover/jedis/ClientFunction.java // public interface ClientFunction <R> { // // public R apply( JedisClient client ); // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClient.java // public interface JedisClient extends BinaryJedisCommands, JedisActions { // // } // // Path: src/main/java/com/officedrop/redis/failover/jedis/JedisClientFactory.java // public interface JedisClientFactory { // // public JedisClient create( HostConfiguration configuration ); // // } // // Path: src/main/java/com/officedrop/redis/failover/utils/CircularList.java // public class CircularList<T> implements Iterable<T> { // // private final ReentrantLock lock = new ReentrantLock(); // private final List<T> collection; // private int currentIndex; // // public CircularList(Collection<T> iterator) { // this.collection = new ArrayList<T>(iterator); // } // // public CircularList( T ... items ) { // this(Arrays.asList(items)); // } // // public int getSize() { // return this.collection.size(); // } // // public boolean isEmpty() { // return this.collection.size() == 0; // } // // public T next() { // // try { // this.lock.lock(); // // T item = this.collection.get(this.currentIndex); // // if ( this.currentIndex >= (this.collection.size() - 1) ) { // this.currentIndex = 0; // } else { // this.currentIndex++; // } // // return item; // // } finally { // this.lock.unlock(); // } // // } // // @Override // public Iterator<T> iterator() { // return this.collection.iterator(); // } // } // Path: src/main/java/com/officedrop/redis/failover/Client.java import com.officedrop.redis.failover.jedis.ClientFunction; import com.officedrop.redis.failover.jedis.JedisClient; import com.officedrop.redis.failover.jedis.JedisClientFactory; import com.officedrop.redis.failover.utils.CircularList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.BinaryClient; import redis.clients.jedis.SortingParams; import redis.clients.jedis.Tuple; import java.util.*; private void updateMaster() { this.quitMaster(); this.master = this.factory.create(this.nodeManager.getLastClusterStatus().getMaster()); } private void updateSlaves() { this.quitSlaves(); List<JedisClient> slaveClients = new ArrayList<JedisClient>(); for ( HostConfiguration configuration : this.nodeManager.getLastClusterStatus().getSlaves() ) { slaveClients.add(this.factory.create(configuration)); } this.slaves = new CircularList<JedisClient>(slaveClients); } private void quitMaster() { if (this.master != null) { try { this.master.quit(); } catch (Exception e) { log.error("Failed while closing the connection to master", e); } } } @Override public Long del(final String... keys) {
return this.doAction(ClientType.MASTER, new ClientFunction<Long>() {
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/strategy/LatencyFailoverSelectionStrategy.java
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // }
import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import java.util.*;
package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:18 PM */ public class LatencyFailoverSelectionStrategy implements FailoverSelectionStrategy { public static final LatencyFailoverSelectionStrategy INSTANCE = new LatencyFailoverSelectionStrategy(); @Override
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // } // Path: src/main/java/com/officedrop/redis/failover/strategy/LatencyFailoverSelectionStrategy.java import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import java.util.*; package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:18 PM */ public class LatencyFailoverSelectionStrategy implements FailoverSelectionStrategy { public static final LatencyFailoverSelectionStrategy INSTANCE = new LatencyFailoverSelectionStrategy(); @Override
public HostConfiguration selectMaster(Set<HostConfiguration> hosts, final Map<String, Map<HostConfiguration, NodeState>> nodeReports) {
officedrop/jedis_failover
src/main/java/com/officedrop/redis/failover/strategy/LatencyFailoverSelectionStrategy.java
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // }
import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import java.util.*;
package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:18 PM */ public class LatencyFailoverSelectionStrategy implements FailoverSelectionStrategy { public static final LatencyFailoverSelectionStrategy INSTANCE = new LatencyFailoverSelectionStrategy(); @Override
// Path: src/main/java/com/officedrop/redis/failover/HostConfiguration.java // public class HostConfiguration { // // private final String host; // private final int port; // private final int timeout; // private final int database; // // public HostConfiguration(String host, int port) { // this( host, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout) { // this( host, port, timeout, Protocol.DEFAULT_DATABASE ); // } // // public HostConfiguration(String host, int port, int timeout, int database) { // // if ( host == null || host.trim().isEmpty() ) { // throw new IllegalArgumentException("'host' can not be null"); // } // // this.port = port; // this.timeout = timeout; // this.host = host; // this.database = database; // } // // public int getPort() { // return port; // } // // public String getHost() { // return host; // } // // public int getTimeout() { // return this.timeout; // } // // public int getDatabase() { // return this.database; // } // // public String asHost() { // return String.format("%s:%s", this.getHost(), this.getPort()); // } // // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof HostConfiguration)) return false; // // HostConfiguration that = (HostConfiguration) o; // // if (port != that.port) return false; // if (database != that.database) return false; // if (!host.equals(that.host)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = host.hashCode(); // result = 31 * result + port; // return result; // } // // @Override // public String toString() { // return "HostConfiguration{" + // "host='" + host + '\'' + // ", port=" + port + // ", timeout=" + timeout + // '}'; // } // // } // // Path: src/main/java/com/officedrop/redis/failover/NodeState.java // public class NodeState { // // public static final NodeState OFFLINE_STATE = new NodeState(-1, true); // // private final long latency; // private final boolean offline; // // private NodeState( long latency, boolean offline ) { // this.latency = latency; // this.offline = offline; // } // // public NodeState( long latency ) { // this(latency, false); // } // // public long getLatency() { // return latency; // } // // public boolean isOffline() { // return offline; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (!(o instanceof NodeState)) return false; // // NodeState nodeState = (NodeState) o; // // if (latency != nodeState.latency) return false; // if (offline != nodeState.offline) return false; // // return true; // } // // @Override // public int hashCode() { // int result = (int) (latency ^ (latency >>> 32)); // result = 31 * result + (offline ? 1 : 0); // return result; // } // // @Override // public String toString() { // return "NodeState{" + // "latency=" + latency + // ", offline=" + offline + // '}'; // } // } // Path: src/main/java/com/officedrop/redis/failover/strategy/LatencyFailoverSelectionStrategy.java import com.officedrop.redis.failover.HostConfiguration; import com.officedrop.redis.failover.NodeState; import java.util.*; package com.officedrop.redis.failover.strategy; /** * User: Maurício Linhares * Date: 1/5/13 * Time: 5:18 PM */ public class LatencyFailoverSelectionStrategy implements FailoverSelectionStrategy { public static final LatencyFailoverSelectionStrategy INSTANCE = new LatencyFailoverSelectionStrategy(); @Override
public HostConfiguration selectMaster(Set<HostConfiguration> hosts, final Map<String, Map<HostConfiguration, NodeState>> nodeReports) {
krazykira/VidEffects
videffects/src/main/java/com/sherazkhilji/videffects/model/Converter.java
// Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/ConvertResultListener.java // public interface ConvertResultListener { // // void onSuccess(); // // void onFail(); // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // }
import android.graphics.SurfaceTexture; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.media.MediaExtractor; import android.media.MediaFormat; import android.media.MediaMuxer; import android.opengl.EGL14; import android.opengl.EGLConfig; import android.opengl.EGLContext; import android.opengl.EGLDisplay; import android.opengl.EGLExt; import android.opengl.EGLSurface; import android.opengl.GLUtils; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.Surface; import androidx.annotation.RequiresApi; import com.sherazkhilji.videffects.interfaces.ConvertResultListener; import com.sherazkhilji.videffects.interfaces.Filter; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; import static android.media.MediaCodec.BUFFER_FLAG_END_OF_STREAM; import static android.opengl.EGLExt.EGL_RECORDABLE_ANDROID;
private long mediaCodedTimeoutUs = 1000L; private final Object lock = new Object(); private volatile boolean frameAvailable = false; private EGLDisplay eglDisplay = null; private EGLContext eglContext = null; private EGLSurface eglSurface = null; public Converter() { } public Converter(String path) { setMetadata(path); try { videoExtractor.setDataSource(path); audioExtractor.setDataSource(path); } catch (IOException e) { e.printStackTrace(); } } private void setMetadata(String path) { Metadata metadata = new MetadataExtractor().extract(path); if (metadata != null) { width = (int) metadata.getWidth(); height = (int) metadata.getHeight(); bitrate = metadata.getBitrate(); } }
// Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/ConvertResultListener.java // public interface ConvertResultListener { // // void onSuccess(); // // void onFail(); // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // } // Path: videffects/src/main/java/com/sherazkhilji/videffects/model/Converter.java import android.graphics.SurfaceTexture; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.media.MediaExtractor; import android.media.MediaFormat; import android.media.MediaMuxer; import android.opengl.EGL14; import android.opengl.EGLConfig; import android.opengl.EGLContext; import android.opengl.EGLDisplay; import android.opengl.EGLExt; import android.opengl.EGLSurface; import android.opengl.GLUtils; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.Surface; import androidx.annotation.RequiresApi; import com.sherazkhilji.videffects.interfaces.ConvertResultListener; import com.sherazkhilji.videffects.interfaces.Filter; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; import static android.media.MediaCodec.BUFFER_FLAG_END_OF_STREAM; import static android.opengl.EGLExt.EGL_RECORDABLE_ANDROID; private long mediaCodedTimeoutUs = 1000L; private final Object lock = new Object(); private volatile boolean frameAvailable = false; private EGLDisplay eglDisplay = null; private EGLContext eglContext = null; private EGLSurface eglSurface = null; public Converter() { } public Converter(String path) { setMetadata(path); try { videoExtractor.setDataSource(path); audioExtractor.setDataSource(path); } catch (IOException e) { e.printStackTrace(); } } private void setMetadata(String path) { Metadata metadata = new MetadataExtractor().extract(path); if (metadata != null) { width = (int) metadata.getWidth(); height = (int) metadata.getHeight(); bitrate = metadata.getBitrate(); } }
public void startConverter(Filter filter, String outPath, ConvertResultListener listener) {
krazykira/VidEffects
videffects/src/main/java/com/sherazkhilji/videffects/model/Converter.java
// Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/ConvertResultListener.java // public interface ConvertResultListener { // // void onSuccess(); // // void onFail(); // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // }
import android.graphics.SurfaceTexture; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.media.MediaExtractor; import android.media.MediaFormat; import android.media.MediaMuxer; import android.opengl.EGL14; import android.opengl.EGLConfig; import android.opengl.EGLContext; import android.opengl.EGLDisplay; import android.opengl.EGLExt; import android.opengl.EGLSurface; import android.opengl.GLUtils; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.Surface; import androidx.annotation.RequiresApi; import com.sherazkhilji.videffects.interfaces.ConvertResultListener; import com.sherazkhilji.videffects.interfaces.Filter; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; import static android.media.MediaCodec.BUFFER_FLAG_END_OF_STREAM; import static android.opengl.EGLExt.EGL_RECORDABLE_ANDROID;
private long mediaCodedTimeoutUs = 1000L; private final Object lock = new Object(); private volatile boolean frameAvailable = false; private EGLDisplay eglDisplay = null; private EGLContext eglContext = null; private EGLSurface eglSurface = null; public Converter() { } public Converter(String path) { setMetadata(path); try { videoExtractor.setDataSource(path); audioExtractor.setDataSource(path); } catch (IOException e) { e.printStackTrace(); } } private void setMetadata(String path) { Metadata metadata = new MetadataExtractor().extract(path); if (metadata != null) { width = (int) metadata.getWidth(); height = (int) metadata.getHeight(); bitrate = metadata.getBitrate(); } }
// Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/ConvertResultListener.java // public interface ConvertResultListener { // // void onSuccess(); // // void onFail(); // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // } // Path: videffects/src/main/java/com/sherazkhilji/videffects/model/Converter.java import android.graphics.SurfaceTexture; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.media.MediaExtractor; import android.media.MediaFormat; import android.media.MediaMuxer; import android.opengl.EGL14; import android.opengl.EGLConfig; import android.opengl.EGLContext; import android.opengl.EGLDisplay; import android.opengl.EGLExt; import android.opengl.EGLSurface; import android.opengl.GLUtils; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.Surface; import androidx.annotation.RequiresApi; import com.sherazkhilji.videffects.interfaces.ConvertResultListener; import com.sherazkhilji.videffects.interfaces.Filter; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; import static android.media.MediaCodec.BUFFER_FLAG_END_OF_STREAM; import static android.opengl.EGLExt.EGL_RECORDABLE_ANDROID; private long mediaCodedTimeoutUs = 1000L; private final Object lock = new Object(); private volatile boolean frameAvailable = false; private EGLDisplay eglDisplay = null; private EGLContext eglContext = null; private EGLSurface eglSurface = null; public Converter() { } public Converter(String path) { setMetadata(path); try { videoExtractor.setDataSource(path); audioExtractor.setDataSource(path); } catch (IOException e) { e.printStackTrace(); } } private void setMetadata(String path) { Metadata metadata = new MetadataExtractor().extract(path); if (metadata != null) { width = (int) metadata.getWidth(); height = (int) metadata.getHeight(); bitrate = metadata.getBitrate(); } }
public void startConverter(Filter filter, String outPath, ConvertResultListener listener) {
krazykira/VidEffects
videffects/src/main/java/com/sherazkhilji/videffects/model/BaseRenderer.java
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public static final int FLOAT_SIZE_BYTES = 4;
import android.opengl.GLES20; import android.opengl.Matrix; import android.util.Log; import static android.opengl.GLES11Ext.GL_TEXTURE_EXTERNAL_OES; import static com.sherazkhilji.videffects.Constants.FLOAT_SIZE_BYTES;
protected abstract int getFragmentShader(); protected int getTexture() { return textureHandles[0]; } protected float[] getTransformMatrix() { return texMatrix; } private int createProgram() { int program = GLES20.glCreateProgram(); if (program != 0) { GLES20.glAttachShader(program, getVertexShader()); GLES20.glAttachShader(program, getFragmentShader()); GLES20.glLinkProgram(program); GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != GLES20.GL_TRUE) { Log.e(TAG, "Could not link program: "); Log.e(TAG, GLES20.glGetProgramInfoLog(program)); GLES20.glDeleteProgram(program); program = 0; } } return program; } protected void init() { GLES20.glGenBuffers(2, bufferHandles, 0); GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferHandles[0]);
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public static final int FLOAT_SIZE_BYTES = 4; // Path: videffects/src/main/java/com/sherazkhilji/videffects/model/BaseRenderer.java import android.opengl.GLES20; import android.opengl.Matrix; import android.util.Log; import static android.opengl.GLES11Ext.GL_TEXTURE_EXTERNAL_OES; import static com.sherazkhilji.videffects.Constants.FLOAT_SIZE_BYTES; protected abstract int getFragmentShader(); protected int getTexture() { return textureHandles[0]; } protected float[] getTransformMatrix() { return texMatrix; } private int createProgram() { int program = GLES20.glCreateProgram(); if (program != 0) { GLES20.glAttachShader(program, getVertexShader()); GLES20.glAttachShader(program, getFragmentShader()); GLES20.glLinkProgram(program); GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != GLES20.GL_TRUE) { Log.e(TAG, "Could not link program: "); Log.e(TAG, GLES20.glGetProgramInfoLog(program)); GLES20.glDeleteProgram(program); program = 0; } } return program; } protected void init() { GLES20.glGenBuffers(2, bufferHandles, 0); GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferHandles[0]);
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, Utils.VERTICES.length * FLOAT_SIZE_BYTES, Utils.getVertexBuffer(), GLES20.GL_DYNAMIC_DRAW);
krazykira/VidEffects
videffects/src/main/java/com/sherazkhilji/videffects/filter/HueFilter.java
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public final class Constants { // // public static final int FLOAT_SIZE_BYTES = 4; // // public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" // + "uniform mat4 uSTMatrix;\n" // + "attribute vec4 aPosition;\n" // + "attribute vec4 aTextureCoord;\n" // + "varying vec2 vTextureCoord;\n" // + "void main() {\n" // + " gl_Position = uMVPMatrix * aPosition;\n" // + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" // + "}\n"; // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // }
import com.sherazkhilji.videffects.Constants; import com.sherazkhilji.videffects.interfaces.Filter; import java.util.Locale;
+ "void main() {\n" + "vec4 kRGBToYPrime = vec4 (0.299, 0.587, 0.114, 0.0);\n" + "vec4 kRGBToI = vec4 (0.595716, -0.274453, -0.321263, 0.0);\n" + "vec4 kRGBToQ = vec4 (0.211456, -0.522591, 0.31135, 0.0);\n" + "vec4 kYIQToR = vec4 (1.0, 0.9563, 0.6210, 0.0);\n" + "vec4 kYIQToG = vec4 (1.0, -0.2721, -0.6474, 0.0);\n" + "vec4 kYIQToB = vec4 (1.0, -1.1070, 1.7046, 0.0);\n" + "vec4 color = texture2D(sTexture, vTextureCoord);\n" + "float YPrime = dot(color, kRGBToYPrime);\n" + "float I = dot(color, kRGBToI);\n" + "float Q = dot(color, kRGBToQ);\n" + "float chroma = sqrt (I * I + Q * Q);\n" + "Q = chroma * sin (intensity);\n" + "I = chroma * cos (intensity);\n" + "vec4 yIQ = vec4 (YPrime, I, Q, 0.0);\n" + "color.r = dot (yIQ, kYIQToR);\n" + "color.g = dot (yIQ, kYIQToG);\n" + "color.b = dot (yIQ, kYIQToB);\n" + "gl_FragColor = color;\n" + "}\n"; private float intensity; @Override public void setIntensity(float intensity) { this.intensity = ((intensity - 45) / 45f + 0.5f) * -1; } @Override public String getVertexShader() {
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public final class Constants { // // public static final int FLOAT_SIZE_BYTES = 4; // // public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" // + "uniform mat4 uSTMatrix;\n" // + "attribute vec4 aPosition;\n" // + "attribute vec4 aTextureCoord;\n" // + "varying vec2 vTextureCoord;\n" // + "void main() {\n" // + " gl_Position = uMVPMatrix * aPosition;\n" // + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" // + "}\n"; // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // } // Path: videffects/src/main/java/com/sherazkhilji/videffects/filter/HueFilter.java import com.sherazkhilji.videffects.Constants; import com.sherazkhilji.videffects.interfaces.Filter; import java.util.Locale; + "void main() {\n" + "vec4 kRGBToYPrime = vec4 (0.299, 0.587, 0.114, 0.0);\n" + "vec4 kRGBToI = vec4 (0.595716, -0.274453, -0.321263, 0.0);\n" + "vec4 kRGBToQ = vec4 (0.211456, -0.522591, 0.31135, 0.0);\n" + "vec4 kYIQToR = vec4 (1.0, 0.9563, 0.6210, 0.0);\n" + "vec4 kYIQToG = vec4 (1.0, -0.2721, -0.6474, 0.0);\n" + "vec4 kYIQToB = vec4 (1.0, -1.1070, 1.7046, 0.0);\n" + "vec4 color = texture2D(sTexture, vTextureCoord);\n" + "float YPrime = dot(color, kRGBToYPrime);\n" + "float I = dot(color, kRGBToI);\n" + "float Q = dot(color, kRGBToQ);\n" + "float chroma = sqrt (I * I + Q * Q);\n" + "Q = chroma * sin (intensity);\n" + "I = chroma * cos (intensity);\n" + "vec4 yIQ = vec4 (YPrime, I, Q, 0.0);\n" + "color.r = dot (yIQ, kYIQToR);\n" + "color.g = dot (yIQ, kYIQToG);\n" + "color.b = dot (yIQ, kYIQToB);\n" + "gl_FragColor = color;\n" + "}\n"; private float intensity; @Override public void setIntensity(float intensity) { this.intensity = ((intensity - 45) / 45f + 0.5f) * -1; } @Override public String getVertexShader() {
return Constants.DEFAULT_VERTEX_SHADER;
krazykira/VidEffects
videffects/src/main/java/com/sherazkhilji/videffects/filter/GrainFilter.java
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public final class Constants { // // public static final int FLOAT_SIZE_BYTES = 4; // // public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" // + "uniform mat4 uSTMatrix;\n" // + "attribute vec4 aPosition;\n" // + "attribute vec4 aTextureCoord;\n" // + "varying vec2 vTextureCoord;\n" // + "void main() {\n" // + " gl_Position = uMVPMatrix * aPosition;\n" // + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" // + "}\n"; // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // }
import android.os.Parcel; import com.sherazkhilji.videffects.Constants; import com.sherazkhilji.videffects.interfaces.Filter; import java.util.Locale; import java.util.concurrent.ThreadLocalRandom;
+ "}\n" + "void main() {\n" + " seed[0] = %f;\n" + " seed[1] = %f;\n" + " scale = %f;\n" + " stepX = " + 0.5f / width + ";\n" + " stepY = " + 0.5f / height + ";\n" + " float noise = texture2D(tex_sampler_1, vTextureCoord + vec2(-stepX, -stepY)).r * 0.224;\n" + " noise += texture2D(tex_sampler_1, vTextureCoord + vec2(-stepX, stepY)).r * 0.224;\n" + " noise += texture2D(tex_sampler_1, vTextureCoord + vec2(stepX, -stepY)).r * 0.224;\n" + " noise += texture2D(tex_sampler_1, vTextureCoord + vec2(stepX, stepY)).r * 0.224;\n" + " noise += 0.4448;\n" + " noise *= scale;\n" + " vec4 color = texture2D(tex_sampler_0, vTextureCoord);\n" + " float energy = 0.33333 * color.r + 0.33333 * color.g + 0.33333 * color.b;\n" + " float mask = (1.0 - sqrt(energy));\n" + " float weight = 1.0 - 1.333 * mask * noise;\n" + " gl_FragColor = vec4(color.rgb * weight, color.a);\n" + " gl_FragColor = gl_FragColor+vec4(rand(vTextureCoord + seed), rand(vTextureCoord + seed),rand(vTextureCoord + seed),1);\n" + "}\n"; } @Override public void setIntensity(float intensity) { this.intensity = intensity; } @Override public String getVertexShader() {
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public final class Constants { // // public static final int FLOAT_SIZE_BYTES = 4; // // public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" // + "uniform mat4 uSTMatrix;\n" // + "attribute vec4 aPosition;\n" // + "attribute vec4 aTextureCoord;\n" // + "varying vec2 vTextureCoord;\n" // + "void main() {\n" // + " gl_Position = uMVPMatrix * aPosition;\n" // + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" // + "}\n"; // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // } // Path: videffects/src/main/java/com/sherazkhilji/videffects/filter/GrainFilter.java import android.os.Parcel; import com.sherazkhilji.videffects.Constants; import com.sherazkhilji.videffects.interfaces.Filter; import java.util.Locale; import java.util.concurrent.ThreadLocalRandom; + "}\n" + "void main() {\n" + " seed[0] = %f;\n" + " seed[1] = %f;\n" + " scale = %f;\n" + " stepX = " + 0.5f / width + ";\n" + " stepY = " + 0.5f / height + ";\n" + " float noise = texture2D(tex_sampler_1, vTextureCoord + vec2(-stepX, -stepY)).r * 0.224;\n" + " noise += texture2D(tex_sampler_1, vTextureCoord + vec2(-stepX, stepY)).r * 0.224;\n" + " noise += texture2D(tex_sampler_1, vTextureCoord + vec2(stepX, -stepY)).r * 0.224;\n" + " noise += texture2D(tex_sampler_1, vTextureCoord + vec2(stepX, stepY)).r * 0.224;\n" + " noise += 0.4448;\n" + " noise *= scale;\n" + " vec4 color = texture2D(tex_sampler_0, vTextureCoord);\n" + " float energy = 0.33333 * color.r + 0.33333 * color.g + 0.33333 * color.b;\n" + " float mask = (1.0 - sqrt(energy));\n" + " float weight = 1.0 - 1.333 * mask * noise;\n" + " gl_FragColor = vec4(color.rgb * weight, color.a);\n" + " gl_FragColor = gl_FragColor+vec4(rand(vTextureCoord + seed), rand(vTextureCoord + seed),rand(vTextureCoord + seed),1);\n" + "}\n"; } @Override public void setIntensity(float intensity) { this.intensity = intensity; } @Override public String getVertexShader() {
return Constants.DEFAULT_VERTEX_SHADER;
krazykira/VidEffects
videffects/src/main/java/com/sherazkhilji/videffects/filter/NoEffectFilter.java
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public final class Constants { // // public static final int FLOAT_SIZE_BYTES = 4; // // public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" // + "uniform mat4 uSTMatrix;\n" // + "attribute vec4 aPosition;\n" // + "attribute vec4 aTextureCoord;\n" // + "varying vec2 vTextureCoord;\n" // + "void main() {\n" // + " gl_Position = uMVPMatrix * aPosition;\n" // + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" // + "}\n"; // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // }
import android.util.Log; import com.sherazkhilji.videffects.Constants; import com.sherazkhilji.videffects.interfaces.Filter;
package com.sherazkhilji.videffects.filter; public class NoEffectFilter implements Filter { private static final String TAG = "NoEffectFilter"; private static final String FRAGMENT_SHADER = "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;\n" + "varying vec2 vTextureCoord;\n" + "uniform samplerExternalOES sTexture;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" + "}\n"; @Override public String getVertexShader() {
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public final class Constants { // // public static final int FLOAT_SIZE_BYTES = 4; // // public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" // + "uniform mat4 uSTMatrix;\n" // + "attribute vec4 aPosition;\n" // + "attribute vec4 aTextureCoord;\n" // + "varying vec2 vTextureCoord;\n" // + "void main() {\n" // + " gl_Position = uMVPMatrix * aPosition;\n" // + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" // + "}\n"; // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // } // Path: videffects/src/main/java/com/sherazkhilji/videffects/filter/NoEffectFilter.java import android.util.Log; import com.sherazkhilji.videffects.Constants; import com.sherazkhilji.videffects.interfaces.Filter; package com.sherazkhilji.videffects.filter; public class NoEffectFilter implements Filter { private static final String TAG = "NoEffectFilter"; private static final String FRAGMENT_SHADER = "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float;\n" + "varying vec2 vTextureCoord;\n" + "uniform samplerExternalOES sTexture;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" + "}\n"; @Override public String getVertexShader() {
return Constants.DEFAULT_VERTEX_SHADER;
krazykira/VidEffects
videffects/src/main/java/com/sherazkhilji/videffects/filter/AutoFixFilter.java
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public final class Constants { // // public static final int FLOAT_SIZE_BYTES = 4; // // public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" // + "uniform mat4 uSTMatrix;\n" // + "attribute vec4 aPosition;\n" // + "attribute vec4 aTextureCoord;\n" // + "varying vec2 vTextureCoord;\n" // + "void main() {\n" // + " gl_Position = uMVPMatrix * aPosition;\n" // + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" // + "}\n"; // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // }
import com.sherazkhilji.videffects.Constants; import com.sherazkhilji.videffects.interfaces.Filter;
package com.sherazkhilji.videffects.filter; public class AutoFixFilter implements Filter { private static final float SHIFT_SCALE = 1.0f / 256f; private static final float HIST_OFFSET = 0.5f / 766f; private static final float HIST_SCALE = 765f / 766f; private static final float DENSITY_OFFSET = 0.5f / 1024f; private static final float DENSITY_SCALE = 1023f / 1024f; private float intensity = 0.0F; private String shader; @Override public void setIntensity(float strength) { this.intensity = strength; } @Override public String getVertexShader() {
// Path: videffects/src/main/java/com/sherazkhilji/videffects/Constants.java // public final class Constants { // // public static final int FLOAT_SIZE_BYTES = 4; // // public static final String DEFAULT_VERTEX_SHADER = "uniform mat4 uMVPMatrix;\n" // + "uniform mat4 uSTMatrix;\n" // + "attribute vec4 aPosition;\n" // + "attribute vec4 aTextureCoord;\n" // + "varying vec2 vTextureCoord;\n" // + "void main() {\n" // + " gl_Position = uMVPMatrix * aPosition;\n" // + " vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" // + "}\n"; // } // // Path: videffects/src/main/java/com/sherazkhilji/videffects/interfaces/Filter.java // public interface Filter { // // public String getVertexShader(); // // public String getFragmentShader(); // // public void setIntensity(float intensity); // } // Path: videffects/src/main/java/com/sherazkhilji/videffects/filter/AutoFixFilter.java import com.sherazkhilji.videffects.Constants; import com.sherazkhilji.videffects.interfaces.Filter; package com.sherazkhilji.videffects.filter; public class AutoFixFilter implements Filter { private static final float SHIFT_SCALE = 1.0f / 256f; private static final float HIST_OFFSET = 0.5f / 766f; private static final float HIST_SCALE = 765f / 766f; private static final float DENSITY_OFFSET = 0.5f / 1024f; private static final float DENSITY_SCALE = 1023f / 1024f; private float intensity = 0.0F; private String shader; @Override public void setIntensity(float strength) { this.intensity = strength; } @Override public String getVertexShader() {
return Constants.DEFAULT_VERTEX_SHADER;
JimSeker/saveData
LvCursorDemo/app/src/main/java/edu/cs4730/lvcursordemo/CustomCursorAdapter.java
// Path: LvCursorDemo/app/src/main/java/edu/cs4730/lvcursordemo/db/DatabaseHelper.java // public class DatabaseHelper extends SupportSQLiteOpenHelper.Callback { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_CODE = "code"; // public static final String KEY_NAME = "name"; // public static final String KEY_CONTINENT = "continent"; // public static final String KEY_REGION = "region"; // // private static final String TAG = "DatabaseHelper"; // public static final String DATABASE_NAME = "World"; // public static final String SQLITE_TABLE = "Country"; // public static final int DATABASE_VERSION = 1; // // // private static final String DATABASE_CREATE = // "CREATE TABLE if not exists " + SQLITE_TABLE + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_CODE + "," + // KEY_NAME + "," + // KEY_CONTINENT + "," + // KEY_REGION + "," + // " UNIQUE (" + KEY_CODE +"));"; // // // // DatabaseHelper() { // super(DATABASE_VERSION); // } // // // @Override // public void onCreate(SupportSQLiteDatabase db) { // Log.w(TAG, DATABASE_CREATE); // db.execSQL(DATABASE_CREATE); // } // // @Override // public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { // Log.w(TAG, "Upgrading database from version " + oldVersion + " to " // + newVersion + ", which will destroy all old data"); // db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE); // onCreate(db); // } // }
import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.cursoradapter.widget.CursorAdapter; import edu.cs4730.lvcursordemo.db.DatabaseHelper;
package edu.cs4730.lvcursordemo; public class CustomCursorAdapter extends CursorAdapter implements OnClickListener { String TAG = "CustomAdapter"; Context myContext; private LayoutInflater inflater; public CustomCursorAdapter(Context context, Cursor c) { super(context, c, 0); //0 no content observer on the cursor. use CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER for //needed for the toast later in the code. myContext = context; //set the inflater for the newView inflater = LayoutInflater.from(context); } /** * setup the view from our layout, no data is set here. Just create the view. */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return inflater.inflate(R.layout.country_custom_info, parent, false); } /** * BindView, is where we set the data fro the view. */ @Override public void bindView(View view, Context context, Cursor cursor) { // here we are setting our data // that means, take the data from the cursor and put it in views TextView textViewcode = view.findViewById(R.id.codeC); //textViewcode.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
// Path: LvCursorDemo/app/src/main/java/edu/cs4730/lvcursordemo/db/DatabaseHelper.java // public class DatabaseHelper extends SupportSQLiteOpenHelper.Callback { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_CODE = "code"; // public static final String KEY_NAME = "name"; // public static final String KEY_CONTINENT = "continent"; // public static final String KEY_REGION = "region"; // // private static final String TAG = "DatabaseHelper"; // public static final String DATABASE_NAME = "World"; // public static final String SQLITE_TABLE = "Country"; // public static final int DATABASE_VERSION = 1; // // // private static final String DATABASE_CREATE = // "CREATE TABLE if not exists " + SQLITE_TABLE + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_CODE + "," + // KEY_NAME + "," + // KEY_CONTINENT + "," + // KEY_REGION + "," + // " UNIQUE (" + KEY_CODE +"));"; // // // // DatabaseHelper() { // super(DATABASE_VERSION); // } // // // @Override // public void onCreate(SupportSQLiteDatabase db) { // Log.w(TAG, DATABASE_CREATE); // db.execSQL(DATABASE_CREATE); // } // // @Override // public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { // Log.w(TAG, "Upgrading database from version " + oldVersion + " to " // + newVersion + ", which will destroy all old data"); // db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE); // onCreate(db); // } // } // Path: LvCursorDemo/app/src/main/java/edu/cs4730/lvcursordemo/CustomCursorAdapter.java import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.cursoradapter.widget.CursorAdapter; import edu.cs4730.lvcursordemo.db.DatabaseHelper; package edu.cs4730.lvcursordemo; public class CustomCursorAdapter extends CursorAdapter implements OnClickListener { String TAG = "CustomAdapter"; Context myContext; private LayoutInflater inflater; public CustomCursorAdapter(Context context, Cursor c) { super(context, c, 0); //0 no content observer on the cursor. use CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER for //needed for the toast later in the code. myContext = context; //set the inflater for the newView inflater = LayoutInflater.from(context); } /** * setup the view from our layout, no data is set here. Just create the view. */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return inflater.inflate(R.layout.country_custom_info, parent, false); } /** * BindView, is where we set the data fro the view. */ @Override public void bindView(View view, Context context, Cursor cursor) { // here we are setting our data // that means, take the data from the cursor and put it in views TextView textViewcode = view.findViewById(R.id.codeC); //textViewcode.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
textViewcode.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.KEY_CODE)));
JimSeker/saveData
sqliteDBDemo/app/src/main/java/edu/cs4730/sqlitedbdemo/myAdapter.java
// Path: sqliteDBDemo/app/src/main/java/edu/cs4730/sqlitedbdemo/db/mySQLiteHelper.java // public class mySQLiteHelper extends SupportSQLiteOpenHelper.Callback { // // private static final String TAG = "mySQLiteHelper"; // // //column names for the table. // public static final String KEY_NAME = "Name"; // public static final String KEY_SCORE = "Score"; // public static final String KEY_ROWID = "_id"; //required field for the cursorAdapter // // public static final String DATABASE_NAME = "myScore.db"; // public static final String TABLE_NAME = "HighScore"; // private static final int DATABASE_VERSION = 2; // // // Database creation sql statement // private static final String DATABASE_CREATE = // "CREATE TABLE " + TABLE_NAME + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + //this line is required for the cursorAdapter. // KEY_NAME + " TEXT, " + // KEY_SCORE + " INTEGER );"; // // //required constructor with the super. // public mySQLiteHelper() { // super(DATABASE_VERSION); // } // // @Override // public void onCreate(SupportSQLiteDatabase db) { // //NOTE only called when the database is initial created! // db.execSQL(DATABASE_CREATE); // } // // @Override // public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { // //Called when the database version changes, Remember the constant from above. // Log.w(TAG, "Upgrading database from version " + oldVersion // + " to " // + newVersion + ", which will destroy all old data"); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // onCreate(db); // } // // }
import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import edu.cs4730.sqlitedbdemo.db.mySQLiteHelper;
package edu.cs4730.sqlitedbdemo; /** * this adapter is very similar to the adapters used for listview, except a ViewHolder is required * see http://developer.android.com/training/improving-layouts/smooth-scrolling.html * except instead having to implement a ViewHolder, it is implemented within * the adapter. */ public class myAdapter extends RecyclerView.Adapter<myAdapter.ViewHolder> { private Cursor mCursor; private int rowLayout; private Context mContext; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder { public TextView myName, myScore; public ViewHolder(View itemView) { super(itemView); myName = itemView.findViewById(R.id.name); myScore = itemView.findViewById(R.id.score); } } //constructor public myAdapter(Cursor c, int rowLayout, Context context) { this.mCursor = c; this.rowLayout = rowLayout; this.mContext = context; } // Create new views (invoked by the layout manager) @NonNull @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false); return new ViewHolder(v); } // Replace the contents of a view (invoked by the layout manager) @SuppressLint("Range") @Override public void onBindViewHolder(ViewHolder viewHolder, int i) { //this assumes it's not called with a null mCursor, since i means there is a data. mCursor.moveToPosition(i); viewHolder.myName.setText(
// Path: sqliteDBDemo/app/src/main/java/edu/cs4730/sqlitedbdemo/db/mySQLiteHelper.java // public class mySQLiteHelper extends SupportSQLiteOpenHelper.Callback { // // private static final String TAG = "mySQLiteHelper"; // // //column names for the table. // public static final String KEY_NAME = "Name"; // public static final String KEY_SCORE = "Score"; // public static final String KEY_ROWID = "_id"; //required field for the cursorAdapter // // public static final String DATABASE_NAME = "myScore.db"; // public static final String TABLE_NAME = "HighScore"; // private static final int DATABASE_VERSION = 2; // // // Database creation sql statement // private static final String DATABASE_CREATE = // "CREATE TABLE " + TABLE_NAME + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + //this line is required for the cursorAdapter. // KEY_NAME + " TEXT, " + // KEY_SCORE + " INTEGER );"; // // //required constructor with the super. // public mySQLiteHelper() { // super(DATABASE_VERSION); // } // // @Override // public void onCreate(SupportSQLiteDatabase db) { // //NOTE only called when the database is initial created! // db.execSQL(DATABASE_CREATE); // } // // @Override // public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { // //Called when the database version changes, Remember the constant from above. // Log.w(TAG, "Upgrading database from version " + oldVersion // + " to " // + newVersion + ", which will destroy all old data"); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // onCreate(db); // } // // } // Path: sqliteDBDemo/app/src/main/java/edu/cs4730/sqlitedbdemo/myAdapter.java import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import edu.cs4730.sqlitedbdemo.db.mySQLiteHelper; package edu.cs4730.sqlitedbdemo; /** * this adapter is very similar to the adapters used for listview, except a ViewHolder is required * see http://developer.android.com/training/improving-layouts/smooth-scrolling.html * except instead having to implement a ViewHolder, it is implemented within * the adapter. */ public class myAdapter extends RecyclerView.Adapter<myAdapter.ViewHolder> { private Cursor mCursor; private int rowLayout; private Context mContext; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder { public TextView myName, myScore; public ViewHolder(View itemView) { super(itemView); myName = itemView.findViewById(R.id.name); myScore = itemView.findViewById(R.id.score); } } //constructor public myAdapter(Cursor c, int rowLayout, Context context) { this.mCursor = c; this.rowLayout = rowLayout; this.mContext = context; } // Create new views (invoked by the layout manager) @NonNull @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false); return new ViewHolder(v); } // Replace the contents of a view (invoked by the layout manager) @SuppressLint("Range") @Override public void onBindViewHolder(ViewHolder viewHolder, int i) { //this assumes it's not called with a null mCursor, since i means there is a data. mCursor.moveToPosition(i); viewHolder.myName.setText(
mCursor.getString(mCursor.getColumnIndex(mySQLiteHelper.KEY_NAME))
JimSeker/saveData
LvCursorDemo/app/src/main/java/edu/cs4730/lvcursordemo/custom_Fragment.java
// Path: LvCursorDemo/app/src/main/java/edu/cs4730/lvcursordemo/db/countryDatabase.java // public class countryDatabase { // private static final String TAG = "CountriesDbAdapter"; // private SupportSQLiteOpenHelper helper; // private SupportSQLiteDatabase db; // // //constructor // public countryDatabase(Context ctx) { // SupportSQLiteOpenHelper.Factory factory = new FrameworkSQLiteOpenHelperFactory(); // SupportSQLiteOpenHelper.Configuration configuration = SupportSQLiteOpenHelper.Configuration.builder(ctx) // .name(DatabaseHelper.DATABASE_NAME) // .callback(new DatabaseHelper()) // .build(); // helper = factory.create(configuration); // // } // // //---opens the database--- // public void open() throws SQLException { // db = helper.getWritableDatabase(); // } // // //returns true if db is open. Helper method. // public boolean isOpen() throws SQLException { // return db.isOpen(); // } // // //---closes the database--- // public void close() { // try { // db.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public long insertCountry(String code, String name, String continent, String region) { // ContentValues initialValues = new ContentValues(); // initialValues.put(DatabaseHelper.KEY_CODE, code); // initialValues.put(DatabaseHelper.KEY_NAME, name); // initialValues.put(DatabaseHelper.KEY_CONTINENT, continent); // initialValues.put(DatabaseHelper.KEY_REGION, region); // // return db.insert(DatabaseHelper.SQLITE_TABLE, CONFLICT_FAIL, initialValues); // } // // public boolean deleteAllCountries() { // // int doneDelete = 0; // doneDelete = db.delete(DatabaseHelper.SQLITE_TABLE, null , null); // Log.w(TAG, Integer.toString(doneDelete)); // return doneDelete > 0; // // } // // //this one uses the supportQueryBuilder that build a SupportSQLiteQuery for the query. // public Cursor qbQuery(String TableName, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // SupportSQLiteQueryBuilder qb = SupportSQLiteQueryBuilder.builder(TableName); // qb.columns(projection); // qb.selection(selection, selectionArgs); // qb.orderBy(sortOrder); // //using the query builder to manage the actual query at this point. // return db.query(qb.create()); // } // // // public Cursor fetchCountriesByName(String inputText) throws SQLException { // Log.w(TAG, inputText); // Cursor mCursor = null; // if (inputText == null || inputText.length () == 0) { // mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CODE, DatabaseHelper.KEY_NAME, DatabaseHelper.KEY_CONTINENT, DatabaseHelper.KEY_REGION}, // null, null, null); // // } // else { // mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CODE, DatabaseHelper.KEY_NAME, DatabaseHelper.KEY_CONTINENT, DatabaseHelper.KEY_REGION}, // DatabaseHelper.KEY_NAME + " like '%" + inputText + "%'", // null,null); // } // if (mCursor != null) { // mCursor.moveToFirst(); // } // return mCursor; // // } // // public Cursor fetchAllCountries() { // // Cursor mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CODE, DatabaseHelper.KEY_NAME, DatabaseHelper.KEY_CONTINENT, DatabaseHelper.KEY_REGION}, // null, null, null); // // if (mCursor != null) { // mCursor.moveToFirst(); // } // return mCursor; // } // // // public void insertSomeCountries() { // // insertCountry("AFG","Afghanistan","Asia","Southern and Central Asia"); // insertCountry("ALB","Albania","Europe","Southern Europe"); // insertCountry("DZA","Algeria","Africa","Northern Africa"); // insertCountry("ASM","American Samoa","Oceania","Polynesia"); // insertCountry("AND","Andorra","Europe","Southern Europe"); // insertCountry("AGO","Angola","Africa","Central Africa"); // insertCountry("AIA","Anguilla","North America","Caribbean"); // // } // // /* // * These two are for the Expandable List View demo piece. // */ // public Cursor fetchGroup() { // //Return ID and continent information, but all of it. // Cursor mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CONTINENT}, // null, null, null); // // if (mCursor != null) { // mCursor.moveToFirst(); // } // return mCursor; // } // // public Cursor fetchChild(String inputText) { // //fetching all the children for a group header, based on continent. // // Cursor mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CODE, DatabaseHelper.KEY_NAME, DatabaseHelper.KEY_REGION}, // DatabaseHelper.KEY_CONTINENT + " = '" + inputText + "'", // null,null); // // if (mCursor != null) { // mCursor.moveToFirst(); // } // return mCursor; // } // // // }
import android.content.Context; import android.database.Cursor; import android.os.Bundle; import androidx.fragment.app.Fragment; import edu.cs4730.lvcursordemo.db.countryDatabase; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.FilterQueryProvider; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener;
package edu.cs4730.lvcursordemo; public class custom_Fragment extends Fragment implements Button.OnClickListener { String TAG = "custom_frag"; Context myContext;
// Path: LvCursorDemo/app/src/main/java/edu/cs4730/lvcursordemo/db/countryDatabase.java // public class countryDatabase { // private static final String TAG = "CountriesDbAdapter"; // private SupportSQLiteOpenHelper helper; // private SupportSQLiteDatabase db; // // //constructor // public countryDatabase(Context ctx) { // SupportSQLiteOpenHelper.Factory factory = new FrameworkSQLiteOpenHelperFactory(); // SupportSQLiteOpenHelper.Configuration configuration = SupportSQLiteOpenHelper.Configuration.builder(ctx) // .name(DatabaseHelper.DATABASE_NAME) // .callback(new DatabaseHelper()) // .build(); // helper = factory.create(configuration); // // } // // //---opens the database--- // public void open() throws SQLException { // db = helper.getWritableDatabase(); // } // // //returns true if db is open. Helper method. // public boolean isOpen() throws SQLException { // return db.isOpen(); // } // // //---closes the database--- // public void close() { // try { // db.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public long insertCountry(String code, String name, String continent, String region) { // ContentValues initialValues = new ContentValues(); // initialValues.put(DatabaseHelper.KEY_CODE, code); // initialValues.put(DatabaseHelper.KEY_NAME, name); // initialValues.put(DatabaseHelper.KEY_CONTINENT, continent); // initialValues.put(DatabaseHelper.KEY_REGION, region); // // return db.insert(DatabaseHelper.SQLITE_TABLE, CONFLICT_FAIL, initialValues); // } // // public boolean deleteAllCountries() { // // int doneDelete = 0; // doneDelete = db.delete(DatabaseHelper.SQLITE_TABLE, null , null); // Log.w(TAG, Integer.toString(doneDelete)); // return doneDelete > 0; // // } // // //this one uses the supportQueryBuilder that build a SupportSQLiteQuery for the query. // public Cursor qbQuery(String TableName, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // SupportSQLiteQueryBuilder qb = SupportSQLiteQueryBuilder.builder(TableName); // qb.columns(projection); // qb.selection(selection, selectionArgs); // qb.orderBy(sortOrder); // //using the query builder to manage the actual query at this point. // return db.query(qb.create()); // } // // // public Cursor fetchCountriesByName(String inputText) throws SQLException { // Log.w(TAG, inputText); // Cursor mCursor = null; // if (inputText == null || inputText.length () == 0) { // mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CODE, DatabaseHelper.KEY_NAME, DatabaseHelper.KEY_CONTINENT, DatabaseHelper.KEY_REGION}, // null, null, null); // // } // else { // mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CODE, DatabaseHelper.KEY_NAME, DatabaseHelper.KEY_CONTINENT, DatabaseHelper.KEY_REGION}, // DatabaseHelper.KEY_NAME + " like '%" + inputText + "%'", // null,null); // } // if (mCursor != null) { // mCursor.moveToFirst(); // } // return mCursor; // // } // // public Cursor fetchAllCountries() { // // Cursor mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CODE, DatabaseHelper.KEY_NAME, DatabaseHelper.KEY_CONTINENT, DatabaseHelper.KEY_REGION}, // null, null, null); // // if (mCursor != null) { // mCursor.moveToFirst(); // } // return mCursor; // } // // // public void insertSomeCountries() { // // insertCountry("AFG","Afghanistan","Asia","Southern and Central Asia"); // insertCountry("ALB","Albania","Europe","Southern Europe"); // insertCountry("DZA","Algeria","Africa","Northern Africa"); // insertCountry("ASM","American Samoa","Oceania","Polynesia"); // insertCountry("AND","Andorra","Europe","Southern Europe"); // insertCountry("AGO","Angola","Africa","Central Africa"); // insertCountry("AIA","Anguilla","North America","Caribbean"); // // } // // /* // * These two are for the Expandable List View demo piece. // */ // public Cursor fetchGroup() { // //Return ID and continent information, but all of it. // Cursor mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CONTINENT}, // null, null, null); // // if (mCursor != null) { // mCursor.moveToFirst(); // } // return mCursor; // } // // public Cursor fetchChild(String inputText) { // //fetching all the children for a group header, based on continent. // // Cursor mCursor = qbQuery(DatabaseHelper.SQLITE_TABLE, // new String[] {DatabaseHelper.KEY_ROWID, DatabaseHelper.KEY_CODE, DatabaseHelper.KEY_NAME, DatabaseHelper.KEY_REGION}, // DatabaseHelper.KEY_CONTINENT + " = '" + inputText + "'", // null,null); // // if (mCursor != null) { // mCursor.moveToFirst(); // } // return mCursor; // } // // // } // Path: LvCursorDemo/app/src/main/java/edu/cs4730/lvcursordemo/custom_Fragment.java import android.content.Context; import android.database.Cursor; import android.os.Bundle; import androidx.fragment.app.Fragment; import edu.cs4730.lvcursordemo.db.countryDatabase; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.FilterQueryProvider; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; package edu.cs4730.lvcursordemo; public class custom_Fragment extends Fragment implements Button.OnClickListener { String TAG = "custom_frag"; Context myContext;
private countryDatabase countryDB;
JimSeker/saveData
sqliteDBViewModelDemo/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo/myAdapter.java
// Path: sqliteDBViewModelDemo/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo/db/mySQLiteHelper.java // public class mySQLiteHelper extends SupportSQLiteOpenHelper.Callback { // // private static final String TAG = "mySQLiteHelper"; // // //column names for the table. // public static final String KEY_NAME = "Name"; // public static final String KEY_SCORE = "Score"; // public static final String KEY_ROWID = "_id"; //required field for the cursorAdapter // // public static final String DATABASE_NAME = "myScore.db"; // public static final String TABLE_NAME = "HighScore"; // private static final int DATABASE_VERSION = 2; // // // Database creation sql statement // private static final String DATABASE_CREATE = // "CREATE TABLE " + TABLE_NAME + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + //this line is required for the cursorAdapter. // KEY_NAME + " TEXT, " + // KEY_SCORE + " INTEGER );"; // // //required constructor with the super. // public mySQLiteHelper() { // super(DATABASE_VERSION); // } // // @Override // public void onCreate(SupportSQLiteDatabase db) { // //NOTE only called when the database is initial created! // db.execSQL(DATABASE_CREATE); // } // // @Override // public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { // //Called when the database version changes, Remember the constant from above. // Log.w(TAG, "Upgrading database from version " + oldVersion // + " to " // + newVersion + ", which will destroy all old data"); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // onCreate(db); // } // // }
import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import edu.cs4730.sqlitedbviewmodeldemo.db.mySQLiteHelper;
package edu.cs4730.sqlitedbviewmodeldemo; /** * this adapter is very similar to the adapters used for listview, except a ViewHolder is required * see http://developer.android.com/training/improving-layouts/smooth-scrolling.html * except instead having to implement a ViewHolder, it is implemented within * the adapter. */ public class myAdapter extends RecyclerView.Adapter<myAdapter.ViewHolder> { private Cursor mCursor; private int rowLayout; private Context mContext; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder { public TextView myName, myScore; public ViewHolder(View itemView) { super(itemView); myName = itemView.findViewById(R.id.name); myScore = itemView.findViewById(R.id.score); } } //constructor public myAdapter(Cursor c, int rowLayout, Context context) { this.mCursor = c; this.rowLayout = rowLayout; this.mContext = context; } // Create new views (invoked by the layout manager) @NonNull @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false); return new ViewHolder(v); } // Replace the contents of a view (invoked by the layout manager) @SuppressLint("Range") @Override public void onBindViewHolder(ViewHolder viewHolder, int i) { //this assumes it's not called with a null mCursor, since i means there is a data. mCursor.moveToPosition(i); viewHolder.myName.setText(
// Path: sqliteDBViewModelDemo/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo/db/mySQLiteHelper.java // public class mySQLiteHelper extends SupportSQLiteOpenHelper.Callback { // // private static final String TAG = "mySQLiteHelper"; // // //column names for the table. // public static final String KEY_NAME = "Name"; // public static final String KEY_SCORE = "Score"; // public static final String KEY_ROWID = "_id"; //required field for the cursorAdapter // // public static final String DATABASE_NAME = "myScore.db"; // public static final String TABLE_NAME = "HighScore"; // private static final int DATABASE_VERSION = 2; // // // Database creation sql statement // private static final String DATABASE_CREATE = // "CREATE TABLE " + TABLE_NAME + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + //this line is required for the cursorAdapter. // KEY_NAME + " TEXT, " + // KEY_SCORE + " INTEGER );"; // // //required constructor with the super. // public mySQLiteHelper() { // super(DATABASE_VERSION); // } // // @Override // public void onCreate(SupportSQLiteDatabase db) { // //NOTE only called when the database is initial created! // db.execSQL(DATABASE_CREATE); // } // // @Override // public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { // //Called when the database version changes, Remember the constant from above. // Log.w(TAG, "Upgrading database from version " + oldVersion // + " to " // + newVersion + ", which will destroy all old data"); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // onCreate(db); // } // // } // Path: sqliteDBViewModelDemo/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo/myAdapter.java import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import edu.cs4730.sqlitedbviewmodeldemo.db.mySQLiteHelper; package edu.cs4730.sqlitedbviewmodeldemo; /** * this adapter is very similar to the adapters used for listview, except a ViewHolder is required * see http://developer.android.com/training/improving-layouts/smooth-scrolling.html * except instead having to implement a ViewHolder, it is implemented within * the adapter. */ public class myAdapter extends RecyclerView.Adapter<myAdapter.ViewHolder> { private Cursor mCursor; private int rowLayout; private Context mContext; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder { public TextView myName, myScore; public ViewHolder(View itemView) { super(itemView); myName = itemView.findViewById(R.id.name); myScore = itemView.findViewById(R.id.score); } } //constructor public myAdapter(Cursor c, int rowLayout, Context context) { this.mCursor = c; this.rowLayout = rowLayout; this.mContext = context; } // Create new views (invoked by the layout manager) @NonNull @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false); return new ViewHolder(v); } // Replace the contents of a view (invoked by the layout manager) @SuppressLint("Range") @Override public void onBindViewHolder(ViewHolder viewHolder, int i) { //this assumes it's not called with a null mCursor, since i means there is a data. mCursor.moveToPosition(i); viewHolder.myName.setText(
mCursor.getString(mCursor.getColumnIndex(mySQLiteHelper.KEY_NAME))
JimSeker/saveData
sqliteDBViewModelDemo/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo/MainActivity.java
// Path: sqliteDBViewModelDemo/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo/db/CursorViewModel.java // public class CursorViewModel extends AndroidViewModel { // ScoreDatabase db; // MutableLiveData<Cursor> myCursor = new MutableLiveData<Cursor>(); // // public CursorViewModel(@NonNull Application application) { // super(application); // db = new ScoreDatabase(application); // db.open(); // myCursor.setValue(db.getAllNames()); // db.close(); // } // // public MutableLiveData<Cursor> getData() { // return myCursor; // } // // // this uses the Convenience method to add something to the database and then update the cursor. // public void add(String name, int value) { // db.open(); // db.insertName(name, value); // myCursor.setValue(db.getAllNames()); // db.close(); // } // // // this uses the Convenience method to update something from the database and then update the cursor. // public int Update(String TableName, ContentValues values, String selection, String[] selectionArgs) { // db.open(); // int ret = db.Update(TableName, values, selection, selectionArgs); // myCursor.setValue(db.getAllNames()); // db.close(); // return ret; // } // // // this uses the Convenience method to delete something in the database and then update the cursor. // public int Delete(String TableName, String selection, String[] selectionArgs) { // db.open(); // int ret = db.Delete(TableName, selection, selectionArgs); // myCursor.setValue(db.getAllNames()); // db.close(); // return ret; // } // // }
import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import edu.cs4730.sqlitedbviewmodeldemo.db.CursorViewModel; import android.database.Cursor; import android.os.Bundle; import android.view.View; import com.google.android.material.floatingactionbutton.FloatingActionButton;
package edu.cs4730.sqlitedbviewmodeldemo; public class MainActivity extends AppCompatActivity { RecyclerView mRecyclerView; FloatingActionButton fab; myAdapter mAdapter;
// Path: sqliteDBViewModelDemo/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo/db/CursorViewModel.java // public class CursorViewModel extends AndroidViewModel { // ScoreDatabase db; // MutableLiveData<Cursor> myCursor = new MutableLiveData<Cursor>(); // // public CursorViewModel(@NonNull Application application) { // super(application); // db = new ScoreDatabase(application); // db.open(); // myCursor.setValue(db.getAllNames()); // db.close(); // } // // public MutableLiveData<Cursor> getData() { // return myCursor; // } // // // this uses the Convenience method to add something to the database and then update the cursor. // public void add(String name, int value) { // db.open(); // db.insertName(name, value); // myCursor.setValue(db.getAllNames()); // db.close(); // } // // // this uses the Convenience method to update something from the database and then update the cursor. // public int Update(String TableName, ContentValues values, String selection, String[] selectionArgs) { // db.open(); // int ret = db.Update(TableName, values, selection, selectionArgs); // myCursor.setValue(db.getAllNames()); // db.close(); // return ret; // } // // // this uses the Convenience method to delete something in the database and then update the cursor. // public int Delete(String TableName, String selection, String[] selectionArgs) { // db.open(); // int ret = db.Delete(TableName, selection, selectionArgs); // myCursor.setValue(db.getAllNames()); // db.close(); // return ret; // } // // } // Path: sqliteDBViewModelDemo/app/src/main/java/edu/cs4730/sqlitedbviewmodeldemo/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import edu.cs4730.sqlitedbviewmodeldemo.db.CursorViewModel; import android.database.Cursor; import android.os.Bundle; import android.view.View; import com.google.android.material.floatingactionbutton.FloatingActionButton; package edu.cs4730.sqlitedbviewmodeldemo; public class MainActivity extends AppCompatActivity { RecyclerView mRecyclerView; FloatingActionButton fab; myAdapter mAdapter;
CursorViewModel mViewModel;
JimSeker/saveData
ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/dummyCP.java
// Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/data/Cube.java // public class Cube { // String[] Column; // // public Cube() { // Column = new String[] { "number", "cube"}; // } // // //getone returns the val and the square of the val in cursor. // public Cursor getone(int val) { // //must return a Cursor, MatrixCursor is an editable cursor. // MatrixCursor myCursor = new MatrixCursor(Column); // myCursor.addRow(new Object[] { val, val*val*val }); // return myCursor; // } // // //returns the number and number of the number from 1 to 10. // public Cursor getall() { // MatrixCursor myCursor = new MatrixCursor(Column); // for (int i=1; i<11; i++) { // myCursor.addRow(new Object[] { i, i*i*i}); // } // return myCursor; // } // } // // Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/data/Square.java // public class Square { // // String[] Column; // // public Square() { // Column = new String[] { "number", "square"}; // } // // //getone returns the val and the square of the val in cursor. // public Cursor getone(int val) { // //must return a Cursor, MatrixCursor is an editable cursor. // MatrixCursor myCursor = new MatrixCursor(Column); // myCursor.addRow(new Object[] { val, val*val}); // return myCursor; // } // // //returns the number and number of the number from 1 to 10. // public Cursor getall() { // MatrixCursor myCursor = new MatrixCursor(Column); // for (int i=1; i<11; i++) { // myCursor.addRow(new Object[] { i, i*i}); // } // return myCursor; // } // }
import androidx.annotation.NonNull; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.util.Log; import edu.cs4730.contentprodemo.data.Cube; import edu.cs4730.contentprodemo.data.Square;
package edu.cs4730.contentprodemo; /** * This example is to provide the very basics of a content provider. It only returns * information, and ignores any attempts to updates/insert/delete. The basic structure is here and * is intended for demonstration purposes. * < * This has two "tables". it can provide squares or cubes * <p> * For a more complete and generic content provider connected to a database, please the sqlite repo, * myDBcontentProvider for more information. * <p> * Note if calling from another applications, it will need to have * <queries> <package android:name="edu.cs4730.contentprodemo" /> </queries> in the manifest file * starting in API 30 for package visibility additions. */ public class dummyCP extends ContentProvider { public static final String PROVIDER_NAME = "edu.cs4730.provider"; //these two are not used, but normally handly to have avialabe in a normal provider. public static final Uri CONTENT_URI1 = Uri.parse("content://" + PROVIDER_NAME + "/square"); public static final Uri CONTENT_URI2 = Uri.parse("content://" + PROVIDER_NAME + "/cube"); private static final int SQUARE = 1; private static final int SQUARE_ID = 2; private static final int CUBE = 3; private static final int CUBE_ID = 4; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "square", SQUARE); uriMatcher.addURI(PROVIDER_NAME, "square/#", SQUARE_ID); uriMatcher.addURI(PROVIDER_NAME, "cube", CUBE); uriMatcher.addURI(PROVIDER_NAME, "cube/#", CUBE_ID); } static final String TAG = "dummyCP";
// Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/data/Cube.java // public class Cube { // String[] Column; // // public Cube() { // Column = new String[] { "number", "cube"}; // } // // //getone returns the val and the square of the val in cursor. // public Cursor getone(int val) { // //must return a Cursor, MatrixCursor is an editable cursor. // MatrixCursor myCursor = new MatrixCursor(Column); // myCursor.addRow(new Object[] { val, val*val*val }); // return myCursor; // } // // //returns the number and number of the number from 1 to 10. // public Cursor getall() { // MatrixCursor myCursor = new MatrixCursor(Column); // for (int i=1; i<11; i++) { // myCursor.addRow(new Object[] { i, i*i*i}); // } // return myCursor; // } // } // // Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/data/Square.java // public class Square { // // String[] Column; // // public Square() { // Column = new String[] { "number", "square"}; // } // // //getone returns the val and the square of the val in cursor. // public Cursor getone(int val) { // //must return a Cursor, MatrixCursor is an editable cursor. // MatrixCursor myCursor = new MatrixCursor(Column); // myCursor.addRow(new Object[] { val, val*val}); // return myCursor; // } // // //returns the number and number of the number from 1 to 10. // public Cursor getall() { // MatrixCursor myCursor = new MatrixCursor(Column); // for (int i=1; i<11; i++) { // myCursor.addRow(new Object[] { i, i*i}); // } // return myCursor; // } // } // Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/dummyCP.java import androidx.annotation.NonNull; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.util.Log; import edu.cs4730.contentprodemo.data.Cube; import edu.cs4730.contentprodemo.data.Square; package edu.cs4730.contentprodemo; /** * This example is to provide the very basics of a content provider. It only returns * information, and ignores any attempts to updates/insert/delete. The basic structure is here and * is intended for demonstration purposes. * < * This has two "tables". it can provide squares or cubes * <p> * For a more complete and generic content provider connected to a database, please the sqlite repo, * myDBcontentProvider for more information. * <p> * Note if calling from another applications, it will need to have * <queries> <package android:name="edu.cs4730.contentprodemo" /> </queries> in the manifest file * starting in API 30 for package visibility additions. */ public class dummyCP extends ContentProvider { public static final String PROVIDER_NAME = "edu.cs4730.provider"; //these two are not used, but normally handly to have avialabe in a normal provider. public static final Uri CONTENT_URI1 = Uri.parse("content://" + PROVIDER_NAME + "/square"); public static final Uri CONTENT_URI2 = Uri.parse("content://" + PROVIDER_NAME + "/cube"); private static final int SQUARE = 1; private static final int SQUARE_ID = 2; private static final int CUBE = 3; private static final int CUBE_ID = 4; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "square", SQUARE); uriMatcher.addURI(PROVIDER_NAME, "square/#", SQUARE_ID); uriMatcher.addURI(PROVIDER_NAME, "cube", CUBE); uriMatcher.addURI(PROVIDER_NAME, "cube/#", CUBE_ID); } static final String TAG = "dummyCP";
Cube myCube;
JimSeker/saveData
ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/dummyCP.java
// Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/data/Cube.java // public class Cube { // String[] Column; // // public Cube() { // Column = new String[] { "number", "cube"}; // } // // //getone returns the val and the square of the val in cursor. // public Cursor getone(int val) { // //must return a Cursor, MatrixCursor is an editable cursor. // MatrixCursor myCursor = new MatrixCursor(Column); // myCursor.addRow(new Object[] { val, val*val*val }); // return myCursor; // } // // //returns the number and number of the number from 1 to 10. // public Cursor getall() { // MatrixCursor myCursor = new MatrixCursor(Column); // for (int i=1; i<11; i++) { // myCursor.addRow(new Object[] { i, i*i*i}); // } // return myCursor; // } // } // // Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/data/Square.java // public class Square { // // String[] Column; // // public Square() { // Column = new String[] { "number", "square"}; // } // // //getone returns the val and the square of the val in cursor. // public Cursor getone(int val) { // //must return a Cursor, MatrixCursor is an editable cursor. // MatrixCursor myCursor = new MatrixCursor(Column); // myCursor.addRow(new Object[] { val, val*val}); // return myCursor; // } // // //returns the number and number of the number from 1 to 10. // public Cursor getall() { // MatrixCursor myCursor = new MatrixCursor(Column); // for (int i=1; i<11; i++) { // myCursor.addRow(new Object[] { i, i*i}); // } // return myCursor; // } // }
import androidx.annotation.NonNull; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.util.Log; import edu.cs4730.contentprodemo.data.Cube; import edu.cs4730.contentprodemo.data.Square;
package edu.cs4730.contentprodemo; /** * This example is to provide the very basics of a content provider. It only returns * information, and ignores any attempts to updates/insert/delete. The basic structure is here and * is intended for demonstration purposes. * < * This has two "tables". it can provide squares or cubes * <p> * For a more complete and generic content provider connected to a database, please the sqlite repo, * myDBcontentProvider for more information. * <p> * Note if calling from another applications, it will need to have * <queries> <package android:name="edu.cs4730.contentprodemo" /> </queries> in the manifest file * starting in API 30 for package visibility additions. */ public class dummyCP extends ContentProvider { public static final String PROVIDER_NAME = "edu.cs4730.provider"; //these two are not used, but normally handly to have avialabe in a normal provider. public static final Uri CONTENT_URI1 = Uri.parse("content://" + PROVIDER_NAME + "/square"); public static final Uri CONTENT_URI2 = Uri.parse("content://" + PROVIDER_NAME + "/cube"); private static final int SQUARE = 1; private static final int SQUARE_ID = 2; private static final int CUBE = 3; private static final int CUBE_ID = 4; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "square", SQUARE); uriMatcher.addURI(PROVIDER_NAME, "square/#", SQUARE_ID); uriMatcher.addURI(PROVIDER_NAME, "cube", CUBE); uriMatcher.addURI(PROVIDER_NAME, "cube/#", CUBE_ID); } static final String TAG = "dummyCP"; Cube myCube;
// Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/data/Cube.java // public class Cube { // String[] Column; // // public Cube() { // Column = new String[] { "number", "cube"}; // } // // //getone returns the val and the square of the val in cursor. // public Cursor getone(int val) { // //must return a Cursor, MatrixCursor is an editable cursor. // MatrixCursor myCursor = new MatrixCursor(Column); // myCursor.addRow(new Object[] { val, val*val*val }); // return myCursor; // } // // //returns the number and number of the number from 1 to 10. // public Cursor getall() { // MatrixCursor myCursor = new MatrixCursor(Column); // for (int i=1; i<11; i++) { // myCursor.addRow(new Object[] { i, i*i*i}); // } // return myCursor; // } // } // // Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/data/Square.java // public class Square { // // String[] Column; // // public Square() { // Column = new String[] { "number", "square"}; // } // // //getone returns the val and the square of the val in cursor. // public Cursor getone(int val) { // //must return a Cursor, MatrixCursor is an editable cursor. // MatrixCursor myCursor = new MatrixCursor(Column); // myCursor.addRow(new Object[] { val, val*val}); // return myCursor; // } // // //returns the number and number of the number from 1 to 10. // public Cursor getall() { // MatrixCursor myCursor = new MatrixCursor(Column); // for (int i=1; i<11; i++) { // myCursor.addRow(new Object[] { i, i*i}); // } // return myCursor; // } // } // Path: ContentProDemo/app/src/main/java/edu/cs4730/contentprodemo/dummyCP.java import androidx.annotation.NonNull; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.util.Log; import edu.cs4730.contentprodemo.data.Cube; import edu.cs4730.contentprodemo.data.Square; package edu.cs4730.contentprodemo; /** * This example is to provide the very basics of a content provider. It only returns * information, and ignores any attempts to updates/insert/delete. The basic structure is here and * is intended for demonstration purposes. * < * This has two "tables". it can provide squares or cubes * <p> * For a more complete and generic content provider connected to a database, please the sqlite repo, * myDBcontentProvider for more information. * <p> * Note if calling from another applications, it will need to have * <queries> <package android:name="edu.cs4730.contentprodemo" /> </queries> in the manifest file * starting in API 30 for package visibility additions. */ public class dummyCP extends ContentProvider { public static final String PROVIDER_NAME = "edu.cs4730.provider"; //these two are not used, but normally handly to have avialabe in a normal provider. public static final Uri CONTENT_URI1 = Uri.parse("content://" + PROVIDER_NAME + "/square"); public static final Uri CONTENT_URI2 = Uri.parse("content://" + PROVIDER_NAME + "/cube"); private static final int SQUARE = 1; private static final int SQUARE_ID = 2; private static final int CUBE = 3; private static final int CUBE_ID = 4; private static final UriMatcher uriMatcher; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(PROVIDER_NAME, "square", SQUARE); uriMatcher.addURI(PROVIDER_NAME, "square/#", SQUARE_ID); uriMatcher.addURI(PROVIDER_NAME, "cube", CUBE); uriMatcher.addURI(PROVIDER_NAME, "cube/#", CUBE_ID); } static final String TAG = "dummyCP"; Cube myCube;
Square mySquare;
JimSeker/saveData
sqliteDemo/app/src/main/java/edu/cs4730/sqlitedemo/ContentProvider_Fragment.java
// Path: sqliteDemo/app/src/main/java/edu/cs4730/sqlitedemo/db/mySQLiteHelper.java // public class mySQLiteHelper extends SupportSQLiteOpenHelper.Callback { // // private static final String TAG = "mySQLiteHelper"; // // //column names for the table. // public static final String KEY_NAME = "Name"; // public static final String KEY_SCORE = "Score"; // public static final String KEY_ROWID = "_id"; //required field for the cursorAdapter // // public static final String DATABASE_NAME = "myScore.db"; // public static final String TABLE_NAME = "HighScore"; // private static final int DATABASE_VERSION = 2; // // // Database creation sql statement // private static final String DATABASE_CREATE = // "CREATE TABLE " + TABLE_NAME + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + //this line is required for the cursorAdapter. // KEY_NAME + " TEXT, " + // KEY_SCORE + " INTEGER );"; // // //required constructor with the super. // public mySQLiteHelper() { // super(DATABASE_VERSION); // } // // @Override // public void onCreate(SupportSQLiteDatabase db) { // //NOTE only called when the database is initial created! // db.execSQL(DATABASE_CREATE); // } // // @Override // public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { // //Called when the database version changes, Remember the constant from above. // Log.w(TAG, "Upgrading database from version " + oldVersion // + " to " // + newVersion + ", which will destroy all old data"); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // onCreate(db); // } // // }
import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.cursoradapter.widget.SimpleCursorAdapter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import edu.cs4730.sqlitedemo.db.mySQLiteHelper;
package edu.cs4730.sqlitedemo; /** * This is a demo of how to use a content provider (which is in this code, myDBContenProvider is the provider) * with a listview. This is very similar to CursorAdapter_fragment, * * See sqliteDemo3 for a recyclerview using a content provider. */ public class ContentProvider_Fragment extends Fragment { String TAG = "ContentProvider_frag"; Cursor cursor; private SimpleCursorAdapter dataAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View myView = inflater.inflate(R.layout.contentprovider_fragment, container, false); //get the people URI Uri CONTENT_URI = Uri.parse("content://edu.cs4730.scoreprovider/score"); //setup the information we want for the contentprovider.
// Path: sqliteDemo/app/src/main/java/edu/cs4730/sqlitedemo/db/mySQLiteHelper.java // public class mySQLiteHelper extends SupportSQLiteOpenHelper.Callback { // // private static final String TAG = "mySQLiteHelper"; // // //column names for the table. // public static final String KEY_NAME = "Name"; // public static final String KEY_SCORE = "Score"; // public static final String KEY_ROWID = "_id"; //required field for the cursorAdapter // // public static final String DATABASE_NAME = "myScore.db"; // public static final String TABLE_NAME = "HighScore"; // private static final int DATABASE_VERSION = 2; // // // Database creation sql statement // private static final String DATABASE_CREATE = // "CREATE TABLE " + TABLE_NAME + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + //this line is required for the cursorAdapter. // KEY_NAME + " TEXT, " + // KEY_SCORE + " INTEGER );"; // // //required constructor with the super. // public mySQLiteHelper() { // super(DATABASE_VERSION); // } // // @Override // public void onCreate(SupportSQLiteDatabase db) { // //NOTE only called when the database is initial created! // db.execSQL(DATABASE_CREATE); // } // // @Override // public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { // //Called when the database version changes, Remember the constant from above. // Log.w(TAG, "Upgrading database from version " + oldVersion // + " to " // + newVersion + ", which will destroy all old data"); // db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // onCreate(db); // } // // } // Path: sqliteDemo/app/src/main/java/edu/cs4730/sqlitedemo/ContentProvider_Fragment.java import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.cursoradapter.widget.SimpleCursorAdapter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import edu.cs4730.sqlitedemo.db.mySQLiteHelper; package edu.cs4730.sqlitedemo; /** * This is a demo of how to use a content provider (which is in this code, myDBContenProvider is the provider) * with a listview. This is very similar to CursorAdapter_fragment, * * See sqliteDemo3 for a recyclerview using a content provider. */ public class ContentProvider_Fragment extends Fragment { String TAG = "ContentProvider_frag"; Cursor cursor; private SimpleCursorAdapter dataAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View myView = inflater.inflate(R.layout.contentprovider_fragment, container, false); //get the people URI Uri CONTENT_URI = Uri.parse("content://edu.cs4730.scoreprovider/score"); //setup the information we want for the contentprovider.
String[] projection = new String[]{mySQLiteHelper.KEY_ROWID, mySQLiteHelper.KEY_NAME, mySQLiteHelper.KEY_SCORE};
MyGrades/mygrades-app
app/src/main/java/de/mygrades/main/events/StatisticsEvent.java
// Path: app/src/main/java/de/mygrades/view/adapter/model/SemesterItem.java // public class SemesterItem implements GradesAdapterItem { // private String semester; // private float average; // private float creditPoints; // private List<GradeItem> grades; // private boolean simpleWeighting; // // public SemesterItem(boolean simpleWeighting) { // grades = new ArrayList<>(); // this.simpleWeighting = simpleWeighting; // } // // public void addGrade(GradeItem gradeItem, boolean updateImmediately) { // grades.add(gradeItem); // // if (updateImmediately) { // update(); // } // } // // /** // * Updates the average grade and the sum of credit points. // */ // public void update() { // AverageCalculator calculator = new AverageCalculator(simpleWeighting); // calculator.calculate(grades); // // this.average = calculator.getAverage(); // this.creditPoints = calculator.getCreditPointsSum(); // } // // public String getSemester() { // return semester; // } // // public void setSemester(String semester) { // this.semester = semester; // } // // public float getAverage() { // return average; // } // // public void setAverage(float average) { // this.average = average; // } // // public float getCreditPoints() { // return creditPoints; // } // // public void setCreditPoints(float creditPoints) { // this.creditPoints = creditPoints; // } // // public List<GradeItem> getGrades() { // return grades; // } // // public int getVisibleGradesCount() { // int count = 0; // for (GradeItem gradeItem : grades) { // count += gradeItem.isHidden() ? 0 : 1; // } // return count; // } // // public void setSimpleWeighting(boolean simpleWeighting) { // this.simpleWeighting = simpleWeighting; // update(); // } // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import de.mygrades.view.adapter.model.SemesterItem;
package de.mygrades.main.events; /** * Event to post statistics to subscribers. */ public class StatisticsEvent { private float average; private float creditPoints; private float creditPointsPerSemester; private float studyProgress; private int gradeCount;
// Path: app/src/main/java/de/mygrades/view/adapter/model/SemesterItem.java // public class SemesterItem implements GradesAdapterItem { // private String semester; // private float average; // private float creditPoints; // private List<GradeItem> grades; // private boolean simpleWeighting; // // public SemesterItem(boolean simpleWeighting) { // grades = new ArrayList<>(); // this.simpleWeighting = simpleWeighting; // } // // public void addGrade(GradeItem gradeItem, boolean updateImmediately) { // grades.add(gradeItem); // // if (updateImmediately) { // update(); // } // } // // /** // * Updates the average grade and the sum of credit points. // */ // public void update() { // AverageCalculator calculator = new AverageCalculator(simpleWeighting); // calculator.calculate(grades); // // this.average = calculator.getAverage(); // this.creditPoints = calculator.getCreditPointsSum(); // } // // public String getSemester() { // return semester; // } // // public void setSemester(String semester) { // this.semester = semester; // } // // public float getAverage() { // return average; // } // // public void setAverage(float average) { // this.average = average; // } // // public float getCreditPoints() { // return creditPoints; // } // // public void setCreditPoints(float creditPoints) { // this.creditPoints = creditPoints; // } // // public List<GradeItem> getGrades() { // return grades; // } // // public int getVisibleGradesCount() { // int count = 0; // for (GradeItem gradeItem : grades) { // count += gradeItem.isHidden() ? 0 : 1; // } // return count; // } // // public void setSimpleWeighting(boolean simpleWeighting) { // this.simpleWeighting = simpleWeighting; // update(); // } // } // Path: app/src/main/java/de/mygrades/main/events/StatisticsEvent.java import java.util.ArrayList; import java.util.List; import java.util.Map; import de.mygrades.view.adapter.model.SemesterItem; package de.mygrades.main.events; /** * Event to post statistics to subscribers. */ public class StatisticsEvent { private float average; private float creditPoints; private float creditPointsPerSemester; private float studyProgress; private int gradeCount;
private List<SemesterItem> semesterItems;
MyGrades/mygrades-app
app/src/main/java/de/mygrades/main/core/Parser.java
// Path: app/src/main/java/de/mygrades/util/exceptions/ParseException.java // @SuppressWarnings("unused") // public class ParseException extends Exception { // // public ParseException(){ // // } // // public ParseException(String detailMessage) { // super(detailMessage); // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public ParseException(Throwable throwable) { // super(throwable); // } // }
import android.content.Context; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.tidy.Tidy; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import de.mygrades.util.exceptions.ParseException;
package de.mygrades.main.core; /** * Parses String to Documents and evaluates xPath expressions on them. */ public class Parser { private Context context; /** * Tidy builder is needed for creating documents out of strings. */ private Tidy tidyBuilder; /** * XPath evaluates xPath expressions on documents. */ private XPath xPath; /** * Transformer is needed for converting a node to string. */ private Transformer transformer;
// Path: app/src/main/java/de/mygrades/util/exceptions/ParseException.java // @SuppressWarnings("unused") // public class ParseException extends Exception { // // public ParseException(){ // // } // // public ParseException(String detailMessage) { // super(detailMessage); // } // // public ParseException(String detailMessage, Throwable throwable) { // super(detailMessage, throwable); // } // // public ParseException(Throwable throwable) { // super(throwable); // } // } // Path: app/src/main/java/de/mygrades/main/core/Parser.java import android.content.Context; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.tidy.Tidy; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import de.mygrades.util.exceptions.ParseException; package de.mygrades.main.core; /** * Parses String to Documents and evaluates xPath expressions on them. */ public class Parser { private Context context; /** * Tidy builder is needed for creating documents out of strings. */ private Tidy tidyBuilder; /** * XPath evaluates xPath expressions on documents. */ private XPath xPath; /** * Transformer is needed for converting a node to string. */ private Transformer transformer;
public Parser(Context context) throws ParseException {
MyGrades/mygrades-app
app/src/main/java/de/mygrades/database/dao/Action.java
// Path: app/src/main/java/de/mygrades/database/dao/DaoSession.java // public class DaoSession extends AbstractDaoSession { // // private final DaoConfig universityDaoConfig; // private final DaoConfig ruleDaoConfig; // private final DaoConfig actionDaoConfig; // private final DaoConfig actionParamDaoConfig; // private final DaoConfig transformerMappingDaoConfig; // private final DaoConfig gradeEntryDaoConfig; // private final DaoConfig overviewDaoConfig; // // private final UniversityDao universityDao; // private final RuleDao ruleDao; // private final ActionDao actionDao; // private final ActionParamDao actionParamDao; // private final TransformerMappingDao transformerMappingDao; // private final GradeEntryDao gradeEntryDao; // private final OverviewDao overviewDao; // // public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> // daoConfigMap) { // super(db); // // universityDaoConfig = daoConfigMap.get(UniversityDao.class).clone(); // universityDaoConfig.initIdentityScope(type); // // ruleDaoConfig = daoConfigMap.get(RuleDao.class).clone(); // ruleDaoConfig.initIdentityScope(type); // // actionDaoConfig = daoConfigMap.get(ActionDao.class).clone(); // actionDaoConfig.initIdentityScope(type); // // actionParamDaoConfig = daoConfigMap.get(ActionParamDao.class).clone(); // actionParamDaoConfig.initIdentityScope(type); // // transformerMappingDaoConfig = daoConfigMap.get(TransformerMappingDao.class).clone(); // transformerMappingDaoConfig.initIdentityScope(type); // // gradeEntryDaoConfig = daoConfigMap.get(GradeEntryDao.class).clone(); // gradeEntryDaoConfig.initIdentityScope(type); // // overviewDaoConfig = daoConfigMap.get(OverviewDao.class).clone(); // overviewDaoConfig.initIdentityScope(type); // // universityDao = new UniversityDao(universityDaoConfig, this); // ruleDao = new RuleDao(ruleDaoConfig, this); // actionDao = new ActionDao(actionDaoConfig, this); // actionParamDao = new ActionParamDao(actionParamDaoConfig, this); // transformerMappingDao = new TransformerMappingDao(transformerMappingDaoConfig, this); // gradeEntryDao = new GradeEntryDao(gradeEntryDaoConfig, this); // overviewDao = new OverviewDao(overviewDaoConfig, this); // // registerDao(University.class, universityDao); // registerDao(Rule.class, ruleDao); // registerDao(Action.class, actionDao); // registerDao(ActionParam.class, actionParamDao); // registerDao(TransformerMapping.class, transformerMappingDao); // registerDao(GradeEntry.class, gradeEntryDao); // registerDao(Overview.class, overviewDao); // } // // public void clear() { // universityDaoConfig.getIdentityScope().clear(); // ruleDaoConfig.getIdentityScope().clear(); // actionDaoConfig.getIdentityScope().clear(); // actionParamDaoConfig.getIdentityScope().clear(); // transformerMappingDaoConfig.getIdentityScope().clear(); // gradeEntryDaoConfig.getIdentityScope().clear(); // overviewDaoConfig.getIdentityScope().clear(); // } // // public UniversityDao getUniversityDao() { // return universityDao; // } // // public RuleDao getRuleDao() { // return ruleDao; // } // // public ActionDao getActionDao() { // return actionDao; // } // // public ActionParamDao getActionParamDao() { // return actionParamDao; // } // // public TransformerMappingDao getTransformerMappingDao() { // return transformerMappingDao; // } // // public GradeEntryDao getGradeEntryDao() { // return gradeEntryDao; // } // // public OverviewDao getOverviewDao() { // return overviewDao; // } // // }
import java.util.List; import de.mygrades.database.dao.DaoSession; import de.greenrobot.dao.DaoException;
package de.mygrades.database.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here // KEEP INCLUDES END /** * Entity mapped to table "ACTION". */ public class Action { private Long actionId; private int position; private String type; /** Not-null value. */ private String method; private String url; private String parseExpression; private long ruleId; /** Used to resolve relations */
// Path: app/src/main/java/de/mygrades/database/dao/DaoSession.java // public class DaoSession extends AbstractDaoSession { // // private final DaoConfig universityDaoConfig; // private final DaoConfig ruleDaoConfig; // private final DaoConfig actionDaoConfig; // private final DaoConfig actionParamDaoConfig; // private final DaoConfig transformerMappingDaoConfig; // private final DaoConfig gradeEntryDaoConfig; // private final DaoConfig overviewDaoConfig; // // private final UniversityDao universityDao; // private final RuleDao ruleDao; // private final ActionDao actionDao; // private final ActionParamDao actionParamDao; // private final TransformerMappingDao transformerMappingDao; // private final GradeEntryDao gradeEntryDao; // private final OverviewDao overviewDao; // // public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> // daoConfigMap) { // super(db); // // universityDaoConfig = daoConfigMap.get(UniversityDao.class).clone(); // universityDaoConfig.initIdentityScope(type); // // ruleDaoConfig = daoConfigMap.get(RuleDao.class).clone(); // ruleDaoConfig.initIdentityScope(type); // // actionDaoConfig = daoConfigMap.get(ActionDao.class).clone(); // actionDaoConfig.initIdentityScope(type); // // actionParamDaoConfig = daoConfigMap.get(ActionParamDao.class).clone(); // actionParamDaoConfig.initIdentityScope(type); // // transformerMappingDaoConfig = daoConfigMap.get(TransformerMappingDao.class).clone(); // transformerMappingDaoConfig.initIdentityScope(type); // // gradeEntryDaoConfig = daoConfigMap.get(GradeEntryDao.class).clone(); // gradeEntryDaoConfig.initIdentityScope(type); // // overviewDaoConfig = daoConfigMap.get(OverviewDao.class).clone(); // overviewDaoConfig.initIdentityScope(type); // // universityDao = new UniversityDao(universityDaoConfig, this); // ruleDao = new RuleDao(ruleDaoConfig, this); // actionDao = new ActionDao(actionDaoConfig, this); // actionParamDao = new ActionParamDao(actionParamDaoConfig, this); // transformerMappingDao = new TransformerMappingDao(transformerMappingDaoConfig, this); // gradeEntryDao = new GradeEntryDao(gradeEntryDaoConfig, this); // overviewDao = new OverviewDao(overviewDaoConfig, this); // // registerDao(University.class, universityDao); // registerDao(Rule.class, ruleDao); // registerDao(Action.class, actionDao); // registerDao(ActionParam.class, actionParamDao); // registerDao(TransformerMapping.class, transformerMappingDao); // registerDao(GradeEntry.class, gradeEntryDao); // registerDao(Overview.class, overviewDao); // } // // public void clear() { // universityDaoConfig.getIdentityScope().clear(); // ruleDaoConfig.getIdentityScope().clear(); // actionDaoConfig.getIdentityScope().clear(); // actionParamDaoConfig.getIdentityScope().clear(); // transformerMappingDaoConfig.getIdentityScope().clear(); // gradeEntryDaoConfig.getIdentityScope().clear(); // overviewDaoConfig.getIdentityScope().clear(); // } // // public UniversityDao getUniversityDao() { // return universityDao; // } // // public RuleDao getRuleDao() { // return ruleDao; // } // // public ActionDao getActionDao() { // return actionDao; // } // // public ActionParamDao getActionParamDao() { // return actionParamDao; // } // // public TransformerMappingDao getTransformerMappingDao() { // return transformerMappingDao; // } // // public GradeEntryDao getGradeEntryDao() { // return gradeEntryDao; // } // // public OverviewDao getOverviewDao() { // return overviewDao; // } // // } // Path: app/src/main/java/de/mygrades/database/dao/Action.java import java.util.List; import de.mygrades.database.dao.DaoSession; import de.greenrobot.dao.DaoException; package de.mygrades.database.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here // KEEP INCLUDES END /** * Entity mapped to table "ACTION". */ public class Action { private Long actionId; private int position; private String type; /** Not-null value. */ private String method; private String url; private String parseExpression; private long ruleId; /** Used to resolve relations */
private transient DaoSession daoSession;
MyGrades/mygrades-app
app/src/main/java/de/mygrades/database/dao/University.java
// Path: app/src/main/java/de/mygrades/database/dao/DaoSession.java // public class DaoSession extends AbstractDaoSession { // // private final DaoConfig universityDaoConfig; // private final DaoConfig ruleDaoConfig; // private final DaoConfig actionDaoConfig; // private final DaoConfig actionParamDaoConfig; // private final DaoConfig transformerMappingDaoConfig; // private final DaoConfig gradeEntryDaoConfig; // private final DaoConfig overviewDaoConfig; // // private final UniversityDao universityDao; // private final RuleDao ruleDao; // private final ActionDao actionDao; // private final ActionParamDao actionParamDao; // private final TransformerMappingDao transformerMappingDao; // private final GradeEntryDao gradeEntryDao; // private final OverviewDao overviewDao; // // public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> // daoConfigMap) { // super(db); // // universityDaoConfig = daoConfigMap.get(UniversityDao.class).clone(); // universityDaoConfig.initIdentityScope(type); // // ruleDaoConfig = daoConfigMap.get(RuleDao.class).clone(); // ruleDaoConfig.initIdentityScope(type); // // actionDaoConfig = daoConfigMap.get(ActionDao.class).clone(); // actionDaoConfig.initIdentityScope(type); // // actionParamDaoConfig = daoConfigMap.get(ActionParamDao.class).clone(); // actionParamDaoConfig.initIdentityScope(type); // // transformerMappingDaoConfig = daoConfigMap.get(TransformerMappingDao.class).clone(); // transformerMappingDaoConfig.initIdentityScope(type); // // gradeEntryDaoConfig = daoConfigMap.get(GradeEntryDao.class).clone(); // gradeEntryDaoConfig.initIdentityScope(type); // // overviewDaoConfig = daoConfigMap.get(OverviewDao.class).clone(); // overviewDaoConfig.initIdentityScope(type); // // universityDao = new UniversityDao(universityDaoConfig, this); // ruleDao = new RuleDao(ruleDaoConfig, this); // actionDao = new ActionDao(actionDaoConfig, this); // actionParamDao = new ActionParamDao(actionParamDaoConfig, this); // transformerMappingDao = new TransformerMappingDao(transformerMappingDaoConfig, this); // gradeEntryDao = new GradeEntryDao(gradeEntryDaoConfig, this); // overviewDao = new OverviewDao(overviewDaoConfig, this); // // registerDao(University.class, universityDao); // registerDao(Rule.class, ruleDao); // registerDao(Action.class, actionDao); // registerDao(ActionParam.class, actionParamDao); // registerDao(TransformerMapping.class, transformerMappingDao); // registerDao(GradeEntry.class, gradeEntryDao); // registerDao(Overview.class, overviewDao); // } // // public void clear() { // universityDaoConfig.getIdentityScope().clear(); // ruleDaoConfig.getIdentityScope().clear(); // actionDaoConfig.getIdentityScope().clear(); // actionParamDaoConfig.getIdentityScope().clear(); // transformerMappingDaoConfig.getIdentityScope().clear(); // gradeEntryDaoConfig.getIdentityScope().clear(); // overviewDaoConfig.getIdentityScope().clear(); // } // // public UniversityDao getUniversityDao() { // return universityDao; // } // // public RuleDao getRuleDao() { // return ruleDao; // } // // public ActionDao getActionDao() { // return actionDao; // } // // public ActionParamDao getActionParamDao() { // return actionParamDao; // } // // public TransformerMappingDao getTransformerMappingDao() { // return transformerMappingDao; // } // // public GradeEntryDao getGradeEntryDao() { // return gradeEntryDao; // } // // public OverviewDao getOverviewDao() { // return overviewDao; // } // // }
import java.util.List; import de.mygrades.database.dao.DaoSession; import de.greenrobot.dao.DaoException;
package de.mygrades.database.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here // KEEP INCLUDES END /** * Entity mapped to table "UNIVERSITY". */ public class University { private Long universityId; /** Not-null value. */ private String name; private Boolean published; private String updatedAtServer; /** Used to resolve relations */
// Path: app/src/main/java/de/mygrades/database/dao/DaoSession.java // public class DaoSession extends AbstractDaoSession { // // private final DaoConfig universityDaoConfig; // private final DaoConfig ruleDaoConfig; // private final DaoConfig actionDaoConfig; // private final DaoConfig actionParamDaoConfig; // private final DaoConfig transformerMappingDaoConfig; // private final DaoConfig gradeEntryDaoConfig; // private final DaoConfig overviewDaoConfig; // // private final UniversityDao universityDao; // private final RuleDao ruleDao; // private final ActionDao actionDao; // private final ActionParamDao actionParamDao; // private final TransformerMappingDao transformerMappingDao; // private final GradeEntryDao gradeEntryDao; // private final OverviewDao overviewDao; // // public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> // daoConfigMap) { // super(db); // // universityDaoConfig = daoConfigMap.get(UniversityDao.class).clone(); // universityDaoConfig.initIdentityScope(type); // // ruleDaoConfig = daoConfigMap.get(RuleDao.class).clone(); // ruleDaoConfig.initIdentityScope(type); // // actionDaoConfig = daoConfigMap.get(ActionDao.class).clone(); // actionDaoConfig.initIdentityScope(type); // // actionParamDaoConfig = daoConfigMap.get(ActionParamDao.class).clone(); // actionParamDaoConfig.initIdentityScope(type); // // transformerMappingDaoConfig = daoConfigMap.get(TransformerMappingDao.class).clone(); // transformerMappingDaoConfig.initIdentityScope(type); // // gradeEntryDaoConfig = daoConfigMap.get(GradeEntryDao.class).clone(); // gradeEntryDaoConfig.initIdentityScope(type); // // overviewDaoConfig = daoConfigMap.get(OverviewDao.class).clone(); // overviewDaoConfig.initIdentityScope(type); // // universityDao = new UniversityDao(universityDaoConfig, this); // ruleDao = new RuleDao(ruleDaoConfig, this); // actionDao = new ActionDao(actionDaoConfig, this); // actionParamDao = new ActionParamDao(actionParamDaoConfig, this); // transformerMappingDao = new TransformerMappingDao(transformerMappingDaoConfig, this); // gradeEntryDao = new GradeEntryDao(gradeEntryDaoConfig, this); // overviewDao = new OverviewDao(overviewDaoConfig, this); // // registerDao(University.class, universityDao); // registerDao(Rule.class, ruleDao); // registerDao(Action.class, actionDao); // registerDao(ActionParam.class, actionParamDao); // registerDao(TransformerMapping.class, transformerMappingDao); // registerDao(GradeEntry.class, gradeEntryDao); // registerDao(Overview.class, overviewDao); // } // // public void clear() { // universityDaoConfig.getIdentityScope().clear(); // ruleDaoConfig.getIdentityScope().clear(); // actionDaoConfig.getIdentityScope().clear(); // actionParamDaoConfig.getIdentityScope().clear(); // transformerMappingDaoConfig.getIdentityScope().clear(); // gradeEntryDaoConfig.getIdentityScope().clear(); // overviewDaoConfig.getIdentityScope().clear(); // } // // public UniversityDao getUniversityDao() { // return universityDao; // } // // public RuleDao getRuleDao() { // return ruleDao; // } // // public ActionDao getActionDao() { // return actionDao; // } // // public ActionParamDao getActionParamDao() { // return actionParamDao; // } // // public TransformerMappingDao getTransformerMappingDao() { // return transformerMappingDao; // } // // public GradeEntryDao getGradeEntryDao() { // return gradeEntryDao; // } // // public OverviewDao getOverviewDao() { // return overviewDao; // } // // } // Path: app/src/main/java/de/mygrades/database/dao/University.java import java.util.List; import de.mygrades.database.dao.DaoSession; import de.greenrobot.dao.DaoException; package de.mygrades.database.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here // KEEP INCLUDES END /** * Entity mapped to table "UNIVERSITY". */ public class University { private Long universityId; /** Not-null value. */ private String name; private Boolean published; private String updatedAtServer; /** Used to resolve relations */
private transient DaoSession daoSession;
MyGrades/mygrades-app
app/src/main/java/de/mygrades/view/adapter/model/SemesterItem.java
// Path: app/src/main/java/de/mygrades/util/AverageCalculator.java // public class AverageCalculator { // private float average; // private float creditPointsSum; // private boolean simpleWeighting; // // public AverageCalculator(boolean simpleWeighting) { // this.simpleWeighting = simpleWeighting; // } // // /** // * Calculates the average grade and credit points sum for a list of GradeItems. // * // * @param items - list of GradeAdapterItems // */ // public void calculate(List<? extends GradesAdapterItem> items) { // average = 0f; // creditPointsSum = 0f; // float creditPointsSumForAverage = 0f; // some grade_entries may have credit points, but no grade // float passedGradesCounter = 0; // used, if simpleWeighting is true // // // iterate over items, count credit points and calculate average // for(GradesAdapterItem item : items) { // if (!(item instanceof GradeItem)) // continue; // // GradeItem gradeItem = (GradeItem) item; // if (gradeItem.isHidden()) // continue; // // double weight = gradeItem.getWeight() == null ? 1 : gradeItem.getWeight(); // // double actCreditPoints = (gradeItem.getCreditPoints() == null ? 0f : gradeItem.getCreditPoints()); // Double modifiedCreditPoints = gradeItem.getModifiedCreditPoints(); // actCreditPoints = modifiedCreditPoints == null ? actCreditPoints : modifiedCreditPoints; // // double grade = (gradeItem.getGrade() == null ? 0f : gradeItem.getGrade()); // Double modifiedGrade = gradeItem.getModifiedGrade(); // grade = modifiedGrade == null ? grade : modifiedGrade; // // if (grade >= 0 && grade < 5) { // creditPointsSum += actCreditPoints; // // only add cps with actual grade to the sum of credit points for average calculation // if (grade > 0) { // creditPointsSumForAverage += (actCreditPoints * weight); // } // } // // if (simpleWeighting && isGradeRelevant(grade)) { // passedGradesCounter += weight; // average += (grade * weight); // } else if (isGradeRelevant(grade)){ // average += grade * actCreditPoints * weight; // } // } // // if (simpleWeighting) { // average = passedGradesCounter > 0 ? average / passedGradesCounter : 0f; // } else { // average = creditPointsSumForAverage > 0 ? average / creditPointsSumForAverage : 0f; // } // } // // /** // * Converts grade entries to grade items and calculates the average and credit points sum. // * // * @param gradeEntries - list of grade entries // */ // public void calculateFromGradeEntries(List<GradeEntry> gradeEntries) { // List<GradeItem> gradeItems = new ArrayList<>(); // for(GradeEntry entry : gradeEntries) { // gradeItems.add(new GradeItem(entry)); // } // calculate(gradeItems); // } // // /** // * Checks if a grade is relevant for average calculation and credit point sum. // * // * @param grade grade to check // * @return true, if grade is relevant // */ // private boolean isGradeRelevant(double grade) { // return grade > 0 && grade < 5; // } // // public float getAverage() { // return average; // } // // public float getCreditPointsSum() { // return creditPointsSum; // } // }
import java.util.ArrayList; import java.util.List; import de.mygrades.util.AverageCalculator;
package de.mygrades.view.adapter.model; /** * Semester item used in GradesRecyclerViewAdapter. */ public class SemesterItem implements GradesAdapterItem { private String semester; private float average; private float creditPoints; private List<GradeItem> grades; private boolean simpleWeighting; public SemesterItem(boolean simpleWeighting) { grades = new ArrayList<>(); this.simpleWeighting = simpleWeighting; } public void addGrade(GradeItem gradeItem, boolean updateImmediately) { grades.add(gradeItem); if (updateImmediately) { update(); } } /** * Updates the average grade and the sum of credit points. */ public void update() {
// Path: app/src/main/java/de/mygrades/util/AverageCalculator.java // public class AverageCalculator { // private float average; // private float creditPointsSum; // private boolean simpleWeighting; // // public AverageCalculator(boolean simpleWeighting) { // this.simpleWeighting = simpleWeighting; // } // // /** // * Calculates the average grade and credit points sum for a list of GradeItems. // * // * @param items - list of GradeAdapterItems // */ // public void calculate(List<? extends GradesAdapterItem> items) { // average = 0f; // creditPointsSum = 0f; // float creditPointsSumForAverage = 0f; // some grade_entries may have credit points, but no grade // float passedGradesCounter = 0; // used, if simpleWeighting is true // // // iterate over items, count credit points and calculate average // for(GradesAdapterItem item : items) { // if (!(item instanceof GradeItem)) // continue; // // GradeItem gradeItem = (GradeItem) item; // if (gradeItem.isHidden()) // continue; // // double weight = gradeItem.getWeight() == null ? 1 : gradeItem.getWeight(); // // double actCreditPoints = (gradeItem.getCreditPoints() == null ? 0f : gradeItem.getCreditPoints()); // Double modifiedCreditPoints = gradeItem.getModifiedCreditPoints(); // actCreditPoints = modifiedCreditPoints == null ? actCreditPoints : modifiedCreditPoints; // // double grade = (gradeItem.getGrade() == null ? 0f : gradeItem.getGrade()); // Double modifiedGrade = gradeItem.getModifiedGrade(); // grade = modifiedGrade == null ? grade : modifiedGrade; // // if (grade >= 0 && grade < 5) { // creditPointsSum += actCreditPoints; // // only add cps with actual grade to the sum of credit points for average calculation // if (grade > 0) { // creditPointsSumForAverage += (actCreditPoints * weight); // } // } // // if (simpleWeighting && isGradeRelevant(grade)) { // passedGradesCounter += weight; // average += (grade * weight); // } else if (isGradeRelevant(grade)){ // average += grade * actCreditPoints * weight; // } // } // // if (simpleWeighting) { // average = passedGradesCounter > 0 ? average / passedGradesCounter : 0f; // } else { // average = creditPointsSumForAverage > 0 ? average / creditPointsSumForAverage : 0f; // } // } // // /** // * Converts grade entries to grade items and calculates the average and credit points sum. // * // * @param gradeEntries - list of grade entries // */ // public void calculateFromGradeEntries(List<GradeEntry> gradeEntries) { // List<GradeItem> gradeItems = new ArrayList<>(); // for(GradeEntry entry : gradeEntries) { // gradeItems.add(new GradeItem(entry)); // } // calculate(gradeItems); // } // // /** // * Checks if a grade is relevant for average calculation and credit point sum. // * // * @param grade grade to check // * @return true, if grade is relevant // */ // private boolean isGradeRelevant(double grade) { // return grade > 0 && grade < 5; // } // // public float getAverage() { // return average; // } // // public float getCreditPointsSum() { // return creditPointsSum; // } // } // Path: app/src/main/java/de/mygrades/view/adapter/model/SemesterItem.java import java.util.ArrayList; import java.util.List; import de.mygrades.util.AverageCalculator; package de.mygrades.view.adapter.model; /** * Semester item used in GradesRecyclerViewAdapter. */ public class SemesterItem implements GradesAdapterItem { private String semester; private float average; private float creditPoints; private List<GradeItem> grades; private boolean simpleWeighting; public SemesterItem(boolean simpleWeighting) { grades = new ArrayList<>(); this.simpleWeighting = simpleWeighting; } public void addGrade(GradeItem gradeItem, boolean updateImmediately) { grades.add(gradeItem); if (updateImmediately) { update(); } } /** * Updates the average grade and the sum of credit points. */ public void update() {
AverageCalculator calculator = new AverageCalculator(simpleWeighting);
MyGrades/mygrades-app
app/src/main/java/de/mygrades/database/dao/Rule.java
// Path: app/src/main/java/de/mygrades/database/dao/DaoSession.java // public class DaoSession extends AbstractDaoSession { // // private final DaoConfig universityDaoConfig; // private final DaoConfig ruleDaoConfig; // private final DaoConfig actionDaoConfig; // private final DaoConfig actionParamDaoConfig; // private final DaoConfig transformerMappingDaoConfig; // private final DaoConfig gradeEntryDaoConfig; // private final DaoConfig overviewDaoConfig; // // private final UniversityDao universityDao; // private final RuleDao ruleDao; // private final ActionDao actionDao; // private final ActionParamDao actionParamDao; // private final TransformerMappingDao transformerMappingDao; // private final GradeEntryDao gradeEntryDao; // private final OverviewDao overviewDao; // // public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> // daoConfigMap) { // super(db); // // universityDaoConfig = daoConfigMap.get(UniversityDao.class).clone(); // universityDaoConfig.initIdentityScope(type); // // ruleDaoConfig = daoConfigMap.get(RuleDao.class).clone(); // ruleDaoConfig.initIdentityScope(type); // // actionDaoConfig = daoConfigMap.get(ActionDao.class).clone(); // actionDaoConfig.initIdentityScope(type); // // actionParamDaoConfig = daoConfigMap.get(ActionParamDao.class).clone(); // actionParamDaoConfig.initIdentityScope(type); // // transformerMappingDaoConfig = daoConfigMap.get(TransformerMappingDao.class).clone(); // transformerMappingDaoConfig.initIdentityScope(type); // // gradeEntryDaoConfig = daoConfigMap.get(GradeEntryDao.class).clone(); // gradeEntryDaoConfig.initIdentityScope(type); // // overviewDaoConfig = daoConfigMap.get(OverviewDao.class).clone(); // overviewDaoConfig.initIdentityScope(type); // // universityDao = new UniversityDao(universityDaoConfig, this); // ruleDao = new RuleDao(ruleDaoConfig, this); // actionDao = new ActionDao(actionDaoConfig, this); // actionParamDao = new ActionParamDao(actionParamDaoConfig, this); // transformerMappingDao = new TransformerMappingDao(transformerMappingDaoConfig, this); // gradeEntryDao = new GradeEntryDao(gradeEntryDaoConfig, this); // overviewDao = new OverviewDao(overviewDaoConfig, this); // // registerDao(University.class, universityDao); // registerDao(Rule.class, ruleDao); // registerDao(Action.class, actionDao); // registerDao(ActionParam.class, actionParamDao); // registerDao(TransformerMapping.class, transformerMappingDao); // registerDao(GradeEntry.class, gradeEntryDao); // registerDao(Overview.class, overviewDao); // } // // public void clear() { // universityDaoConfig.getIdentityScope().clear(); // ruleDaoConfig.getIdentityScope().clear(); // actionDaoConfig.getIdentityScope().clear(); // actionParamDaoConfig.getIdentityScope().clear(); // transformerMappingDaoConfig.getIdentityScope().clear(); // gradeEntryDaoConfig.getIdentityScope().clear(); // overviewDaoConfig.getIdentityScope().clear(); // } // // public UniversityDao getUniversityDao() { // return universityDao; // } // // public RuleDao getRuleDao() { // return ruleDao; // } // // public ActionDao getActionDao() { // return actionDao; // } // // public ActionParamDao getActionParamDao() { // return actionParamDao; // } // // public TransformerMappingDao getTransformerMappingDao() { // return transformerMappingDao; // } // // public GradeEntryDao getGradeEntryDao() { // return gradeEntryDao; // } // // public OverviewDao getOverviewDao() { // return overviewDao; // } // // }
import java.util.List; import de.mygrades.database.dao.DaoSession; import de.greenrobot.dao.DaoException;
package de.mygrades.database.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here // KEEP INCLUDES END /** * Entity mapped to table "RULE". */ public class Rule { private Long ruleId; /** Not-null value. */ private String name; private String semesterFormat; private String semesterPattern; private Integer semesterStartSummer; private Integer semesterStartWinter; private Double gradeFactor; private java.util.Date lastUpdated; private Boolean overview; private String type; private long universityId; /** Used to resolve relations */
// Path: app/src/main/java/de/mygrades/database/dao/DaoSession.java // public class DaoSession extends AbstractDaoSession { // // private final DaoConfig universityDaoConfig; // private final DaoConfig ruleDaoConfig; // private final DaoConfig actionDaoConfig; // private final DaoConfig actionParamDaoConfig; // private final DaoConfig transformerMappingDaoConfig; // private final DaoConfig gradeEntryDaoConfig; // private final DaoConfig overviewDaoConfig; // // private final UniversityDao universityDao; // private final RuleDao ruleDao; // private final ActionDao actionDao; // private final ActionParamDao actionParamDao; // private final TransformerMappingDao transformerMappingDao; // private final GradeEntryDao gradeEntryDao; // private final OverviewDao overviewDao; // // public DaoSession(SQLiteDatabase db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig> // daoConfigMap) { // super(db); // // universityDaoConfig = daoConfigMap.get(UniversityDao.class).clone(); // universityDaoConfig.initIdentityScope(type); // // ruleDaoConfig = daoConfigMap.get(RuleDao.class).clone(); // ruleDaoConfig.initIdentityScope(type); // // actionDaoConfig = daoConfigMap.get(ActionDao.class).clone(); // actionDaoConfig.initIdentityScope(type); // // actionParamDaoConfig = daoConfigMap.get(ActionParamDao.class).clone(); // actionParamDaoConfig.initIdentityScope(type); // // transformerMappingDaoConfig = daoConfigMap.get(TransformerMappingDao.class).clone(); // transformerMappingDaoConfig.initIdentityScope(type); // // gradeEntryDaoConfig = daoConfigMap.get(GradeEntryDao.class).clone(); // gradeEntryDaoConfig.initIdentityScope(type); // // overviewDaoConfig = daoConfigMap.get(OverviewDao.class).clone(); // overviewDaoConfig.initIdentityScope(type); // // universityDao = new UniversityDao(universityDaoConfig, this); // ruleDao = new RuleDao(ruleDaoConfig, this); // actionDao = new ActionDao(actionDaoConfig, this); // actionParamDao = new ActionParamDao(actionParamDaoConfig, this); // transformerMappingDao = new TransformerMappingDao(transformerMappingDaoConfig, this); // gradeEntryDao = new GradeEntryDao(gradeEntryDaoConfig, this); // overviewDao = new OverviewDao(overviewDaoConfig, this); // // registerDao(University.class, universityDao); // registerDao(Rule.class, ruleDao); // registerDao(Action.class, actionDao); // registerDao(ActionParam.class, actionParamDao); // registerDao(TransformerMapping.class, transformerMappingDao); // registerDao(GradeEntry.class, gradeEntryDao); // registerDao(Overview.class, overviewDao); // } // // public void clear() { // universityDaoConfig.getIdentityScope().clear(); // ruleDaoConfig.getIdentityScope().clear(); // actionDaoConfig.getIdentityScope().clear(); // actionParamDaoConfig.getIdentityScope().clear(); // transformerMappingDaoConfig.getIdentityScope().clear(); // gradeEntryDaoConfig.getIdentityScope().clear(); // overviewDaoConfig.getIdentityScope().clear(); // } // // public UniversityDao getUniversityDao() { // return universityDao; // } // // public RuleDao getRuleDao() { // return ruleDao; // } // // public ActionDao getActionDao() { // return actionDao; // } // // public ActionParamDao getActionParamDao() { // return actionParamDao; // } // // public TransformerMappingDao getTransformerMappingDao() { // return transformerMappingDao; // } // // public GradeEntryDao getGradeEntryDao() { // return gradeEntryDao; // } // // public OverviewDao getOverviewDao() { // return overviewDao; // } // // } // Path: app/src/main/java/de/mygrades/database/dao/Rule.java import java.util.List; import de.mygrades.database.dao.DaoSession; import de.greenrobot.dao.DaoException; package de.mygrades.database.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here // KEEP INCLUDES END /** * Entity mapped to table "RULE". */ public class Rule { private Long ruleId; /** Not-null value. */ private String name; private String semesterFormat; private String semesterPattern; private Integer semesterStartSummer; private Integer semesterStartWinter; private Double gradeFactor; private java.util.Date lastUpdated; private Boolean overview; private String type; private long universityId; /** Used to resolve relations */
private transient DaoSession daoSession;
MyGrades/mygrades-app
app/src/main/java/de/mygrades/view/adapter/model/UniversityHeader.java
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // }
import de.mygrades.main.events.ErrorEvent;
package de.mygrades.view.adapter.model; /** * Header above list of sectioned universities. * It holds the state for the loading animation and current error. */ public class UniversityHeader extends UniversityGroupItem { private boolean isLoading;
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityHeader.java import de.mygrades.main.events.ErrorEvent; package de.mygrades.view.adapter.model; /** * Header above list of sectioned universities. * It holds the state for the loading animation and current error. */ public class UniversityHeader extends UniversityGroupItem { private boolean isLoading;
private ErrorEvent.ErrorType actErrorType;
MyGrades/mygrades-app
app/src/main/java/de/mygrades/main/processor/ErrorProcessor.java
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/ErrorReportDoneEvent.java // public class ErrorReportDoneEvent { // } // // Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // }
import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.ErrorReportDoneEvent; import de.mygrades.util.Constants; import retrofit.RetrofitError;
package de.mygrades.main.processor; /** * ErrorProcessor is responsible to send error reports from users to the server. */ public class ErrorProcessor extends BaseProcessor { private static final String TAG = ErrorProcessor.class.getSimpleName(); public ErrorProcessor(Context context) { super(context); } /** * Posts an error to the server. * * @param name - name * @param email - email address * @param errorMessage - error message */ public void postErrorReport(String name, String email, String errorMessage) { // No Connection -> event no Connection, abort if (!isOnline()) {
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/ErrorReportDoneEvent.java // public class ErrorReportDoneEvent { // } // // Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // } // Path: app/src/main/java/de/mygrades/main/processor/ErrorProcessor.java import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.ErrorReportDoneEvent; import de.mygrades.util.Constants; import retrofit.RetrofitError; package de.mygrades.main.processor; /** * ErrorProcessor is responsible to send error reports from users to the server. */ public class ErrorProcessor extends BaseProcessor { private static final String TAG = ErrorProcessor.class.getSimpleName(); public ErrorProcessor(Context context) { super(context); } /** * Posts an error to the server. * * @param name - name * @param email - email address * @param errorMessage - error message */ public void postErrorReport(String name, String email, String errorMessage) { // No Connection -> event no Connection, abort if (!isOnline()) {
postErrorEvent(ErrorEvent.ErrorType.NO_NETWORK, "No Internet Connection!");
MyGrades/mygrades-app
app/src/main/java/de/mygrades/main/processor/ErrorProcessor.java
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/ErrorReportDoneEvent.java // public class ErrorReportDoneEvent { // } // // Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // }
import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.ErrorReportDoneEvent; import de.mygrades.util.Constants; import retrofit.RetrofitError;
package de.mygrades.main.processor; /** * ErrorProcessor is responsible to send error reports from users to the server. */ public class ErrorProcessor extends BaseProcessor { private static final String TAG = ErrorProcessor.class.getSimpleName(); public ErrorProcessor(Context context) { super(context); } /** * Posts an error to the server. * * @param name - name * @param email - email address * @param errorMessage - error message */ public void postErrorReport(String name, String email, String errorMessage) { // No Connection -> event no Connection, abort if (!isOnline()) { postErrorEvent(ErrorEvent.ErrorType.NO_NETWORK, "No Internet Connection!"); return; } try { // get university id SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/ErrorReportDoneEvent.java // public class ErrorReportDoneEvent { // } // // Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // } // Path: app/src/main/java/de/mygrades/main/processor/ErrorProcessor.java import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.ErrorReportDoneEvent; import de.mygrades.util.Constants; import retrofit.RetrofitError; package de.mygrades.main.processor; /** * ErrorProcessor is responsible to send error reports from users to the server. */ public class ErrorProcessor extends BaseProcessor { private static final String TAG = ErrorProcessor.class.getSimpleName(); public ErrorProcessor(Context context) { super(context); } /** * Posts an error to the server. * * @param name - name * @param email - email address * @param errorMessage - error message */ public void postErrorReport(String name, String email, String errorMessage) { // No Connection -> event no Connection, abort if (!isOnline()) { postErrorEvent(ErrorEvent.ErrorType.NO_NETWORK, "No Internet Connection!"); return; } try { // get university id SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
long universityId = prefs.getLong(Constants.PREF_KEY_UNIVERSITY_ID, -1);
MyGrades/mygrades-app
app/src/main/java/de/mygrades/main/processor/ErrorProcessor.java
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/ErrorReportDoneEvent.java // public class ErrorReportDoneEvent { // } // // Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // }
import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.ErrorReportDoneEvent; import de.mygrades.util.Constants; import retrofit.RetrofitError;
package de.mygrades.main.processor; /** * ErrorProcessor is responsible to send error reports from users to the server. */ public class ErrorProcessor extends BaseProcessor { private static final String TAG = ErrorProcessor.class.getSimpleName(); public ErrorProcessor(Context context) { super(context); } /** * Posts an error to the server. * * @param name - name * @param email - email address * @param errorMessage - error message */ public void postErrorReport(String name, String email, String errorMessage) { // No Connection -> event no Connection, abort if (!isOnline()) { postErrorEvent(ErrorEvent.ErrorType.NO_NETWORK, "No Internet Connection!"); return; } try { // get university id SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); long universityId = prefs.getLong(Constants.PREF_KEY_UNIVERSITY_ID, -1); long ruleId = prefs.getLong(Constants.PREF_KEY_RULE_ID, -1); // create error report Error error = new Error(); error.setName(name); error.setEmail(email); error.setMessage(errorMessage); error.setAppVersion(BuildConfig.VERSION_NAME); error.setUniversityId(universityId); error.setRuleId(ruleId); error.setAndroidVersion(Build.VERSION.RELEASE + ", " + Build.VERSION.SDK_INT); error.setDevice(Build.MANUFACTURER + ", " + Build.MODEL); // post to server restClient.getRestApi().postError(error); // post event
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/ErrorReportDoneEvent.java // public class ErrorReportDoneEvent { // } // // Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // } // Path: app/src/main/java/de/mygrades/main/processor/ErrorProcessor.java import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.ErrorReportDoneEvent; import de.mygrades.util.Constants; import retrofit.RetrofitError; package de.mygrades.main.processor; /** * ErrorProcessor is responsible to send error reports from users to the server. */ public class ErrorProcessor extends BaseProcessor { private static final String TAG = ErrorProcessor.class.getSimpleName(); public ErrorProcessor(Context context) { super(context); } /** * Posts an error to the server. * * @param name - name * @param email - email address * @param errorMessage - error message */ public void postErrorReport(String name, String email, String errorMessage) { // No Connection -> event no Connection, abort if (!isOnline()) { postErrorEvent(ErrorEvent.ErrorType.NO_NETWORK, "No Internet Connection!"); return; } try { // get university id SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); long universityId = prefs.getLong(Constants.PREF_KEY_UNIVERSITY_ID, -1); long ruleId = prefs.getLong(Constants.PREF_KEY_RULE_ID, -1); // create error report Error error = new Error(); error.setName(name); error.setEmail(email); error.setMessage(errorMessage); error.setAppVersion(BuildConfig.VERSION_NAME); error.setUniversityId(universityId); error.setRuleId(ruleId); error.setAndroidVersion(Build.VERSION.RELEASE + ", " + Build.VERSION.SDK_INT); error.setDevice(Build.MANUFACTURER + ", " + Build.MODEL); // post to server restClient.getRestApi().postError(error); // post event
EventBus.getDefault().post(new ErrorReportDoneEvent());
MyGrades/mygrades-app
app/src/main/java/de/mygrades/main/processor/WishProcessor.java
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/PostWishDoneEvent.java // public class PostWishDoneEvent { // }
import android.content.Context; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.PostWishDoneEvent; import retrofit.RetrofitError;
package de.mygrades.main.processor; /** * WishProcessor is used to send university wishes from users to the server. */ public class WishProcessor extends BaseProcessor { private static final String TAG = WishProcessor.class.getSimpleName(); public WishProcessor(Context context) { super(context); } /** * Posts an university wish to the server. * * @param universityName - university name * @param name - name * @param email - email address * @param message - message */ public void postWish(String universityName, String name, String email, String message) { // No Connection -> event no Connection, abort if (!isOnline()) {
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/PostWishDoneEvent.java // public class PostWishDoneEvent { // } // Path: app/src/main/java/de/mygrades/main/processor/WishProcessor.java import android.content.Context; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.PostWishDoneEvent; import retrofit.RetrofitError; package de.mygrades.main.processor; /** * WishProcessor is used to send university wishes from users to the server. */ public class WishProcessor extends BaseProcessor { private static final String TAG = WishProcessor.class.getSimpleName(); public WishProcessor(Context context) { super(context); } /** * Posts an university wish to the server. * * @param universityName - university name * @param name - name * @param email - email address * @param message - message */ public void postWish(String universityName, String name, String email, String message) { // No Connection -> event no Connection, abort if (!isOnline()) {
postErrorEvent(ErrorEvent.ErrorType.NO_NETWORK, "No Internet Connection!");
MyGrades/mygrades-app
app/src/main/java/de/mygrades/main/processor/WishProcessor.java
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/PostWishDoneEvent.java // public class PostWishDoneEvent { // }
import android.content.Context; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.PostWishDoneEvent; import retrofit.RetrofitError;
package de.mygrades.main.processor; /** * WishProcessor is used to send university wishes from users to the server. */ public class WishProcessor extends BaseProcessor { private static final String TAG = WishProcessor.class.getSimpleName(); public WishProcessor(Context context) { super(context); } /** * Posts an university wish to the server. * * @param universityName - university name * @param name - name * @param email - email address * @param message - message */ public void postWish(String universityName, String name, String email, String message) { // No Connection -> event no Connection, abort if (!isOnline()) { postErrorEvent(ErrorEvent.ErrorType.NO_NETWORK, "No Internet Connection!"); return; } try { // create wish Wish wish = new Wish(); wish.setUniversityName(universityName); wish.setName(name); wish.setEmail(email); wish.setMessage(message); wish.setAppVersion(BuildConfig.VERSION_NAME); // post to server restClient.getRestApi().postWish(wish); // post event
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // // Path: app/src/main/java/de/mygrades/main/events/PostWishDoneEvent.java // public class PostWishDoneEvent { // } // Path: app/src/main/java/de/mygrades/main/processor/WishProcessor.java import android.content.Context; import de.greenrobot.event.EventBus; import de.mygrades.BuildConfig; import de.mygrades.main.events.ErrorEvent; import de.mygrades.main.events.PostWishDoneEvent; import retrofit.RetrofitError; package de.mygrades.main.processor; /** * WishProcessor is used to send university wishes from users to the server. */ public class WishProcessor extends BaseProcessor { private static final String TAG = WishProcessor.class.getSimpleName(); public WishProcessor(Context context) { super(context); } /** * Posts an university wish to the server. * * @param universityName - university name * @param name - name * @param email - email address * @param message - message */ public void postWish(String universityName, String name, String email, String message) { // No Connection -> event no Connection, abort if (!isOnline()) { postErrorEvent(ErrorEvent.ErrorType.NO_NETWORK, "No Internet Connection!"); return; } try { // create wish Wish wish = new Wish(); wish.setUniversityName(universityName); wish.setName(name); wish.setEmail(email); wish.setMessage(message); wish.setAppVersion(BuildConfig.VERSION_NAME); // post to server restClient.getRestApi().postWish(wish); // post event
EventBus.getDefault().post(new PostWishDoneEvent());
MyGrades/mygrades-app
app/src/main/java/de/mygrades/view/PtrHeader.java
// Path: app/src/main/java/de/mygrades/main/events/ScrapeProgressEvent.java // public class ScrapeProgressEvent { // private int currentStep; // private int stepCount; // private boolean isScrapeForOverview; // private String gradeHash; // // public ScrapeProgressEvent(int currentStep, int stepCount) { // this.currentStep = currentStep; // this.stepCount = stepCount; // this.isScrapeForOverview = false; // this.gradeHash = null; // } // // public ScrapeProgressEvent(int currentStep, int stepCount, boolean isScrapeForOverview) { // this(currentStep, stepCount); // this.isScrapeForOverview = isScrapeForOverview; // } // // public ScrapeProgressEvent(int currentStep, int stepCount, boolean isScrapeForOverview, String gradeHash) { // this(currentStep, stepCount, isScrapeForOverview); // this.gradeHash = gradeHash; // } // // public int getCurrentStep() { // return currentStep; // } // // public void setCurrentStep(int currentStep) { // this.currentStep = currentStep; // } // // public int getStepCount() { // return stepCount; // } // // public void setStepCount(int stepCount) { // this.stepCount = stepCount; // } // // public boolean isScrapeForOverview() { // return isScrapeForOverview; // } // // public void setIsScrapeForOverview(boolean isScrapeForOverview) { // this.isScrapeForOverview = isScrapeForOverview; // } // // public String getGradeHash() { // return gradeHash; // } // // public void setGradeHash(String gradeHash) { // this.gradeHash = gradeHash; // } // } // // Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // }
import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.os.Bundle; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.animation.AnimationUtils; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.FrameLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import de.greenrobot.event.EventBus; import de.mygrades.R; import de.mygrades.main.events.ScrapeProgressEvent; import de.mygrades.util.Constants; import in.srain.cube.views.ptr.PtrFrameLayout; import in.srain.cube.views.ptr.PtrUIHandler; import in.srain.cube.views.ptr.indicator.PtrIndicator; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.FrameLayout; import android.widget.TextView; import com.pnikosis.materialishprogress.ProgressWheel; import org.w3c.dom.Text; import in.srain.cube.views.ptr.indicator.PtrIndicator; import java.text.SimpleDateFormat; import java.util.Date;
tvHeaderText.setText(R.string.ptr_header_release_to_refresh); } } } /** * Increases progress on progressWheel. * * @param currentStep current step * @param stepCount count of steps */ public void increaseProgress(int currentStep, int stepCount) { progressWheel.increaseProgress(currentStep, stepCount); } /** * Set progress on progressWheel. * * @param progress Progress of Loading */ public void setProgress(float progress) { progressWheel.setProgress(progress); } /** * Save attributes regarding ptr to instance state. * @param outState instance state bundle */ public void saveInstanceState(Bundle outState) {
// Path: app/src/main/java/de/mygrades/main/events/ScrapeProgressEvent.java // public class ScrapeProgressEvent { // private int currentStep; // private int stepCount; // private boolean isScrapeForOverview; // private String gradeHash; // // public ScrapeProgressEvent(int currentStep, int stepCount) { // this.currentStep = currentStep; // this.stepCount = stepCount; // this.isScrapeForOverview = false; // this.gradeHash = null; // } // // public ScrapeProgressEvent(int currentStep, int stepCount, boolean isScrapeForOverview) { // this(currentStep, stepCount); // this.isScrapeForOverview = isScrapeForOverview; // } // // public ScrapeProgressEvent(int currentStep, int stepCount, boolean isScrapeForOverview, String gradeHash) { // this(currentStep, stepCount, isScrapeForOverview); // this.gradeHash = gradeHash; // } // // public int getCurrentStep() { // return currentStep; // } // // public void setCurrentStep(int currentStep) { // this.currentStep = currentStep; // } // // public int getStepCount() { // return stepCount; // } // // public void setStepCount(int stepCount) { // this.stepCount = stepCount; // } // // public boolean isScrapeForOverview() { // return isScrapeForOverview; // } // // public void setIsScrapeForOverview(boolean isScrapeForOverview) { // this.isScrapeForOverview = isScrapeForOverview; // } // // public String getGradeHash() { // return gradeHash; // } // // public void setGradeHash(String gradeHash) { // this.gradeHash = gradeHash; // } // } // // Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // } // Path: app/src/main/java/de/mygrades/view/PtrHeader.java import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.os.Bundle; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.animation.AnimationUtils; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.FrameLayout; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import de.greenrobot.event.EventBus; import de.mygrades.R; import de.mygrades.main.events.ScrapeProgressEvent; import de.mygrades.util.Constants; import in.srain.cube.views.ptr.PtrFrameLayout; import in.srain.cube.views.ptr.PtrUIHandler; import in.srain.cube.views.ptr.indicator.PtrIndicator; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.FrameLayout; import android.widget.TextView; import com.pnikosis.materialishprogress.ProgressWheel; import org.w3c.dom.Text; import in.srain.cube.views.ptr.indicator.PtrIndicator; import java.text.SimpleDateFormat; import java.util.Date; tvHeaderText.setText(R.string.ptr_header_release_to_refresh); } } } /** * Increases progress on progressWheel. * * @param currentStep current step * @param stepCount count of steps */ public void increaseProgress(int currentStep, int stepCount) { progressWheel.increaseProgress(currentStep, stepCount); } /** * Set progress on progressWheel. * * @param progress Progress of Loading */ public void setProgress(float progress) { progressWheel.setProgress(progress); } /** * Save attributes regarding ptr to instance state. * @param outState instance state bundle */ public void saveInstanceState(Bundle outState) {
outState.putBoolean(Constants.INSTANCE_IS_SCRAPING_STATE, isScraping);
MyGrades/mygrades-app
app/src/main/java/de/mygrades/main/alarm/ScrapeAlarmManager.java
// Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Log; import de.mygrades.R; import de.mygrades.util.Constants;
// minutes * 60 secs * 1000 msec long interval = intervalMinutes * 60 * 1000; // first alarm triggers minimum 10 minutes after being set long trigger = 10 * 60 * 1000; // we can't use setInexactRepeating, because of the rare predefined intervals alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + trigger, interval, alarmIntent); Log.d(TAG, "Alarm set. Interval: " + interval + ", Trigger: " + trigger); // enable boot receiver to set alarm after reboot packageManager.setComponentEnabledSetting(bootReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); Log.d(TAG, "BootReceiver enabled!"); } /** * Sets an one time fallback alarm if necessary. * It is set in 1/4 of the original interval time. * So at maximum there can be 3 one time fallback alarms within * an interval of original repeating alarm. * @param isError is this one time alarm caused by an error? */ public void setOneTimeFallbackAlarm(boolean isError) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); if (isError) {
// Path: app/src/main/java/de/mygrades/util/Constants.java // public class Constants { // // // secure preferences constants // public static final String NOT_SO_SECURE_PREF_FILE = "userdata"; // public static final String PREF_KEY_USERNAME = "username"; // public static final String PREF_KEY_PASSWORD = "password"; // // // normal preferences constants // public static final String PREF_KEY_UNIVERSITY_ID = "university_id"; // public static final String PREF_KEY_RULE_ID = "rule_id"; // public static final String PREF_KEY_INITIAL_LOADING_DONE = "initial_loading_done"; // public static final String PREF_KEY_LAST_UPDATED_AT = "last_updated_at"; // public static final String PREF_KEY_SCRAPING_FAILS_INTERVAL = "scraping_fails_interval"; // public static final String PREF_KEY_ALARM_ERROR_SCRAPING_COUNT = "alarm_error_scraping_count"; // public static final String PREF_KEY_DISMISSED_NOTIFICATION_INFO = "dismissed_notification_info"; // public static final String PREF_KEY_DISMISSED_DONATION_INFO = "dismissed_donation_info"; // public static final String PREF_KEY_DISMISSED_RATING_INFO = "dismissed_rating_info"; // public static final String PREF_KEY_DISMISSED_EDIT_MODE_INFO = "dismissed_edit_mode_info"; // public static final String PREF_KEY_APPLICATION_LAUNCHES_COUNTER = "application_launches_counter"; // // // Scraping status instance state // public static final String INSTANCE_IS_SCRAPING_STATE = "is_scraping_state"; // public static final String INSTANCE_PROGRESS_STATE = "progress_state"; // // // grade entry 'seen' state // public static final int GRADE_ENTRY_SEEN = 0; // public static final int GRADE_ENTRY_NEW = 1; // public static final int GRADE_ENTRY_UPDATED = 2; // } // Path: app/src/main/java/de/mygrades/main/alarm/ScrapeAlarmManager.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Log; import de.mygrades.R; import de.mygrades.util.Constants; // minutes * 60 secs * 1000 msec long interval = intervalMinutes * 60 * 1000; // first alarm triggers minimum 10 minutes after being set long trigger = 10 * 60 * 1000; // we can't use setInexactRepeating, because of the rare predefined intervals alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + trigger, interval, alarmIntent); Log.d(TAG, "Alarm set. Interval: " + interval + ", Trigger: " + trigger); // enable boot receiver to set alarm after reboot packageManager.setComponentEnabledSetting(bootReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); Log.d(TAG, "BootReceiver enabled!"); } /** * Sets an one time fallback alarm if necessary. * It is set in 1/4 of the original interval time. * So at maximum there can be 3 one time fallback alarms within * an interval of original repeating alarm. * @param isError is this one time alarm caused by an error? */ public void setOneTimeFallbackAlarm(boolean isError) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); if (isError) {
int errorCount = prefs.getInt(Constants.PREF_KEY_ALARM_ERROR_SCRAPING_COUNT, 0);
MyGrades/mygrades-app
app/src/main/java/de/mygrades/view/adapter/dataprovider/UniversitiesDataProvider.java
// Path: app/src/main/java/de/mygrades/view/adapter/model/RuleItem.java // public class RuleItem implements Comparable<RuleItem> { // private long childId; // private String name; // private long ruleId; // // public RuleItem(long childId) { // this.childId = childId; // } // // public long getChildId() { // return childId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getRuleId() { // return ruleId; // } // // public void setRuleId(long ruleId) { // this.ruleId = ruleId; // } // // /** // * Starts an intent to go to the LoginActivity. // * // * @param context Context // * @param universityData UniversityData used in intent data // */ // public void goToLogin(Context context, UniversityItem universityData) { // final Intent intent = new Intent(context, LoginActivity.class); // // intent.putExtra(LoginActivity.EXTRA_UNIVERSITY_NAME, universityData.getName()); // intent.putExtra(LoginActivity.EXTRA_UNIVERSITY_ID, universityData.getUniversityId()); // intent.putExtra(LoginActivity.EXTRA_RULE_ID, ruleId); // context.startActivity(intent); // } // // @Override // public int compareTo(RuleItem another) { // return name.compareToIgnoreCase(another.getName()); // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityFooter.java // public class UniversityFooter extends UniversityGroupItem { // private boolean visible; // // public UniversityFooter() { // visible = false; // } // // @Override // public long getGroupId() { // return -1; // } // // public boolean isVisible() { // return visible; // } // // public void setVisible(boolean visible) { // this.visible = visible; // } // // public void goToSubmitWish(Context context) { // String uri = "de.mygrades.view.activity://goto.fragment/postwish"; // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); // context.startActivity(intent); // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityGroupItem.java // public abstract class UniversityGroupItem { // // /** // * Get the group id. // * ExpandableItemAdapter requires stable IDs for each group item. // * // * @return group id // */ // public abstract long getGroupId(); // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityHeader.java // public class UniversityHeader extends UniversityGroupItem { // private boolean isLoading; // private ErrorEvent.ErrorType actErrorType; // // public UniversityHeader() { // isLoading = false; // actErrorType = null; // } // // public boolean isLoading() { // return isLoading; // } // // public void setIsLoading(boolean isLoading) { // this.isLoading = isLoading; // } // // public ErrorEvent.ErrorType getActErrorType() { // return actErrorType; // } // // public void setActErrorType(ErrorEvent.ErrorType actErrorType) { // this.actErrorType = actErrorType; // } // // @Override // public long getGroupId() { // return 0; // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityItem.java // public class UniversityItem extends UniversityGroupItem { // private long groupId; // private String name; // private long universityId; // private boolean isSectionHeader; // private String sectionTitle; // private boolean showRuleHint; // // private List<RuleItem> rules; // // public UniversityItem(long groupId) { // this.groupId = groupId; // rules = new ArrayList<>(); // showRuleHint = false; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // this.sectionTitle = String.valueOf(name.toUpperCase().charAt(0)); // } // // public long getUniversityId() { // return universityId; // } // // public void setUniversityId(long universityId) { // this.universityId = universityId; // } // // public boolean isSectionHeader() { // return isSectionHeader; // } // // public void setIsSectionHeader(boolean isSectionHeader) { // this.isSectionHeader = isSectionHeader; // } // // public List<RuleItem> getRules() { // return rules; // } // // public void addRuleData(RuleItem ruleItem) { // this.rules.add(ruleItem); // } // // public String getSectionTitle() { // return sectionTitle; // } // // @Override // public long getGroupId() { // return groupId; // } // // public boolean showRuleHint() { // return showRuleHint; // } // // public void setShowRuleHint(boolean showRuleHint) { // this.showRuleHint = showRuleHint; // } // }
import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; import de.mygrades.view.adapter.model.RuleItem; import de.mygrades.view.adapter.model.UniversityFooter; import de.mygrades.view.adapter.model.UniversityGroupItem; import de.mygrades.view.adapter.model.UniversityHeader; import de.mygrades.view.adapter.model.UniversityItem;
package de.mygrades.view.adapter.dataprovider; /** * UniversitiesDataProvider provides access to the underlying university items. */ public class UniversitiesDataProvider { private List<UniversityGroupItem> items;
// Path: app/src/main/java/de/mygrades/view/adapter/model/RuleItem.java // public class RuleItem implements Comparable<RuleItem> { // private long childId; // private String name; // private long ruleId; // // public RuleItem(long childId) { // this.childId = childId; // } // // public long getChildId() { // return childId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getRuleId() { // return ruleId; // } // // public void setRuleId(long ruleId) { // this.ruleId = ruleId; // } // // /** // * Starts an intent to go to the LoginActivity. // * // * @param context Context // * @param universityData UniversityData used in intent data // */ // public void goToLogin(Context context, UniversityItem universityData) { // final Intent intent = new Intent(context, LoginActivity.class); // // intent.putExtra(LoginActivity.EXTRA_UNIVERSITY_NAME, universityData.getName()); // intent.putExtra(LoginActivity.EXTRA_UNIVERSITY_ID, universityData.getUniversityId()); // intent.putExtra(LoginActivity.EXTRA_RULE_ID, ruleId); // context.startActivity(intent); // } // // @Override // public int compareTo(RuleItem another) { // return name.compareToIgnoreCase(another.getName()); // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityFooter.java // public class UniversityFooter extends UniversityGroupItem { // private boolean visible; // // public UniversityFooter() { // visible = false; // } // // @Override // public long getGroupId() { // return -1; // } // // public boolean isVisible() { // return visible; // } // // public void setVisible(boolean visible) { // this.visible = visible; // } // // public void goToSubmitWish(Context context) { // String uri = "de.mygrades.view.activity://goto.fragment/postwish"; // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); // context.startActivity(intent); // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityGroupItem.java // public abstract class UniversityGroupItem { // // /** // * Get the group id. // * ExpandableItemAdapter requires stable IDs for each group item. // * // * @return group id // */ // public abstract long getGroupId(); // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityHeader.java // public class UniversityHeader extends UniversityGroupItem { // private boolean isLoading; // private ErrorEvent.ErrorType actErrorType; // // public UniversityHeader() { // isLoading = false; // actErrorType = null; // } // // public boolean isLoading() { // return isLoading; // } // // public void setIsLoading(boolean isLoading) { // this.isLoading = isLoading; // } // // public ErrorEvent.ErrorType getActErrorType() { // return actErrorType; // } // // public void setActErrorType(ErrorEvent.ErrorType actErrorType) { // this.actErrorType = actErrorType; // } // // @Override // public long getGroupId() { // return 0; // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityItem.java // public class UniversityItem extends UniversityGroupItem { // private long groupId; // private String name; // private long universityId; // private boolean isSectionHeader; // private String sectionTitle; // private boolean showRuleHint; // // private List<RuleItem> rules; // // public UniversityItem(long groupId) { // this.groupId = groupId; // rules = new ArrayList<>(); // showRuleHint = false; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // this.sectionTitle = String.valueOf(name.toUpperCase().charAt(0)); // } // // public long getUniversityId() { // return universityId; // } // // public void setUniversityId(long universityId) { // this.universityId = universityId; // } // // public boolean isSectionHeader() { // return isSectionHeader; // } // // public void setIsSectionHeader(boolean isSectionHeader) { // this.isSectionHeader = isSectionHeader; // } // // public List<RuleItem> getRules() { // return rules; // } // // public void addRuleData(RuleItem ruleItem) { // this.rules.add(ruleItem); // } // // public String getSectionTitle() { // return sectionTitle; // } // // @Override // public long getGroupId() { // return groupId; // } // // public boolean showRuleHint() { // return showRuleHint; // } // // public void setShowRuleHint(boolean showRuleHint) { // this.showRuleHint = showRuleHint; // } // } // Path: app/src/main/java/de/mygrades/view/adapter/dataprovider/UniversitiesDataProvider.java import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; import de.mygrades.view.adapter.model.RuleItem; import de.mygrades.view.adapter.model.UniversityFooter; import de.mygrades.view.adapter.model.UniversityGroupItem; import de.mygrades.view.adapter.model.UniversityHeader; import de.mygrades.view.adapter.model.UniversityItem; package de.mygrades.view.adapter.dataprovider; /** * UniversitiesDataProvider provides access to the underlying university items. */ public class UniversitiesDataProvider { private List<UniversityGroupItem> items;
private UniversityHeader header;
MyGrades/mygrades-app
app/src/main/java/de/mygrades/view/adapter/dataprovider/UniversitiesDataProvider.java
// Path: app/src/main/java/de/mygrades/view/adapter/model/RuleItem.java // public class RuleItem implements Comparable<RuleItem> { // private long childId; // private String name; // private long ruleId; // // public RuleItem(long childId) { // this.childId = childId; // } // // public long getChildId() { // return childId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getRuleId() { // return ruleId; // } // // public void setRuleId(long ruleId) { // this.ruleId = ruleId; // } // // /** // * Starts an intent to go to the LoginActivity. // * // * @param context Context // * @param universityData UniversityData used in intent data // */ // public void goToLogin(Context context, UniversityItem universityData) { // final Intent intent = new Intent(context, LoginActivity.class); // // intent.putExtra(LoginActivity.EXTRA_UNIVERSITY_NAME, universityData.getName()); // intent.putExtra(LoginActivity.EXTRA_UNIVERSITY_ID, universityData.getUniversityId()); // intent.putExtra(LoginActivity.EXTRA_RULE_ID, ruleId); // context.startActivity(intent); // } // // @Override // public int compareTo(RuleItem another) { // return name.compareToIgnoreCase(another.getName()); // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityFooter.java // public class UniversityFooter extends UniversityGroupItem { // private boolean visible; // // public UniversityFooter() { // visible = false; // } // // @Override // public long getGroupId() { // return -1; // } // // public boolean isVisible() { // return visible; // } // // public void setVisible(boolean visible) { // this.visible = visible; // } // // public void goToSubmitWish(Context context) { // String uri = "de.mygrades.view.activity://goto.fragment/postwish"; // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); // context.startActivity(intent); // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityGroupItem.java // public abstract class UniversityGroupItem { // // /** // * Get the group id. // * ExpandableItemAdapter requires stable IDs for each group item. // * // * @return group id // */ // public abstract long getGroupId(); // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityHeader.java // public class UniversityHeader extends UniversityGroupItem { // private boolean isLoading; // private ErrorEvent.ErrorType actErrorType; // // public UniversityHeader() { // isLoading = false; // actErrorType = null; // } // // public boolean isLoading() { // return isLoading; // } // // public void setIsLoading(boolean isLoading) { // this.isLoading = isLoading; // } // // public ErrorEvent.ErrorType getActErrorType() { // return actErrorType; // } // // public void setActErrorType(ErrorEvent.ErrorType actErrorType) { // this.actErrorType = actErrorType; // } // // @Override // public long getGroupId() { // return 0; // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityItem.java // public class UniversityItem extends UniversityGroupItem { // private long groupId; // private String name; // private long universityId; // private boolean isSectionHeader; // private String sectionTitle; // private boolean showRuleHint; // // private List<RuleItem> rules; // // public UniversityItem(long groupId) { // this.groupId = groupId; // rules = new ArrayList<>(); // showRuleHint = false; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // this.sectionTitle = String.valueOf(name.toUpperCase().charAt(0)); // } // // public long getUniversityId() { // return universityId; // } // // public void setUniversityId(long universityId) { // this.universityId = universityId; // } // // public boolean isSectionHeader() { // return isSectionHeader; // } // // public void setIsSectionHeader(boolean isSectionHeader) { // this.isSectionHeader = isSectionHeader; // } // // public List<RuleItem> getRules() { // return rules; // } // // public void addRuleData(RuleItem ruleItem) { // this.rules.add(ruleItem); // } // // public String getSectionTitle() { // return sectionTitle; // } // // @Override // public long getGroupId() { // return groupId; // } // // public boolean showRuleHint() { // return showRuleHint; // } // // public void setShowRuleHint(boolean showRuleHint) { // this.showRuleHint = showRuleHint; // } // }
import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; import de.mygrades.view.adapter.model.RuleItem; import de.mygrades.view.adapter.model.UniversityFooter; import de.mygrades.view.adapter.model.UniversityGroupItem; import de.mygrades.view.adapter.model.UniversityHeader; import de.mygrades.view.adapter.model.UniversityItem;
package de.mygrades.view.adapter.dataprovider; /** * UniversitiesDataProvider provides access to the underlying university items. */ public class UniversitiesDataProvider { private List<UniversityGroupItem> items; private UniversityHeader header;
// Path: app/src/main/java/de/mygrades/view/adapter/model/RuleItem.java // public class RuleItem implements Comparable<RuleItem> { // private long childId; // private String name; // private long ruleId; // // public RuleItem(long childId) { // this.childId = childId; // } // // public long getChildId() { // return childId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getRuleId() { // return ruleId; // } // // public void setRuleId(long ruleId) { // this.ruleId = ruleId; // } // // /** // * Starts an intent to go to the LoginActivity. // * // * @param context Context // * @param universityData UniversityData used in intent data // */ // public void goToLogin(Context context, UniversityItem universityData) { // final Intent intent = new Intent(context, LoginActivity.class); // // intent.putExtra(LoginActivity.EXTRA_UNIVERSITY_NAME, universityData.getName()); // intent.putExtra(LoginActivity.EXTRA_UNIVERSITY_ID, universityData.getUniversityId()); // intent.putExtra(LoginActivity.EXTRA_RULE_ID, ruleId); // context.startActivity(intent); // } // // @Override // public int compareTo(RuleItem another) { // return name.compareToIgnoreCase(another.getName()); // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityFooter.java // public class UniversityFooter extends UniversityGroupItem { // private boolean visible; // // public UniversityFooter() { // visible = false; // } // // @Override // public long getGroupId() { // return -1; // } // // public boolean isVisible() { // return visible; // } // // public void setVisible(boolean visible) { // this.visible = visible; // } // // public void goToSubmitWish(Context context) { // String uri = "de.mygrades.view.activity://goto.fragment/postwish"; // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); // context.startActivity(intent); // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityGroupItem.java // public abstract class UniversityGroupItem { // // /** // * Get the group id. // * ExpandableItemAdapter requires stable IDs for each group item. // * // * @return group id // */ // public abstract long getGroupId(); // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityHeader.java // public class UniversityHeader extends UniversityGroupItem { // private boolean isLoading; // private ErrorEvent.ErrorType actErrorType; // // public UniversityHeader() { // isLoading = false; // actErrorType = null; // } // // public boolean isLoading() { // return isLoading; // } // // public void setIsLoading(boolean isLoading) { // this.isLoading = isLoading; // } // // public ErrorEvent.ErrorType getActErrorType() { // return actErrorType; // } // // public void setActErrorType(ErrorEvent.ErrorType actErrorType) { // this.actErrorType = actErrorType; // } // // @Override // public long getGroupId() { // return 0; // } // } // // Path: app/src/main/java/de/mygrades/view/adapter/model/UniversityItem.java // public class UniversityItem extends UniversityGroupItem { // private long groupId; // private String name; // private long universityId; // private boolean isSectionHeader; // private String sectionTitle; // private boolean showRuleHint; // // private List<RuleItem> rules; // // public UniversityItem(long groupId) { // this.groupId = groupId; // rules = new ArrayList<>(); // showRuleHint = false; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // this.sectionTitle = String.valueOf(name.toUpperCase().charAt(0)); // } // // public long getUniversityId() { // return universityId; // } // // public void setUniversityId(long universityId) { // this.universityId = universityId; // } // // public boolean isSectionHeader() { // return isSectionHeader; // } // // public void setIsSectionHeader(boolean isSectionHeader) { // this.isSectionHeader = isSectionHeader; // } // // public List<RuleItem> getRules() { // return rules; // } // // public void addRuleData(RuleItem ruleItem) { // this.rules.add(ruleItem); // } // // public String getSectionTitle() { // return sectionTitle; // } // // @Override // public long getGroupId() { // return groupId; // } // // public boolean showRuleHint() { // return showRuleHint; // } // // public void setShowRuleHint(boolean showRuleHint) { // this.showRuleHint = showRuleHint; // } // } // Path: app/src/main/java/de/mygrades/view/adapter/dataprovider/UniversitiesDataProvider.java import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager; import java.util.ArrayList; import java.util.Collections; import java.util.List; import de.mygrades.view.adapter.model.RuleItem; import de.mygrades.view.adapter.model.UniversityFooter; import de.mygrades.view.adapter.model.UniversityGroupItem; import de.mygrades.view.adapter.model.UniversityHeader; import de.mygrades.view.adapter.model.UniversityItem; package de.mygrades.view.adapter.dataprovider; /** * UniversitiesDataProvider provides access to the underlying university items. */ public class UniversitiesDataProvider { private List<UniversityGroupItem> items; private UniversityHeader header;
private UniversityFooter footer;
MyGrades/mygrades-app
app/src/main/java/de/mygrades/view/UIHelper.java
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // }
import android.content.Context; import android.graphics.Color; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.TextView; import de.mygrades.R; import de.mygrades.main.events.ErrorEvent;
package de.mygrades.view; /** * Helper methods for UI. */ public class UIHelper { /** * Shows a Snackbar with a given text and action on the given view. * * @param view view where the snackbar should be shown * @param text text to show * @param action OnClickListener * @param actionText text for the OnClickListener */ public static void showSnackbar(View view, String text, View.OnClickListener action, String actionText) { if (view != null) { Snackbar snackbar = Snackbar .make(view, text, Snackbar.LENGTH_LONG) .setAction(actionText, action) .setActionTextColor(ContextCompat.getColor(view.getContext(), R.color.colorPrimary)); // change text color View snackbarView = snackbar.getView(); TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.WHITE); snackbar.show(); } } /** * Shows a Snackbar with a given text on the given view. * * @param view view where the snackbar should be shown * @param text text to show */ public static void showSnackbar(View view, String text) { showSnackbar(view, text, null, null); } /** * Evaluates the Error from errorEvent and displays specific message. * * @param view view where the error should be shown * @param errorEvent Error Event which holds the information about the concrete Error * @param tryAgainListener Button * @param goToFaqListener Button */
// Path: app/src/main/java/de/mygrades/main/events/ErrorEvent.java // public class ErrorEvent { // private ErrorType type; // private String msg; // // public ErrorEvent() { // } // // public ErrorEvent(ErrorType type, String msg) { // this.type = type; // this.msg = msg; // } // // public ErrorType getType() { // return type; // } // // public void setType(ErrorType type) { // this.type = type; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public enum ErrorType { // GENERAL, TIMEOUT, NO_NETWORK // } // } // Path: app/src/main/java/de/mygrades/view/UIHelper.java import android.content.Context; import android.graphics.Color; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.TextView; import de.mygrades.R; import de.mygrades.main.events.ErrorEvent; package de.mygrades.view; /** * Helper methods for UI. */ public class UIHelper { /** * Shows a Snackbar with a given text and action on the given view. * * @param view view where the snackbar should be shown * @param text text to show * @param action OnClickListener * @param actionText text for the OnClickListener */ public static void showSnackbar(View view, String text, View.OnClickListener action, String actionText) { if (view != null) { Snackbar snackbar = Snackbar .make(view, text, Snackbar.LENGTH_LONG) .setAction(actionText, action) .setActionTextColor(ContextCompat.getColor(view.getContext(), R.color.colorPrimary)); // change text color View snackbarView = snackbar.getView(); TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.WHITE); snackbar.show(); } } /** * Shows a Snackbar with a given text on the given view. * * @param view view where the snackbar should be shown * @param text text to show */ public static void showSnackbar(View view, String text) { showSnackbar(view, text, null, null); } /** * Evaluates the Error from errorEvent and displays specific message. * * @param view view where the error should be shown * @param errorEvent Error Event which holds the information about the concrete Error * @param tryAgainListener Button * @param goToFaqListener Button */
public static void displayErrorMessage(View view, ErrorEvent errorEvent, View.OnClickListener tryAgainListener, View.OnClickListener goToFaqListener) {
sksamuel/camelwatch
camelwatch-web/src/main/java/camelwatch/rest/ContextRestEndpoint.java
// Path: camelwatch-api/src/main/java/org/camelwatch/api/CamelBean.java // public class CamelBean { // // private final Map<String, Object> properties = Maps.newTreeMap(); // // private String name; // // private String description; // // public String getDescription() { // return description; // } // // public String getName() { // return name; // } // // public Map<String, Object> getProperties() { // return properties; // } // // public void setDescription(String description) { // this.description = description; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: camelwatch-api/src/main/java/org/camelwatch/api/CamelConnectionFactory.java // @Service // public class CamelConnectionFactory { // // @Value("${jmx.endpoint.url}") // private String url; // // @Value("${jmx.endpoint.username}") // private String username; // // @Value("${jmx.endpoint.password}") // private String password; // // private final Map<ObjectName, MBeanInfo> beanInfoCache = Maps.newHashMap(); // // public CamelConnection getConnection() throws MalformedObjectNameException, NullPointerException, IOException { // return new CamelJmxConnection(url, username, password, beanInfoCache); // } // // public CamelConnection getConnection(String url, String username, String password) throws MalformedObjectNameException, NullPointerException, IOException { // Map<ObjectName, MBeanInfo> beanInfoCache = Maps.newHashMap() ; // return new CamelJmxConnection(url, username, password, beanInfoCache); // } // }
import org.camelwatch.api.CamelBean; import org.camelwatch.api.CamelConnectionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List;
package camelwatch.rest; /** * @author Stephen K Samuel samspade79@gmail.com 2 Jul 2012 10:09:57 */ @Controller public class ContextRestEndpoint { @Autowired
// Path: camelwatch-api/src/main/java/org/camelwatch/api/CamelBean.java // public class CamelBean { // // private final Map<String, Object> properties = Maps.newTreeMap(); // // private String name; // // private String description; // // public String getDescription() { // return description; // } // // public String getName() { // return name; // } // // public Map<String, Object> getProperties() { // return properties; // } // // public void setDescription(String description) { // this.description = description; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: camelwatch-api/src/main/java/org/camelwatch/api/CamelConnectionFactory.java // @Service // public class CamelConnectionFactory { // // @Value("${jmx.endpoint.url}") // private String url; // // @Value("${jmx.endpoint.username}") // private String username; // // @Value("${jmx.endpoint.password}") // private String password; // // private final Map<ObjectName, MBeanInfo> beanInfoCache = Maps.newHashMap(); // // public CamelConnection getConnection() throws MalformedObjectNameException, NullPointerException, IOException { // return new CamelJmxConnection(url, username, password, beanInfoCache); // } // // public CamelConnection getConnection(String url, String username, String password) throws MalformedObjectNameException, NullPointerException, IOException { // Map<ObjectName, MBeanInfo> beanInfoCache = Maps.newHashMap() ; // return new CamelJmxConnection(url, username, password, beanInfoCache); // } // } // Path: camelwatch-web/src/main/java/camelwatch/rest/ContextRestEndpoint.java import org.camelwatch.api.CamelBean; import org.camelwatch.api.CamelConnectionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; package camelwatch.rest; /** * @author Stephen K Samuel samspade79@gmail.com 2 Jul 2012 10:09:57 */ @Controller public class ContextRestEndpoint { @Autowired
private CamelConnectionFactory connectionFactory;