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 |
|---|---|---|---|---|---|---|
Martin20150405/Pano360 | vrlib/src/main/java/com/martin/ads/vrlib/ui/Pano360ConfigBundle.java | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/MimeType.java
// public class MimeType {
// //media source
// public static final int ONLINE=0x0001;
// public static final int ASSETS=0x0002;
// public static final int RAW=0x0004;
// public static final int LOCAL_FILE=0x0008;
// public static final int BITMAP=0x0010;
//
// //media type
// public static final int PICTURE=0x0100;
// public static final int VIDEO=0x0200;
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.SparseArray;
import com.martin.ads.vrlib.constant.MimeType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List; | }
public boolean isImageModeEnabled() {
return imageModeEnabled;
}
public boolean isPlaneModeEnabled() {
return planeModeEnabled;
}
public Pano360ConfigBundle setPlaneModeEnabled(boolean planeModeEnabled) {
this.planeModeEnabled = planeModeEnabled;
return this;
}
public boolean isWindowModeEnabled() {
return windowModeEnabled;
}
public boolean isRemoveHotspot() {
return removeHotspot;
}
public Pano360ConfigBundle setRemoveHotspot(boolean removeHotspot) {
this.removeHotspot = removeHotspot;
return this;
}
public Pano360ConfigBundle setMimeType(int mimeType) {
this.mimeType = mimeType; | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/MimeType.java
// public class MimeType {
// //media source
// public static final int ONLINE=0x0001;
// public static final int ASSETS=0x0002;
// public static final int RAW=0x0004;
// public static final int LOCAL_FILE=0x0008;
// public static final int BITMAP=0x0010;
//
// //media type
// public static final int PICTURE=0x0100;
// public static final int VIDEO=0x0200;
// }
// Path: vrlib/src/main/java/com/martin/ads/vrlib/ui/Pano360ConfigBundle.java
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.SparseArray;
import com.martin.ads.vrlib.constant.MimeType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
}
public boolean isImageModeEnabled() {
return imageModeEnabled;
}
public boolean isPlaneModeEnabled() {
return planeModeEnabled;
}
public Pano360ConfigBundle setPlaneModeEnabled(boolean planeModeEnabled) {
this.planeModeEnabled = planeModeEnabled;
return this;
}
public boolean isWindowModeEnabled() {
return windowModeEnabled;
}
public boolean isRemoveHotspot() {
return removeHotspot;
}
public Pano360ConfigBundle setRemoveHotspot(boolean removeHotspot) {
this.removeHotspot = removeHotspot;
return this;
}
public Pano360ConfigBundle setMimeType(int mimeType) {
this.mimeType = mimeType; | imageModeEnabled=(mimeType & MimeType.PICTURE)!=0; |
Martin20150405/Pano360 | vrlib/src/main/java/com/martin/ads/vrlib/utils/PlaneTextureRotationUtils.java | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/Rotation.java
// public enum Rotation {
// NORMAL, ROTATION_90, ROTATION_180, ROTATION_270
// }
| import com.martin.ads.vrlib.constant.Rotation; | /*
* Copyright (C) 2012 CyberAgent
*
* 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.martin.ads.vrlib.utils;
public class PlaneTextureRotationUtils {
public static final float TEXTURE_NO_ROTATION[] = {
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 1.0f,
1.0f, 0.0f
};
public static final float TEXTURE_ROTATED_90[] = {
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f
};
public static final float TEXTURE_ROTATED_180[] = {
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f,
0.0f, 1.0f
};
public static final float TEXTURE_ROTATED_270[] = {
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f
};
private PlaneTextureRotationUtils() {
}
| // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/Rotation.java
// public enum Rotation {
// NORMAL, ROTATION_90, ROTATION_180, ROTATION_270
// }
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/PlaneTextureRotationUtils.java
import com.martin.ads.vrlib.constant.Rotation;
/*
* Copyright (C) 2012 CyberAgent
*
* 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.martin.ads.vrlib.utils;
public class PlaneTextureRotationUtils {
public static final float TEXTURE_NO_ROTATION[] = {
0.0f, 1.0f,
0.0f, 0.0f,
1.0f, 1.0f,
1.0f, 0.0f
};
public static final float TEXTURE_ROTATED_90[] = {
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f
};
public static final float TEXTURE_ROTATED_180[] = {
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f,
0.0f, 1.0f
};
public static final float TEXTURE_ROTATED_270[] = {
0.0f, 1.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 0.0f
};
private PlaneTextureRotationUtils() {
}
| public static float[] getRotation(final Rotation rotation, final boolean flipHorizontal, |
Martin20150405/Pano360 | vrlib/src/main/java/com/martin/ads/vrlib/filters/advanced/mx/MxLomoFilter.java | // Path: vrlib/src/main/java/com/martin/ads/vrlib/filters/base/SimpleFragmentShaderFilter.java
// public class SimpleFragmentShaderFilter extends AbsFilter {
//
// protected GLSimpleProgram glSimpleProgram;
// protected Plane plane;
//
// public SimpleFragmentShaderFilter(Context context,
// final String fragmentShaderPath) {
// glSimpleProgram=new GLSimpleProgram(context, "filter/vsh/simple.glsl",fragmentShaderPath);
// plane =new Plane(true);
// }
//
// @Override
// public void init() {
// glSimpleProgram.create();
// }
//
// @Override
// public void onPreDrawElements() {
// super.onPreDrawElements();
// glSimpleProgram.use();
// plane.uploadTexCoordinateBuffer(glSimpleProgram.getTextureCoordinateHandle());
// plane.uploadVerticesBuffer(glSimpleProgram.getPositionHandle());
// }
//
// @Override
// public void destroy() {
// glSimpleProgram.onDestroy();
// }
//
// @Override
// public void onDrawFrame(int textureId) {
// onPreDrawElements();
// TextureUtils.bindTexture2D(textureId, GLES20.GL_TEXTURE0,glSimpleProgram.getTextureSamplerHandle(),0);
// GLES20.glViewport(0,0,surfaceWidth,surfaceHeight);
// plane.draw();
// }
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/TextureUtils.java
// public class TextureUtils {
// private static final String TAG = "TextureUtils";
//
// public static void bindTexture2D(int textureId,int activeTextureID,int handle,int idx){
// if (textureId != GLEtc.NO_TEXTURE) {
// GLES20.glActiveTexture(activeTextureID);
// GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
// GLES20.glUniform1i(handle, idx);
// }
// }
//
// public static void bindTextureOES(int textureId,int activeTextureID,int handle,int idx){
// if (textureId != GLEtc.NO_TEXTURE) {
// GLES20.glActiveTexture(activeTextureID);
// GLES20.glBindTexture(GLEtc.GL_TEXTURE_EXTERNAL_OES, textureId);
// GLES20.glUniform1i(handle, idx);
// }
// }
//
// public static int loadTextureFromResources(Context context, int resourceId,int imageSize[]){
// return getTextureFromBitmap(
// BitmapUtils.loadBitmapFromRaw(context,resourceId),
// imageSize);
// }
//
// public static int loadTextureFromAssets(Context context, String filePath,int imageSize[]){
// return getTextureFromBitmap(
// BitmapUtils.loadBitmapFromAssets(context,filePath),
// imageSize);
// }
//
// //bitmap will be recycled after calling this method
// public static int getTextureFromBitmap(Bitmap bitmap,int imageSize[]){
// final int[] textureObjectIds=new int[1];
// GLES20.glGenTextures(1,textureObjectIds,0);
// if (textureObjectIds[0]==0){
// Log.d(TAG,"Failed at glGenTextures");
// return 0;
// }
//
// if (bitmap==null){
// Log.d(TAG,"Failed at decoding bitmap");
// GLES20.glDeleteTextures(1,textureObjectIds,0);
// return 0;
// }
//
// if(imageSize!=null && imageSize.length>=2){
// imageSize[0]=bitmap.getWidth();
// imageSize[1]=bitmap.getHeight();
// }
//
// GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,textureObjectIds[0]);
//
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
// GLUtils.texImage2D(GLES20.GL_TEXTURE_2D,0,bitmap,0);
// bitmap.recycle();
//
// GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,0);
// return textureObjectIds[0];
// }
// }
| import android.content.Context;
import android.opengl.GLES20;
import com.martin.ads.vrlib.filters.base.SimpleFragmentShaderFilter;
import com.martin.ads.vrlib.utils.TextureUtils; | package com.martin.ads.vrlib.filters.advanced.mx;
/**
* Created by Ads on 2017/2/1.
* MxLomoFilter (LOMO)
*/
public class MxLomoFilter extends SimpleFragmentShaderFilter {
public MxLomoFilter(Context context) {
super(context, "filter/fsh/mx_lomo.glsl");
}
@Override
public void onDrawFrame(int textureId) {
onPreDrawElements();
setUniform1f(glSimpleProgram.getProgramId(),"rOffset",1.0f);
setUniform1f(glSimpleProgram.getProgramId(),"gOffset",1.0f);
setUniform1f(glSimpleProgram.getProgramId(),"bOffset",1.0f); | // Path: vrlib/src/main/java/com/martin/ads/vrlib/filters/base/SimpleFragmentShaderFilter.java
// public class SimpleFragmentShaderFilter extends AbsFilter {
//
// protected GLSimpleProgram glSimpleProgram;
// protected Plane plane;
//
// public SimpleFragmentShaderFilter(Context context,
// final String fragmentShaderPath) {
// glSimpleProgram=new GLSimpleProgram(context, "filter/vsh/simple.glsl",fragmentShaderPath);
// plane =new Plane(true);
// }
//
// @Override
// public void init() {
// glSimpleProgram.create();
// }
//
// @Override
// public void onPreDrawElements() {
// super.onPreDrawElements();
// glSimpleProgram.use();
// plane.uploadTexCoordinateBuffer(glSimpleProgram.getTextureCoordinateHandle());
// plane.uploadVerticesBuffer(glSimpleProgram.getPositionHandle());
// }
//
// @Override
// public void destroy() {
// glSimpleProgram.onDestroy();
// }
//
// @Override
// public void onDrawFrame(int textureId) {
// onPreDrawElements();
// TextureUtils.bindTexture2D(textureId, GLES20.GL_TEXTURE0,glSimpleProgram.getTextureSamplerHandle(),0);
// GLES20.glViewport(0,0,surfaceWidth,surfaceHeight);
// plane.draw();
// }
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/TextureUtils.java
// public class TextureUtils {
// private static final String TAG = "TextureUtils";
//
// public static void bindTexture2D(int textureId,int activeTextureID,int handle,int idx){
// if (textureId != GLEtc.NO_TEXTURE) {
// GLES20.glActiveTexture(activeTextureID);
// GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId);
// GLES20.glUniform1i(handle, idx);
// }
// }
//
// public static void bindTextureOES(int textureId,int activeTextureID,int handle,int idx){
// if (textureId != GLEtc.NO_TEXTURE) {
// GLES20.glActiveTexture(activeTextureID);
// GLES20.glBindTexture(GLEtc.GL_TEXTURE_EXTERNAL_OES, textureId);
// GLES20.glUniform1i(handle, idx);
// }
// }
//
// public static int loadTextureFromResources(Context context, int resourceId,int imageSize[]){
// return getTextureFromBitmap(
// BitmapUtils.loadBitmapFromRaw(context,resourceId),
// imageSize);
// }
//
// public static int loadTextureFromAssets(Context context, String filePath,int imageSize[]){
// return getTextureFromBitmap(
// BitmapUtils.loadBitmapFromAssets(context,filePath),
// imageSize);
// }
//
// //bitmap will be recycled after calling this method
// public static int getTextureFromBitmap(Bitmap bitmap,int imageSize[]){
// final int[] textureObjectIds=new int[1];
// GLES20.glGenTextures(1,textureObjectIds,0);
// if (textureObjectIds[0]==0){
// Log.d(TAG,"Failed at glGenTextures");
// return 0;
// }
//
// if (bitmap==null){
// Log.d(TAG,"Failed at decoding bitmap");
// GLES20.glDeleteTextures(1,textureObjectIds,0);
// return 0;
// }
//
// if(imageSize!=null && imageSize.length>=2){
// imageSize[0]=bitmap.getWidth();
// imageSize[1]=bitmap.getHeight();
// }
//
// GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,textureObjectIds[0]);
//
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
// GLUtils.texImage2D(GLES20.GL_TEXTURE_2D,0,bitmap,0);
// bitmap.recycle();
//
// GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,0);
// return textureObjectIds[0];
// }
// }
// Path: vrlib/src/main/java/com/martin/ads/vrlib/filters/advanced/mx/MxLomoFilter.java
import android.content.Context;
import android.opengl.GLES20;
import com.martin.ads.vrlib.filters.base.SimpleFragmentShaderFilter;
import com.martin.ads.vrlib.utils.TextureUtils;
package com.martin.ads.vrlib.filters.advanced.mx;
/**
* Created by Ads on 2017/2/1.
* MxLomoFilter (LOMO)
*/
public class MxLomoFilter extends SimpleFragmentShaderFilter {
public MxLomoFilter(Context context) {
super(context, "filter/fsh/mx_lomo.glsl");
}
@Override
public void onDrawFrame(int textureId) {
onPreDrawElements();
setUniform1f(glSimpleProgram.getProgramId(),"rOffset",1.0f);
setUniform1f(glSimpleProgram.getProgramId(),"gOffset",1.0f);
setUniform1f(glSimpleProgram.getProgramId(),"bOffset",1.0f); | TextureUtils.bindTexture2D(textureId, GLES20.GL_TEXTURE0,glSimpleProgram.getTextureSamplerHandle(),0); |
Martin20150405/Pano360 | vrlib/src/main/java/com/martin/ads/vrlib/utils/StatusHelper.java | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/PanoMode.java
// public enum PanoMode
// {
// MOTION,TOUCH,SINGLE_SCREEN,DUAL_SCREEN
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/PanoStatus.java
// public enum PanoStatus
// {
// IDLE, PREPARED,BUFFERING, PLAYING, PAUSED_BY_USER, PAUSED, STOPPED, COMPLETE, ERROR
// }
| import android.content.Context;
import com.martin.ads.vrlib.constant.PanoMode;
import com.martin.ads.vrlib.constant.PanoStatus; | package com.martin.ads.vrlib.utils;
/**
* Project: Pano360
* Package: com.martin.ads.pano360.utils
* Created by Ads on 2016/5/2.
*/
public class StatusHelper {
private PanoStatus panoStatus; | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/PanoMode.java
// public enum PanoMode
// {
// MOTION,TOUCH,SINGLE_SCREEN,DUAL_SCREEN
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/PanoStatus.java
// public enum PanoStatus
// {
// IDLE, PREPARED,BUFFERING, PLAYING, PAUSED_BY_USER, PAUSED, STOPPED, COMPLETE, ERROR
// }
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/StatusHelper.java
import android.content.Context;
import com.martin.ads.vrlib.constant.PanoMode;
import com.martin.ads.vrlib.constant.PanoStatus;
package com.martin.ads.vrlib.utils;
/**
* Project: Pano360
* Package: com.martin.ads.pano360.utils
* Created by Ads on 2016/5/2.
*/
public class StatusHelper {
private PanoStatus panoStatus; | private PanoMode panoDisPlayMode; |
Martin20150405/Pano360 | vrlib/src/main/java/com/martin/ads/vrlib/SensorEventHandler.java | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/Constants.java
// public class Constants {
// public static final int FLOAT_SIZE_BYTES = 4;
// public static final int SHORT_SIZE_BYTES = 2;
// //Sensor
// public static final int SENSOR_ACC= Sensor.TYPE_ACCELEROMETER;
// public static final int SENSOR_MAG=Sensor.TYPE_MAGNETIC_FIELD;
// public static final int SENSOR_ROT=Sensor.TYPE_ROTATION_VECTOR;
//
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/SensorUtils.java
// public class SensorUtils {
// private static float[] mTmp = new float[16];
// private static float[] oTmp = new float[16];
//
// //by default, the coordinate is remapped to landscape
// public static void sensorRotationVectorToMatrix(SensorEvent event, int deviceRotation, float[] output) {
// float[] values = event.values;
// switch (deviceRotation){
// case Surface.ROTATION_0:
// SensorManager.getRotationMatrixFromVector(output, values);
// break;
// default:
// SensorManager.getRotationMatrixFromVector(mTmp, values);
// SensorManager.remapCoordinateSystem(mTmp, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, output);
// }
// Matrix.rotateM(output, 0, 90.0F, 1.0F, 0.0F, 0.0F);
// }
//
// public static void getOrientation(SensorEvent event,float[] output){
// //sensorRotationVectorToMatrix(event,oTmp);
// SensorManager.getRotationMatrixFromVector(oTmp, event.values);
// SensorManager.getOrientation(oTmp,output);
// }
//
// public static void getOrientationFromRotationMatrix(float[] rotationMatrix,float[] output){
// SensorManager.getOrientation(rotationMatrix,output);
// }
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/StatusHelper.java
// public class StatusHelper {
// private PanoStatus panoStatus;
// private PanoMode panoDisPlayMode;
// private PanoMode panoInteractiveMode;
// private Context context;
// public StatusHelper(Context context) {
// this.context = context;
// }
//
// public Context getContext() {
// return context;
// }
//
// public PanoStatus getPanoStatus() {
// return panoStatus;
// }
//
// public void setPanoStatus(PanoStatus panoStatus) {
// this.panoStatus = panoStatus;
// }
//
// public PanoMode getPanoDisPlayMode() {
// return panoDisPlayMode;
// }
//
// public void setPanoDisPlayMode(PanoMode panoDisPlayMode) {
// this.panoDisPlayMode = panoDisPlayMode;
// }
//
// public PanoMode getPanoInteractiveMode() {
// return panoInteractiveMode;
// }
//
// public void setPanoInteractiveMode(PanoMode panoInteractiveMode) {
// this.panoInteractiveMode = panoInteractiveMode;
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Surface;
import com.martin.ads.vrlib.constant.Constants;
import com.martin.ads.vrlib.utils.SensorUtils;
import com.martin.ads.vrlib.utils.StatusHelper; | package com.martin.ads.vrlib;
/**
* Project: Pano360
* Package: com.martin.ads.pano360
* Created by Ads on 2016/5/2.
*/
public class SensorEventHandler implements SensorEventListener {
public static String TAG = "SensorEventHandler";
private float[] rotationMatrix = new float[16];
//private float[] orientationData=new float[3];
| // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/Constants.java
// public class Constants {
// public static final int FLOAT_SIZE_BYTES = 4;
// public static final int SHORT_SIZE_BYTES = 2;
// //Sensor
// public static final int SENSOR_ACC= Sensor.TYPE_ACCELEROMETER;
// public static final int SENSOR_MAG=Sensor.TYPE_MAGNETIC_FIELD;
// public static final int SENSOR_ROT=Sensor.TYPE_ROTATION_VECTOR;
//
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/SensorUtils.java
// public class SensorUtils {
// private static float[] mTmp = new float[16];
// private static float[] oTmp = new float[16];
//
// //by default, the coordinate is remapped to landscape
// public static void sensorRotationVectorToMatrix(SensorEvent event, int deviceRotation, float[] output) {
// float[] values = event.values;
// switch (deviceRotation){
// case Surface.ROTATION_0:
// SensorManager.getRotationMatrixFromVector(output, values);
// break;
// default:
// SensorManager.getRotationMatrixFromVector(mTmp, values);
// SensorManager.remapCoordinateSystem(mTmp, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, output);
// }
// Matrix.rotateM(output, 0, 90.0F, 1.0F, 0.0F, 0.0F);
// }
//
// public static void getOrientation(SensorEvent event,float[] output){
// //sensorRotationVectorToMatrix(event,oTmp);
// SensorManager.getRotationMatrixFromVector(oTmp, event.values);
// SensorManager.getOrientation(oTmp,output);
// }
//
// public static void getOrientationFromRotationMatrix(float[] rotationMatrix,float[] output){
// SensorManager.getOrientation(rotationMatrix,output);
// }
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/StatusHelper.java
// public class StatusHelper {
// private PanoStatus panoStatus;
// private PanoMode panoDisPlayMode;
// private PanoMode panoInteractiveMode;
// private Context context;
// public StatusHelper(Context context) {
// this.context = context;
// }
//
// public Context getContext() {
// return context;
// }
//
// public PanoStatus getPanoStatus() {
// return panoStatus;
// }
//
// public void setPanoStatus(PanoStatus panoStatus) {
// this.panoStatus = panoStatus;
// }
//
// public PanoMode getPanoDisPlayMode() {
// return panoDisPlayMode;
// }
//
// public void setPanoDisPlayMode(PanoMode panoDisPlayMode) {
// this.panoDisPlayMode = panoDisPlayMode;
// }
//
// public PanoMode getPanoInteractiveMode() {
// return panoInteractiveMode;
// }
//
// public void setPanoInteractiveMode(PanoMode panoInteractiveMode) {
// this.panoInteractiveMode = panoInteractiveMode;
// }
// }
// Path: vrlib/src/main/java/com/martin/ads/vrlib/SensorEventHandler.java
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Surface;
import com.martin.ads.vrlib.constant.Constants;
import com.martin.ads.vrlib.utils.SensorUtils;
import com.martin.ads.vrlib.utils.StatusHelper;
package com.martin.ads.vrlib;
/**
* Project: Pano360
* Package: com.martin.ads.pano360
* Created by Ads on 2016/5/2.
*/
public class SensorEventHandler implements SensorEventListener {
public static String TAG = "SensorEventHandler";
private float[] rotationMatrix = new float[16];
//private float[] orientationData=new float[3];
| private StatusHelper statusHelper; |
Martin20150405/Pano360 | vrlib/src/main/java/com/martin/ads/vrlib/SensorEventHandler.java | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/Constants.java
// public class Constants {
// public static final int FLOAT_SIZE_BYTES = 4;
// public static final int SHORT_SIZE_BYTES = 2;
// //Sensor
// public static final int SENSOR_ACC= Sensor.TYPE_ACCELEROMETER;
// public static final int SENSOR_MAG=Sensor.TYPE_MAGNETIC_FIELD;
// public static final int SENSOR_ROT=Sensor.TYPE_ROTATION_VECTOR;
//
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/SensorUtils.java
// public class SensorUtils {
// private static float[] mTmp = new float[16];
// private static float[] oTmp = new float[16];
//
// //by default, the coordinate is remapped to landscape
// public static void sensorRotationVectorToMatrix(SensorEvent event, int deviceRotation, float[] output) {
// float[] values = event.values;
// switch (deviceRotation){
// case Surface.ROTATION_0:
// SensorManager.getRotationMatrixFromVector(output, values);
// break;
// default:
// SensorManager.getRotationMatrixFromVector(mTmp, values);
// SensorManager.remapCoordinateSystem(mTmp, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, output);
// }
// Matrix.rotateM(output, 0, 90.0F, 1.0F, 0.0F, 0.0F);
// }
//
// public static void getOrientation(SensorEvent event,float[] output){
// //sensorRotationVectorToMatrix(event,oTmp);
// SensorManager.getRotationMatrixFromVector(oTmp, event.values);
// SensorManager.getOrientation(oTmp,output);
// }
//
// public static void getOrientationFromRotationMatrix(float[] rotationMatrix,float[] output){
// SensorManager.getOrientation(rotationMatrix,output);
// }
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/StatusHelper.java
// public class StatusHelper {
// private PanoStatus panoStatus;
// private PanoMode panoDisPlayMode;
// private PanoMode panoInteractiveMode;
// private Context context;
// public StatusHelper(Context context) {
// this.context = context;
// }
//
// public Context getContext() {
// return context;
// }
//
// public PanoStatus getPanoStatus() {
// return panoStatus;
// }
//
// public void setPanoStatus(PanoStatus panoStatus) {
// this.panoStatus = panoStatus;
// }
//
// public PanoMode getPanoDisPlayMode() {
// return panoDisPlayMode;
// }
//
// public void setPanoDisPlayMode(PanoMode panoDisPlayMode) {
// this.panoDisPlayMode = panoDisPlayMode;
// }
//
// public PanoMode getPanoInteractiveMode() {
// return panoInteractiveMode;
// }
//
// public void setPanoInteractiveMode(PanoMode panoInteractiveMode) {
// this.panoInteractiveMode = panoInteractiveMode;
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Surface;
import com.martin.ads.vrlib.constant.Constants;
import com.martin.ads.vrlib.utils.SensorUtils;
import com.martin.ads.vrlib.utils.StatusHelper; | package com.martin.ads.vrlib;
/**
* Project: Pano360
* Package: com.martin.ads.pano360
* Created by Ads on 2016/5/2.
*/
public class SensorEventHandler implements SensorEventListener {
public static String TAG = "SensorEventHandler";
private float[] rotationMatrix = new float[16];
//private float[] orientationData=new float[3];
private StatusHelper statusHelper;
private SensorHandlerCallback sensorHandlerCallback;
private boolean sensorRegistered;
private SensorManager sensorManager;
private int mDeviceRotation;
public void init(){
sensorRegistered=false;
sensorManager = (SensorManager) statusHelper.getContext()
.getSystemService(Context.SENSOR_SERVICE); | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/Constants.java
// public class Constants {
// public static final int FLOAT_SIZE_BYTES = 4;
// public static final int SHORT_SIZE_BYTES = 2;
// //Sensor
// public static final int SENSOR_ACC= Sensor.TYPE_ACCELEROMETER;
// public static final int SENSOR_MAG=Sensor.TYPE_MAGNETIC_FIELD;
// public static final int SENSOR_ROT=Sensor.TYPE_ROTATION_VECTOR;
//
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/SensorUtils.java
// public class SensorUtils {
// private static float[] mTmp = new float[16];
// private static float[] oTmp = new float[16];
//
// //by default, the coordinate is remapped to landscape
// public static void sensorRotationVectorToMatrix(SensorEvent event, int deviceRotation, float[] output) {
// float[] values = event.values;
// switch (deviceRotation){
// case Surface.ROTATION_0:
// SensorManager.getRotationMatrixFromVector(output, values);
// break;
// default:
// SensorManager.getRotationMatrixFromVector(mTmp, values);
// SensorManager.remapCoordinateSystem(mTmp, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, output);
// }
// Matrix.rotateM(output, 0, 90.0F, 1.0F, 0.0F, 0.0F);
// }
//
// public static void getOrientation(SensorEvent event,float[] output){
// //sensorRotationVectorToMatrix(event,oTmp);
// SensorManager.getRotationMatrixFromVector(oTmp, event.values);
// SensorManager.getOrientation(oTmp,output);
// }
//
// public static void getOrientationFromRotationMatrix(float[] rotationMatrix,float[] output){
// SensorManager.getOrientation(rotationMatrix,output);
// }
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/StatusHelper.java
// public class StatusHelper {
// private PanoStatus panoStatus;
// private PanoMode panoDisPlayMode;
// private PanoMode panoInteractiveMode;
// private Context context;
// public StatusHelper(Context context) {
// this.context = context;
// }
//
// public Context getContext() {
// return context;
// }
//
// public PanoStatus getPanoStatus() {
// return panoStatus;
// }
//
// public void setPanoStatus(PanoStatus panoStatus) {
// this.panoStatus = panoStatus;
// }
//
// public PanoMode getPanoDisPlayMode() {
// return panoDisPlayMode;
// }
//
// public void setPanoDisPlayMode(PanoMode panoDisPlayMode) {
// this.panoDisPlayMode = panoDisPlayMode;
// }
//
// public PanoMode getPanoInteractiveMode() {
// return panoInteractiveMode;
// }
//
// public void setPanoInteractiveMode(PanoMode panoInteractiveMode) {
// this.panoInteractiveMode = panoInteractiveMode;
// }
// }
// Path: vrlib/src/main/java/com/martin/ads/vrlib/SensorEventHandler.java
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Surface;
import com.martin.ads.vrlib.constant.Constants;
import com.martin.ads.vrlib.utils.SensorUtils;
import com.martin.ads.vrlib.utils.StatusHelper;
package com.martin.ads.vrlib;
/**
* Project: Pano360
* Package: com.martin.ads.pano360
* Created by Ads on 2016/5/2.
*/
public class SensorEventHandler implements SensorEventListener {
public static String TAG = "SensorEventHandler";
private float[] rotationMatrix = new float[16];
//private float[] orientationData=new float[3];
private StatusHelper statusHelper;
private SensorHandlerCallback sensorHandlerCallback;
private boolean sensorRegistered;
private SensorManager sensorManager;
private int mDeviceRotation;
public void init(){
sensorRegistered=false;
sensorManager = (SensorManager) statusHelper.getContext()
.getSystemService(Context.SENSOR_SERVICE); | Sensor sensorRot = sensorManager.getDefaultSensor(Constants.SENSOR_ROT); |
Martin20150405/Pano360 | vrlib/src/main/java/com/martin/ads/vrlib/SensorEventHandler.java | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/Constants.java
// public class Constants {
// public static final int FLOAT_SIZE_BYTES = 4;
// public static final int SHORT_SIZE_BYTES = 2;
// //Sensor
// public static final int SENSOR_ACC= Sensor.TYPE_ACCELEROMETER;
// public static final int SENSOR_MAG=Sensor.TYPE_MAGNETIC_FIELD;
// public static final int SENSOR_ROT=Sensor.TYPE_ROTATION_VECTOR;
//
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/SensorUtils.java
// public class SensorUtils {
// private static float[] mTmp = new float[16];
// private static float[] oTmp = new float[16];
//
// //by default, the coordinate is remapped to landscape
// public static void sensorRotationVectorToMatrix(SensorEvent event, int deviceRotation, float[] output) {
// float[] values = event.values;
// switch (deviceRotation){
// case Surface.ROTATION_0:
// SensorManager.getRotationMatrixFromVector(output, values);
// break;
// default:
// SensorManager.getRotationMatrixFromVector(mTmp, values);
// SensorManager.remapCoordinateSystem(mTmp, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, output);
// }
// Matrix.rotateM(output, 0, 90.0F, 1.0F, 0.0F, 0.0F);
// }
//
// public static void getOrientation(SensorEvent event,float[] output){
// //sensorRotationVectorToMatrix(event,oTmp);
// SensorManager.getRotationMatrixFromVector(oTmp, event.values);
// SensorManager.getOrientation(oTmp,output);
// }
//
// public static void getOrientationFromRotationMatrix(float[] rotationMatrix,float[] output){
// SensorManager.getOrientation(rotationMatrix,output);
// }
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/StatusHelper.java
// public class StatusHelper {
// private PanoStatus panoStatus;
// private PanoMode panoDisPlayMode;
// private PanoMode panoInteractiveMode;
// private Context context;
// public StatusHelper(Context context) {
// this.context = context;
// }
//
// public Context getContext() {
// return context;
// }
//
// public PanoStatus getPanoStatus() {
// return panoStatus;
// }
//
// public void setPanoStatus(PanoStatus panoStatus) {
// this.panoStatus = panoStatus;
// }
//
// public PanoMode getPanoDisPlayMode() {
// return panoDisPlayMode;
// }
//
// public void setPanoDisPlayMode(PanoMode panoDisPlayMode) {
// this.panoDisPlayMode = panoDisPlayMode;
// }
//
// public PanoMode getPanoInteractiveMode() {
// return panoInteractiveMode;
// }
//
// public void setPanoInteractiveMode(PanoMode panoInteractiveMode) {
// this.panoInteractiveMode = panoInteractiveMode;
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Surface;
import com.martin.ads.vrlib.constant.Constants;
import com.martin.ads.vrlib.utils.SensorUtils;
import com.martin.ads.vrlib.utils.StatusHelper; | package com.martin.ads.vrlib;
/**
* Project: Pano360
* Package: com.martin.ads.pano360
* Created by Ads on 2016/5/2.
*/
public class SensorEventHandler implements SensorEventListener {
public static String TAG = "SensorEventHandler";
private float[] rotationMatrix = new float[16];
//private float[] orientationData=new float[3];
private StatusHelper statusHelper;
private SensorHandlerCallback sensorHandlerCallback;
private boolean sensorRegistered;
private SensorManager sensorManager;
private int mDeviceRotation;
public void init(){
sensorRegistered=false;
sensorManager = (SensorManager) statusHelper.getContext()
.getSystemService(Context.SENSOR_SERVICE);
Sensor sensorRot = sensorManager.getDefaultSensor(Constants.SENSOR_ROT);
if (sensorRot==null) return;
sensorManager.registerListener(this, sensorRot, SensorManager.SENSOR_DELAY_GAME);
sensorRegistered=true;
}
public void releaseResources(){
if (!sensorRegistered || sensorManager==null) return;
sensorManager.unregisterListener(this);
sensorRegistered = false;
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.accuracy != 0){
int type = event.sensor.getType();
switch (type){
case Constants.SENSOR_ROT:
//FIXME
mDeviceRotation= ((Activity)statusHelper.getContext()).getWindowManager().getDefaultDisplay().getRotation(); | // Path: vrlib/src/main/java/com/martin/ads/vrlib/constant/Constants.java
// public class Constants {
// public static final int FLOAT_SIZE_BYTES = 4;
// public static final int SHORT_SIZE_BYTES = 2;
// //Sensor
// public static final int SENSOR_ACC= Sensor.TYPE_ACCELEROMETER;
// public static final int SENSOR_MAG=Sensor.TYPE_MAGNETIC_FIELD;
// public static final int SENSOR_ROT=Sensor.TYPE_ROTATION_VECTOR;
//
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/SensorUtils.java
// public class SensorUtils {
// private static float[] mTmp = new float[16];
// private static float[] oTmp = new float[16];
//
// //by default, the coordinate is remapped to landscape
// public static void sensorRotationVectorToMatrix(SensorEvent event, int deviceRotation, float[] output) {
// float[] values = event.values;
// switch (deviceRotation){
// case Surface.ROTATION_0:
// SensorManager.getRotationMatrixFromVector(output, values);
// break;
// default:
// SensorManager.getRotationMatrixFromVector(mTmp, values);
// SensorManager.remapCoordinateSystem(mTmp, SensorManager.AXIS_Y, SensorManager.AXIS_MINUS_X, output);
// }
// Matrix.rotateM(output, 0, 90.0F, 1.0F, 0.0F, 0.0F);
// }
//
// public static void getOrientation(SensorEvent event,float[] output){
// //sensorRotationVectorToMatrix(event,oTmp);
// SensorManager.getRotationMatrixFromVector(oTmp, event.values);
// SensorManager.getOrientation(oTmp,output);
// }
//
// public static void getOrientationFromRotationMatrix(float[] rotationMatrix,float[] output){
// SensorManager.getOrientation(rotationMatrix,output);
// }
// }
//
// Path: vrlib/src/main/java/com/martin/ads/vrlib/utils/StatusHelper.java
// public class StatusHelper {
// private PanoStatus panoStatus;
// private PanoMode panoDisPlayMode;
// private PanoMode panoInteractiveMode;
// private Context context;
// public StatusHelper(Context context) {
// this.context = context;
// }
//
// public Context getContext() {
// return context;
// }
//
// public PanoStatus getPanoStatus() {
// return panoStatus;
// }
//
// public void setPanoStatus(PanoStatus panoStatus) {
// this.panoStatus = panoStatus;
// }
//
// public PanoMode getPanoDisPlayMode() {
// return panoDisPlayMode;
// }
//
// public void setPanoDisPlayMode(PanoMode panoDisPlayMode) {
// this.panoDisPlayMode = panoDisPlayMode;
// }
//
// public PanoMode getPanoInteractiveMode() {
// return panoInteractiveMode;
// }
//
// public void setPanoInteractiveMode(PanoMode panoInteractiveMode) {
// this.panoInteractiveMode = panoInteractiveMode;
// }
// }
// Path: vrlib/src/main/java/com/martin/ads/vrlib/SensorEventHandler.java
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Surface;
import com.martin.ads.vrlib.constant.Constants;
import com.martin.ads.vrlib.utils.SensorUtils;
import com.martin.ads.vrlib.utils.StatusHelper;
package com.martin.ads.vrlib;
/**
* Project: Pano360
* Package: com.martin.ads.pano360
* Created by Ads on 2016/5/2.
*/
public class SensorEventHandler implements SensorEventListener {
public static String TAG = "SensorEventHandler";
private float[] rotationMatrix = new float[16];
//private float[] orientationData=new float[3];
private StatusHelper statusHelper;
private SensorHandlerCallback sensorHandlerCallback;
private boolean sensorRegistered;
private SensorManager sensorManager;
private int mDeviceRotation;
public void init(){
sensorRegistered=false;
sensorManager = (SensorManager) statusHelper.getContext()
.getSystemService(Context.SENSOR_SERVICE);
Sensor sensorRot = sensorManager.getDefaultSensor(Constants.SENSOR_ROT);
if (sensorRot==null) return;
sensorManager.registerListener(this, sensorRot, SensorManager.SENSOR_DELAY_GAME);
sensorRegistered=true;
}
public void releaseResources(){
if (!sensorRegistered || sensorManager==null) return;
sensorManager.unregisterListener(this);
sensorRegistered = false;
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.accuracy != 0){
int type = event.sensor.getType();
switch (type){
case Constants.SENSOR_ROT:
//FIXME
mDeviceRotation= ((Activity)statusHelper.getContext()).getWindowManager().getDefaultDisplay().getRotation(); | SensorUtils.sensorRotationVectorToMatrix(event,mDeviceRotation,rotationMatrix); |
trond-arve-wasskog/nytt-folkeregister-atom | datomic/src/test/java/ske/folkeregister/datomic/person/FeedGeneratorTest.java | // Path: datomic/src/main/java/ske/folkeregister/datomic/feed/FeedGenerator.java
// @SuppressWarnings("unchecked")
// public class FeedGenerator implements Runnable {
//
// private static final Logger log = LoggerFactory.getLogger(FeedGenerator.class);
//
// private static final Abdera abdera = Abdera.getInstance();
// private static final String attr_query =
// "[:find ?attrname :in $ ?attr :where [?attr :db/ident ?attrname]]";
// public static final String ssn_query =
// "[:find ?ssn :in $ ?entity :where [?entity :person/ssn ?ssn]]";
//
// private final BlockingQueue<Map> txReportQueue;
// private final WebResource feedResource;
//
// public FeedGenerator(Connection conn, WebResource feedResource) {
// this.feedResource = feedResource;
// txReportQueue = conn.txReportQueue();
// }
//
// @Override
// public void run() {
// while (true) {
// try {
// final Map tx = txReportQueue.take();
// final List<Datum> txData = (List<Datum>) tx.get(TX_DATA);
//
// log.info("Create feed entries tx: {}", txData.get(0).v());
//
// txData
// .stream()
// .skip(1)
// .collect(Collectors.groupingBy(Datum::e))
// .entrySet()
// .stream()
// .map(e -> {
// Entry entry = abdera.newEntry();
//
// String ssn = queryForSSN(tx, e.getKey());
// entry.addLink(entry.addLink("/person/" + ssn, "person"));
// entry.setTitle("Person " + ssn + " oppdatert");
//
// e.getValue().forEach(datum -> {
// if (datum.added()) {
// entry.addCategory(
// "added",
// queryForAttrName(tx.get(DB_AFTER), datum.a()),
// datum.v().toString()
// );
// } else {
// entry.addCategory(
// "removed",
// queryForAttrName(tx.get(DB_BEFORE), datum.a()),
// datum.v().toString()
// );
// }
// });
//
// return entry;
// })
// .forEach(entry -> {
// try {
// feedResource.type(MediaType.APPLICATION_ATOM_XML_TYPE).post(entry);
// } catch (Exception e) {
// log.error("Problem posting feed entry: {} ({})", entry, e.getMessage());
// }
// });
// } catch (Exception e) {
// log.error("Problem reading tx-report", e);
// }
// }
// }
//
// private String queryForSSN(Map tx, Object entity) {
// return Peer.q(ssn_query, tx.get(DB_AFTER), entity).iterator().next().get(0).toString();
// }
//
// private String queryForAttrName(Object db, Object attr) {
// return Peer.q(attr_query, db, attr).iterator().next().get(0).toString();
// }
// }
//
// Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
| import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import datomic.Connection;
import org.junit.Test;
import ske.folkeregister.datomic.feed.FeedGenerator;
import ske.folkeregister.datomic.util.IO;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static datomic.Util.list;
import static datomic.Util.map; | package ske.folkeregister.datomic.person;
public class FeedGeneratorTest {
@Test
public void listenForChanges() throws Exception { | // Path: datomic/src/main/java/ske/folkeregister/datomic/feed/FeedGenerator.java
// @SuppressWarnings("unchecked")
// public class FeedGenerator implements Runnable {
//
// private static final Logger log = LoggerFactory.getLogger(FeedGenerator.class);
//
// private static final Abdera abdera = Abdera.getInstance();
// private static final String attr_query =
// "[:find ?attrname :in $ ?attr :where [?attr :db/ident ?attrname]]";
// public static final String ssn_query =
// "[:find ?ssn :in $ ?entity :where [?entity :person/ssn ?ssn]]";
//
// private final BlockingQueue<Map> txReportQueue;
// private final WebResource feedResource;
//
// public FeedGenerator(Connection conn, WebResource feedResource) {
// this.feedResource = feedResource;
// txReportQueue = conn.txReportQueue();
// }
//
// @Override
// public void run() {
// while (true) {
// try {
// final Map tx = txReportQueue.take();
// final List<Datum> txData = (List<Datum>) tx.get(TX_DATA);
//
// log.info("Create feed entries tx: {}", txData.get(0).v());
//
// txData
// .stream()
// .skip(1)
// .collect(Collectors.groupingBy(Datum::e))
// .entrySet()
// .stream()
// .map(e -> {
// Entry entry = abdera.newEntry();
//
// String ssn = queryForSSN(tx, e.getKey());
// entry.addLink(entry.addLink("/person/" + ssn, "person"));
// entry.setTitle("Person " + ssn + " oppdatert");
//
// e.getValue().forEach(datum -> {
// if (datum.added()) {
// entry.addCategory(
// "added",
// queryForAttrName(tx.get(DB_AFTER), datum.a()),
// datum.v().toString()
// );
// } else {
// entry.addCategory(
// "removed",
// queryForAttrName(tx.get(DB_BEFORE), datum.a()),
// datum.v().toString()
// );
// }
// });
//
// return entry;
// })
// .forEach(entry -> {
// try {
// feedResource.type(MediaType.APPLICATION_ATOM_XML_TYPE).post(entry);
// } catch (Exception e) {
// log.error("Problem posting feed entry: {} ({})", entry, e.getMessage());
// }
// });
// } catch (Exception e) {
// log.error("Problem reading tx-report", e);
// }
// }
// }
//
// private String queryForSSN(Map tx, Object entity) {
// return Peer.q(ssn_query, tx.get(DB_AFTER), entity).iterator().next().get(0).toString();
// }
//
// private String queryForAttrName(Object db, Object attr) {
// return Peer.q(attr_query, db, attr).iterator().next().get(0).toString();
// }
// }
//
// Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
// Path: datomic/src/test/java/ske/folkeregister/datomic/person/FeedGeneratorTest.java
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import datomic.Connection;
import org.junit.Test;
import ske.folkeregister.datomic.feed.FeedGenerator;
import ske.folkeregister.datomic.util.IO;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static datomic.Util.list;
import static datomic.Util.map;
package ske.folkeregister.datomic.person;
public class FeedGeneratorTest {
@Test
public void listenForChanges() throws Exception { | final Connection conn = IO.newMemConnection(); |
trond-arve-wasskog/nytt-folkeregister-atom | datomic/src/test/java/ske/folkeregister/datomic/person/FeedGeneratorTest.java | // Path: datomic/src/main/java/ske/folkeregister/datomic/feed/FeedGenerator.java
// @SuppressWarnings("unchecked")
// public class FeedGenerator implements Runnable {
//
// private static final Logger log = LoggerFactory.getLogger(FeedGenerator.class);
//
// private static final Abdera abdera = Abdera.getInstance();
// private static final String attr_query =
// "[:find ?attrname :in $ ?attr :where [?attr :db/ident ?attrname]]";
// public static final String ssn_query =
// "[:find ?ssn :in $ ?entity :where [?entity :person/ssn ?ssn]]";
//
// private final BlockingQueue<Map> txReportQueue;
// private final WebResource feedResource;
//
// public FeedGenerator(Connection conn, WebResource feedResource) {
// this.feedResource = feedResource;
// txReportQueue = conn.txReportQueue();
// }
//
// @Override
// public void run() {
// while (true) {
// try {
// final Map tx = txReportQueue.take();
// final List<Datum> txData = (List<Datum>) tx.get(TX_DATA);
//
// log.info("Create feed entries tx: {}", txData.get(0).v());
//
// txData
// .stream()
// .skip(1)
// .collect(Collectors.groupingBy(Datum::e))
// .entrySet()
// .stream()
// .map(e -> {
// Entry entry = abdera.newEntry();
//
// String ssn = queryForSSN(tx, e.getKey());
// entry.addLink(entry.addLink("/person/" + ssn, "person"));
// entry.setTitle("Person " + ssn + " oppdatert");
//
// e.getValue().forEach(datum -> {
// if (datum.added()) {
// entry.addCategory(
// "added",
// queryForAttrName(tx.get(DB_AFTER), datum.a()),
// datum.v().toString()
// );
// } else {
// entry.addCategory(
// "removed",
// queryForAttrName(tx.get(DB_BEFORE), datum.a()),
// datum.v().toString()
// );
// }
// });
//
// return entry;
// })
// .forEach(entry -> {
// try {
// feedResource.type(MediaType.APPLICATION_ATOM_XML_TYPE).post(entry);
// } catch (Exception e) {
// log.error("Problem posting feed entry: {} ({})", entry, e.getMessage());
// }
// });
// } catch (Exception e) {
// log.error("Problem reading tx-report", e);
// }
// }
// }
//
// private String queryForSSN(Map tx, Object entity) {
// return Peer.q(ssn_query, tx.get(DB_AFTER), entity).iterator().next().get(0).toString();
// }
//
// private String queryForAttrName(Object db, Object attr) {
// return Peer.q(attr_query, db, attr).iterator().next().get(0).toString();
// }
// }
//
// Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
| import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import datomic.Connection;
import org.junit.Test;
import ske.folkeregister.datomic.feed.FeedGenerator;
import ske.folkeregister.datomic.util.IO;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static datomic.Util.list;
import static datomic.Util.map; | package ske.folkeregister.datomic.person;
public class FeedGeneratorTest {
@Test
public void listenForChanges() throws Exception {
final Connection conn = IO.newMemConnection();
IO.transactAllFromFile(conn, "datomic/schema.edn");
final ExecutorService executorService = Executors.newSingleThreadExecutor();
final WebResource atomhopperResource =
Client.create().resource("http://localhost:8080/folkeregister/person");
| // Path: datomic/src/main/java/ske/folkeregister/datomic/feed/FeedGenerator.java
// @SuppressWarnings("unchecked")
// public class FeedGenerator implements Runnable {
//
// private static final Logger log = LoggerFactory.getLogger(FeedGenerator.class);
//
// private static final Abdera abdera = Abdera.getInstance();
// private static final String attr_query =
// "[:find ?attrname :in $ ?attr :where [?attr :db/ident ?attrname]]";
// public static final String ssn_query =
// "[:find ?ssn :in $ ?entity :where [?entity :person/ssn ?ssn]]";
//
// private final BlockingQueue<Map> txReportQueue;
// private final WebResource feedResource;
//
// public FeedGenerator(Connection conn, WebResource feedResource) {
// this.feedResource = feedResource;
// txReportQueue = conn.txReportQueue();
// }
//
// @Override
// public void run() {
// while (true) {
// try {
// final Map tx = txReportQueue.take();
// final List<Datum> txData = (List<Datum>) tx.get(TX_DATA);
//
// log.info("Create feed entries tx: {}", txData.get(0).v());
//
// txData
// .stream()
// .skip(1)
// .collect(Collectors.groupingBy(Datum::e))
// .entrySet()
// .stream()
// .map(e -> {
// Entry entry = abdera.newEntry();
//
// String ssn = queryForSSN(tx, e.getKey());
// entry.addLink(entry.addLink("/person/" + ssn, "person"));
// entry.setTitle("Person " + ssn + " oppdatert");
//
// e.getValue().forEach(datum -> {
// if (datum.added()) {
// entry.addCategory(
// "added",
// queryForAttrName(tx.get(DB_AFTER), datum.a()),
// datum.v().toString()
// );
// } else {
// entry.addCategory(
// "removed",
// queryForAttrName(tx.get(DB_BEFORE), datum.a()),
// datum.v().toString()
// );
// }
// });
//
// return entry;
// })
// .forEach(entry -> {
// try {
// feedResource.type(MediaType.APPLICATION_ATOM_XML_TYPE).post(entry);
// } catch (Exception e) {
// log.error("Problem posting feed entry: {} ({})", entry, e.getMessage());
// }
// });
// } catch (Exception e) {
// log.error("Problem reading tx-report", e);
// }
// }
// }
//
// private String queryForSSN(Map tx, Object entity) {
// return Peer.q(ssn_query, tx.get(DB_AFTER), entity).iterator().next().get(0).toString();
// }
//
// private String queryForAttrName(Object db, Object attr) {
// return Peer.q(attr_query, db, attr).iterator().next().get(0).toString();
// }
// }
//
// Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
// Path: datomic/src/test/java/ske/folkeregister/datomic/person/FeedGeneratorTest.java
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import datomic.Connection;
import org.junit.Test;
import ske.folkeregister.datomic.feed.FeedGenerator;
import ske.folkeregister.datomic.util.IO;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static datomic.Util.list;
import static datomic.Util.map;
package ske.folkeregister.datomic.person;
public class FeedGeneratorTest {
@Test
public void listenForChanges() throws Exception {
final Connection conn = IO.newMemConnection();
IO.transactAllFromFile(conn, "datomic/schema.edn");
final ExecutorService executorService = Executors.newSingleThreadExecutor();
final WebResource atomhopperResource =
Client.create().resource("http://localhost:8080/folkeregister/person");
| executorService.execute(new FeedGenerator(conn, atomhopperResource)); |
trond-arve-wasskog/nytt-folkeregister-atom | datomic/src/main/java/ske/folkeregister/dw/api/PersonResource.java | // Path: datomic/src/main/java/ske/folkeregister/datomic/person/PersonApi.java
// public interface PersonApi {
// List<Object> findAllPersons();
//
// void changeNameAndStatus(String ssn, String newName, String newStatus) throws Exception;
//
// void moveToNewAddress(String ssn, String street, String number, String postnumber) throws Exception;
//
// List<Map> changesForPerson(String ssn) throws Exception;
//
// Map getPerson(String ssn) throws Exception;
//
// void updatePerson(Map person) throws Exception;
// }
| import ske.folkeregister.datomic.person.PersonApi;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Map; | package ske.folkeregister.dw.api;
@Path("persons")
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {
| // Path: datomic/src/main/java/ske/folkeregister/datomic/person/PersonApi.java
// public interface PersonApi {
// List<Object> findAllPersons();
//
// void changeNameAndStatus(String ssn, String newName, String newStatus) throws Exception;
//
// void moveToNewAddress(String ssn, String street, String number, String postnumber) throws Exception;
//
// List<Map> changesForPerson(String ssn) throws Exception;
//
// Map getPerson(String ssn) throws Exception;
//
// void updatePerson(Map person) throws Exception;
// }
// Path: datomic/src/main/java/ske/folkeregister/dw/api/PersonResource.java
import ske.folkeregister.datomic.person.PersonApi;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Map;
package ske.folkeregister.dw.api;
@Path("persons")
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {
| private final PersonApi personApi; |
trond-arve-wasskog/nytt-folkeregister-atom | datomic/src/test/java/ske/folkeregister/datomic/person/DatomicPersonApiTest.java | // Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
| import datomic.Connection;
import org.junit.Before;
import org.junit.Test;
import ske.folkeregister.datomic.util.IO;
import java.util.List;
import java.util.Map;
import static datomic.Util.map;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue; | changes.forEach(changeset -> {
System.out.println("\nTidspunkt: " + changeset.get("timestamp"));
System.out.println("Endringer:");
((List) changeset.get("changes")).forEach(obj -> System.out.println("\t" + obj));
});
}
@Test
public void testUpdateAndGet() throws Exception {
final String ssn = "1234";
final String name = "Test Person";
assertTrue("Empty map == not found", personApi.getPerson(ssn).isEmpty());
personApi.updatePerson(map(
":person/ssn", ssn,
":person/name", name
));
final Map person = personApi.getPerson(ssn);
assertEquals(ssn, person.get("ssn"));
assertEquals(name, person.get("name"));
assertTrue("Person not in all persons", personApi.findAllPersons().contains(person));
}
@Before
public void setUp() throws Exception {
System.out.print("Creating in-memory Datomic connection..."); | // Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
// Path: datomic/src/test/java/ske/folkeregister/datomic/person/DatomicPersonApiTest.java
import datomic.Connection;
import org.junit.Before;
import org.junit.Test;
import ske.folkeregister.datomic.util.IO;
import java.util.List;
import java.util.Map;
import static datomic.Util.map;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
changes.forEach(changeset -> {
System.out.println("\nTidspunkt: " + changeset.get("timestamp"));
System.out.println("Endringer:");
((List) changeset.get("changes")).forEach(obj -> System.out.println("\t" + obj));
});
}
@Test
public void testUpdateAndGet() throws Exception {
final String ssn = "1234";
final String name = "Test Person";
assertTrue("Empty map == not found", personApi.getPerson(ssn).isEmpty());
personApi.updatePerson(map(
":person/ssn", ssn,
":person/name", name
));
final Map person = personApi.getPerson(ssn);
assertEquals(ssn, person.get("ssn"));
assertEquals(name, person.get("name"));
assertTrue("Person not in all persons", personApi.findAllPersons().contains(person));
}
@Before
public void setUp() throws Exception {
System.out.print("Creating in-memory Datomic connection..."); | Connection conn = IO.newMemConnection(); |
trond-arve-wasskog/nytt-folkeregister-atom | datomic/src/main/java/ske/folkeregister/datomic/person/DatomicPersonApi.java | // Path: datomic/src/main/java/ske/folkeregister/datomic/util/Changes.java
// @SuppressWarnings("unchecked")
// public class Changes {
//
// private static final String TX_ATTR_FOR_ENTITY =
// "[:find ?tx ?a :in $ ?e :where [?e ?a _ ?tx]]";
//
// /**
// * Fra August Lilleaas: http://dbs-are-fn.com/2013/datomic_history_of_an_entity/
// */
// public static List<Map> changeOverTimeForEntity(Database db, Object entityId) {
// return Peer
// // Extracts all transaction/attributes for given database/entity
// .q(TX_ATTR_FOR_ENTITY, db.history(), entityId).stream()
// // Group all attribute changes for one transaction
// .collect(Collectors.groupingBy(list -> list.get(0))).values().stream()
// // Convert to map of timestamped changes
// .map(changes -> {
// final Object tx = changes.get(0).get(0);
// return map(
// "changes", mapChangesForEntity(db, entityId, changes),
// "timestamp", db.asOf(tx).entity(tx).get(":db/txInstant")
// );
// })
// // Return as a list of change-maps
// .collect(Collectors.toList());
// }
//
// private static List<Map> mapChangesForEntity(
// Database db,
// Object entityId,
// List<List<Object>> changes
// ) {
// return changes.stream()
// // Convert to map of attribute-changes
// .map(list -> {
// final Long tx = (Long) list.get(0);
// final Object attr = list.get(1);
//
// // Get database before and after transaction occured
// final Database dbBefore = db.asOf(tx - 1);
// final Database dbAfter = db.asOf(tx);
//
// // Get the attribute name before and after transaction occured
// final Object attrBefore = dbBefore.entity(attr).get(":db/ident");
// final Object attrAfter = dbAfter.entity(attr).get(":db/ident");
//
// // Find both the old and the new value of the attribute
// final Object oldVal = IO.attrToValue(dbBefore.entity(entityId), attrBefore);
// final Object newVal = IO.attrToValue(dbAfter.entity(entityId), attrAfter);
//
// // Create map with attribute-name -> old/new value
// return map(
// "attr", attrAfter.toString(),
// "old", oldVal,
// "new", newVal
// );
// })
// .collect(Collectors.toList());
// }
// }
//
// Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
| import datomic.Connection;
import datomic.Database;
import datomic.Entity;
import datomic.Peer;
import ske.folkeregister.datomic.util.Changes;
import ske.folkeregister.datomic.util.IO;
import java.util.*;
import java.util.stream.Collectors;
import static datomic.Peer.tempid;
import static datomic.Util.*;
import static datomic.Util.list;
import static datomic.Util.map; |
@Override
public void changeNameAndStatus(String ssn, String newName, String newStatus) throws Exception {
updatePerson(map(
":person/ssn", ssn,
":person/sivilstatus", read(newStatus),
":person/name", newName
));
}
@Override
public void moveToNewAddress(String ssn, String street, String number, String postnumber) throws Exception {
Object newTmpAddressId = tempid("db.part/user");
conn.transact(list(
map(
":db/id", newTmpAddressId,
":address/street", street,
":address/streetnumber", number,
":address/postnumber", postnumber
),
map(
":db/id", list(":person/ssn", ssn),
":person/address", newTmpAddressId
)
)).get();
}
@Override
public List<Map> changesForPerson(String ssn) throws Exception {
return findPersonBySSN(ssn) | // Path: datomic/src/main/java/ske/folkeregister/datomic/util/Changes.java
// @SuppressWarnings("unchecked")
// public class Changes {
//
// private static final String TX_ATTR_FOR_ENTITY =
// "[:find ?tx ?a :in $ ?e :where [?e ?a _ ?tx]]";
//
// /**
// * Fra August Lilleaas: http://dbs-are-fn.com/2013/datomic_history_of_an_entity/
// */
// public static List<Map> changeOverTimeForEntity(Database db, Object entityId) {
// return Peer
// // Extracts all transaction/attributes for given database/entity
// .q(TX_ATTR_FOR_ENTITY, db.history(), entityId).stream()
// // Group all attribute changes for one transaction
// .collect(Collectors.groupingBy(list -> list.get(0))).values().stream()
// // Convert to map of timestamped changes
// .map(changes -> {
// final Object tx = changes.get(0).get(0);
// return map(
// "changes", mapChangesForEntity(db, entityId, changes),
// "timestamp", db.asOf(tx).entity(tx).get(":db/txInstant")
// );
// })
// // Return as a list of change-maps
// .collect(Collectors.toList());
// }
//
// private static List<Map> mapChangesForEntity(
// Database db,
// Object entityId,
// List<List<Object>> changes
// ) {
// return changes.stream()
// // Convert to map of attribute-changes
// .map(list -> {
// final Long tx = (Long) list.get(0);
// final Object attr = list.get(1);
//
// // Get database before and after transaction occured
// final Database dbBefore = db.asOf(tx - 1);
// final Database dbAfter = db.asOf(tx);
//
// // Get the attribute name before and after transaction occured
// final Object attrBefore = dbBefore.entity(attr).get(":db/ident");
// final Object attrAfter = dbAfter.entity(attr).get(":db/ident");
//
// // Find both the old and the new value of the attribute
// final Object oldVal = IO.attrToValue(dbBefore.entity(entityId), attrBefore);
// final Object newVal = IO.attrToValue(dbAfter.entity(entityId), attrAfter);
//
// // Create map with attribute-name -> old/new value
// return map(
// "attr", attrAfter.toString(),
// "old", oldVal,
// "new", newVal
// );
// })
// .collect(Collectors.toList());
// }
// }
//
// Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
// Path: datomic/src/main/java/ske/folkeregister/datomic/person/DatomicPersonApi.java
import datomic.Connection;
import datomic.Database;
import datomic.Entity;
import datomic.Peer;
import ske.folkeregister.datomic.util.Changes;
import ske.folkeregister.datomic.util.IO;
import java.util.*;
import java.util.stream.Collectors;
import static datomic.Peer.tempid;
import static datomic.Util.*;
import static datomic.Util.list;
import static datomic.Util.map;
@Override
public void changeNameAndStatus(String ssn, String newName, String newStatus) throws Exception {
updatePerson(map(
":person/ssn", ssn,
":person/sivilstatus", read(newStatus),
":person/name", newName
));
}
@Override
public void moveToNewAddress(String ssn, String street, String number, String postnumber) throws Exception {
Object newTmpAddressId = tempid("db.part/user");
conn.transact(list(
map(
":db/id", newTmpAddressId,
":address/street", street,
":address/streetnumber", number,
":address/postnumber", postnumber
),
map(
":db/id", list(":person/ssn", ssn),
":person/address", newTmpAddressId
)
)).get();
}
@Override
public List<Map> changesForPerson(String ssn) throws Exception {
return findPersonBySSN(ssn) | .map(id -> Changes.changeOverTimeForEntity(conn.db(), id)) |
trond-arve-wasskog/nytt-folkeregister-atom | datomic/src/main/java/ske/folkeregister/datomic/person/DatomicPersonApi.java | // Path: datomic/src/main/java/ske/folkeregister/datomic/util/Changes.java
// @SuppressWarnings("unchecked")
// public class Changes {
//
// private static final String TX_ATTR_FOR_ENTITY =
// "[:find ?tx ?a :in $ ?e :where [?e ?a _ ?tx]]";
//
// /**
// * Fra August Lilleaas: http://dbs-are-fn.com/2013/datomic_history_of_an_entity/
// */
// public static List<Map> changeOverTimeForEntity(Database db, Object entityId) {
// return Peer
// // Extracts all transaction/attributes for given database/entity
// .q(TX_ATTR_FOR_ENTITY, db.history(), entityId).stream()
// // Group all attribute changes for one transaction
// .collect(Collectors.groupingBy(list -> list.get(0))).values().stream()
// // Convert to map of timestamped changes
// .map(changes -> {
// final Object tx = changes.get(0).get(0);
// return map(
// "changes", mapChangesForEntity(db, entityId, changes),
// "timestamp", db.asOf(tx).entity(tx).get(":db/txInstant")
// );
// })
// // Return as a list of change-maps
// .collect(Collectors.toList());
// }
//
// private static List<Map> mapChangesForEntity(
// Database db,
// Object entityId,
// List<List<Object>> changes
// ) {
// return changes.stream()
// // Convert to map of attribute-changes
// .map(list -> {
// final Long tx = (Long) list.get(0);
// final Object attr = list.get(1);
//
// // Get database before and after transaction occured
// final Database dbBefore = db.asOf(tx - 1);
// final Database dbAfter = db.asOf(tx);
//
// // Get the attribute name before and after transaction occured
// final Object attrBefore = dbBefore.entity(attr).get(":db/ident");
// final Object attrAfter = dbAfter.entity(attr).get(":db/ident");
//
// // Find both the old and the new value of the attribute
// final Object oldVal = IO.attrToValue(dbBefore.entity(entityId), attrBefore);
// final Object newVal = IO.attrToValue(dbAfter.entity(entityId), attrAfter);
//
// // Create map with attribute-name -> old/new value
// return map(
// "attr", attrAfter.toString(),
// "old", oldVal,
// "new", newVal
// );
// })
// .collect(Collectors.toList());
// }
// }
//
// Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
| import datomic.Connection;
import datomic.Database;
import datomic.Entity;
import datomic.Peer;
import ske.folkeregister.datomic.util.Changes;
import ske.folkeregister.datomic.util.IO;
import java.util.*;
import java.util.stream.Collectors;
import static datomic.Peer.tempid;
import static datomic.Util.*;
import static datomic.Util.list;
import static datomic.Util.map; | }
@Override
public void moveToNewAddress(String ssn, String street, String number, String postnumber) throws Exception {
Object newTmpAddressId = tempid("db.part/user");
conn.transact(list(
map(
":db/id", newTmpAddressId,
":address/street", street,
":address/streetnumber", number,
":address/postnumber", postnumber
),
map(
":db/id", list(":person/ssn", ssn),
":person/address", newTmpAddressId
)
)).get();
}
@Override
public List<Map> changesForPerson(String ssn) throws Exception {
return findPersonBySSN(ssn)
.map(id -> Changes.changeOverTimeForEntity(conn.db(), id))
.orElse(Collections.<Map>emptyList());
}
@Override
public Map getPerson(String ssn) throws Exception {
return findPersonBySSN(ssn)
.map(id -> conn.db().entity(id)) | // Path: datomic/src/main/java/ske/folkeregister/datomic/util/Changes.java
// @SuppressWarnings("unchecked")
// public class Changes {
//
// private static final String TX_ATTR_FOR_ENTITY =
// "[:find ?tx ?a :in $ ?e :where [?e ?a _ ?tx]]";
//
// /**
// * Fra August Lilleaas: http://dbs-are-fn.com/2013/datomic_history_of_an_entity/
// */
// public static List<Map> changeOverTimeForEntity(Database db, Object entityId) {
// return Peer
// // Extracts all transaction/attributes for given database/entity
// .q(TX_ATTR_FOR_ENTITY, db.history(), entityId).stream()
// // Group all attribute changes for one transaction
// .collect(Collectors.groupingBy(list -> list.get(0))).values().stream()
// // Convert to map of timestamped changes
// .map(changes -> {
// final Object tx = changes.get(0).get(0);
// return map(
// "changes", mapChangesForEntity(db, entityId, changes),
// "timestamp", db.asOf(tx).entity(tx).get(":db/txInstant")
// );
// })
// // Return as a list of change-maps
// .collect(Collectors.toList());
// }
//
// private static List<Map> mapChangesForEntity(
// Database db,
// Object entityId,
// List<List<Object>> changes
// ) {
// return changes.stream()
// // Convert to map of attribute-changes
// .map(list -> {
// final Long tx = (Long) list.get(0);
// final Object attr = list.get(1);
//
// // Get database before and after transaction occured
// final Database dbBefore = db.asOf(tx - 1);
// final Database dbAfter = db.asOf(tx);
//
// // Get the attribute name before and after transaction occured
// final Object attrBefore = dbBefore.entity(attr).get(":db/ident");
// final Object attrAfter = dbAfter.entity(attr).get(":db/ident");
//
// // Find both the old and the new value of the attribute
// final Object oldVal = IO.attrToValue(dbBefore.entity(entityId), attrBefore);
// final Object newVal = IO.attrToValue(dbAfter.entity(entityId), attrAfter);
//
// // Create map with attribute-name -> old/new value
// return map(
// "attr", attrAfter.toString(),
// "old", oldVal,
// "new", newVal
// );
// })
// .collect(Collectors.toList());
// }
// }
//
// Path: datomic/src/main/java/ske/folkeregister/datomic/util/IO.java
// @SuppressWarnings("unchecked")
// public class IO {
//
// public static void transactAllFromFile(Connection conn, String filename) throws InterruptedException, ExecutionException {
// for (List tx : readData(filename)) {
// conn.transact(tx).get();
// }
// }
//
// public static Connection newMemConnection() {
// String uri = "datomic:mem://" + UUID.randomUUID();
// Peer.createDatabase(uri);
// return Peer.connect(uri);
// }
//
// public static Map<String, Object> entityToMap(Entity entity) {
// return entity
// .keySet()
// .stream()
// .collect(Collectors.toMap(
// key -> key.substring(key.lastIndexOf("/") + 1),
// key -> attrToValue(entity, key)
// ));
// }
//
// public static Object attrToValue(Entity entity, Object key) {
// Object value = entity.get(key);
// if (value instanceof Entity) {
// value = entityToMap((Entity) value);
// } else if (value instanceof Keyword) {
// value = ((Keyword) value).getName();
// }
// return value;
// }
//
// private static List<List> readData(String filename) {
// return Util.readAll(new InputStreamReader(
// Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
// }
// }
// Path: datomic/src/main/java/ske/folkeregister/datomic/person/DatomicPersonApi.java
import datomic.Connection;
import datomic.Database;
import datomic.Entity;
import datomic.Peer;
import ske.folkeregister.datomic.util.Changes;
import ske.folkeregister.datomic.util.IO;
import java.util.*;
import java.util.stream.Collectors;
import static datomic.Peer.tempid;
import static datomic.Util.*;
import static datomic.Util.list;
import static datomic.Util.map;
}
@Override
public void moveToNewAddress(String ssn, String street, String number, String postnumber) throws Exception {
Object newTmpAddressId = tempid("db.part/user");
conn.transact(list(
map(
":db/id", newTmpAddressId,
":address/street", street,
":address/streetnumber", number,
":address/postnumber", postnumber
),
map(
":db/id", list(":person/ssn", ssn),
":person/address", newTmpAddressId
)
)).get();
}
@Override
public List<Map> changesForPerson(String ssn) throws Exception {
return findPersonBySSN(ssn)
.map(id -> Changes.changeOverTimeForEntity(conn.db(), id))
.orElse(Collections.<Map>emptyList());
}
@Override
public Map getPerson(String ssn) throws Exception {
return findPersonBySSN(ssn)
.map(id -> conn.db().entity(id)) | .map(IO::entityToMap) |
todvora/eet-client | src/main/java/cz/tomasdvorak/eet/client/timing/TimingReceiveInterceptor.java | // Path: src/main/java/cz/tomasdvorak/eet/client/utils/DateUtils.java
// public final class DateUtils {
//
// private static final XmlDateAdapter DATE_ADAPTER = new XmlDateAdapter();
//
// private DateUtils() {
// // utils class, no instance allowed
// }
//
// public static Date parse(final String date) {
// try {
// return DATE_ADAPTER.unmarshal(date);
// } catch (final ParseException e) {
// throw new InvalidFormatException(e);
// }
// }
//
// public static String format(final Date date) {
// return DATE_ADAPTER.marshal(date);
// }
// }
| import cz.tomasdvorak.eet.client.utils.DateUtils;
import cz.tomasdvorak.eet.client.utils.StringJoiner;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.LoggingMessage;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Date; | package cz.tomasdvorak.eet.client.timing;
/**
* Interceptor for logging the request-responce cycle duration to a CSV log.
*/
public class TimingReceiveInterceptor extends AbstractPhaseInterceptor<Message> {
public static final TimingReceiveInterceptor INSTANCE = new TimingReceiveInterceptor();
private static final Logger logger = LoggerFactory.getLogger(TimingReceiveInterceptor.class);
private TimingReceiveInterceptor() {
super(Phase.RECEIVE);
}
@Override
public void handleMessage(final Message msg) throws Fault {
final Long startTime = (Long) msg.getExchange().remove(TimingSendInterceptor.KEY);
if (startTime != null) {
final long executionTime = System.currentTimeMillis() - startTime;
logger.info(formatLogEntry(msg, executionTime));
}
}
private String formatLogEntry(final Message msg, final long executionTime) {
return StringJoiner.join(";", Arrays.asList( | // Path: src/main/java/cz/tomasdvorak/eet/client/utils/DateUtils.java
// public final class DateUtils {
//
// private static final XmlDateAdapter DATE_ADAPTER = new XmlDateAdapter();
//
// private DateUtils() {
// // utils class, no instance allowed
// }
//
// public static Date parse(final String date) {
// try {
// return DATE_ADAPTER.unmarshal(date);
// } catch (final ParseException e) {
// throw new InvalidFormatException(e);
// }
// }
//
// public static String format(final Date date) {
// return DATE_ADAPTER.marshal(date);
// }
// }
// Path: src/main/java/cz/tomasdvorak/eet/client/timing/TimingReceiveInterceptor.java
import cz.tomasdvorak.eet.client.utils.DateUtils;
import cz.tomasdvorak.eet.client.utils.StringJoiner;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.LoggingMessage;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Date;
package cz.tomasdvorak.eet.client.timing;
/**
* Interceptor for logging the request-responce cycle duration to a CSV log.
*/
public class TimingReceiveInterceptor extends AbstractPhaseInterceptor<Message> {
public static final TimingReceiveInterceptor INSTANCE = new TimingReceiveInterceptor();
private static final Logger logger = LoggerFactory.getLogger(TimingReceiveInterceptor.class);
private TimingReceiveInterceptor() {
super(Phase.RECEIVE);
}
@Override
public void handleMessage(final Message msg) throws Fault {
final Long startTime = (Long) msg.getExchange().remove(TimingSendInterceptor.KEY);
if (startTime != null) {
final long executionTime = System.currentTimeMillis() - startTime;
logger.info(formatLogEntry(msg, executionTime));
}
}
private String formatLogEntry(final Message msg, final long executionTime) {
return StringJoiner.join(";", Arrays.asList( | "" + DateUtils.format(new Date()), |
todvora/eet-client | src/main/java/cz/tomasdvorak/eet/client/dto/SubmitResult.java | // Path: src/main/java/cz/tomasdvorak/eet/client/persistence/RequestSerializer.java
// public class RequestSerializer {
//
// /**
// * Convert request to a String representation.
// */
// public static String toString(TrzbaType request) {
// try {
// final JAXBElement<TrzbaType> trzba = new ObjectFactory().createTrzba(request);
// JAXBContext context = JAXBContext.newInstance(TrzbaType.class);
// StringWriter sw = new StringWriter();
// context.createMarshaller().marshal(trzba, sw);
// return sw.toString();
// } catch (JAXBException e) {
// throw new RequestSerializationException("Failed to serialize EET request to String", e);
// }
// }
//
// /**
// * Restore request from a String back to object.
// */
// public static TrzbaType fromString(String request) {
// try {
// JAXBContext jaxbContext = JAXBContext.newInstance(TrzbaType.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
// InputStream is = new ByteArrayInputStream(request.getBytes());
// JAXBElement<TrzbaType> reqestElement = jaxbUnmarshaller.unmarshal(new StreamSource(is), TrzbaType.class);
// return reqestElement.getValue();
// } catch (JAXBException e) {
// throw new RequestSerializationException("Failed to deserialize EET request from String", e);
// }
// }
// }
| import cz.etrzby.xml.OdpovedType;
import cz.etrzby.xml.TrzbaType;
import cz.tomasdvorak.eet.client.persistence.RequestSerializer;
import cz.tomasdvorak.eet.client.utils.StringUtils; | package cz.tomasdvorak.eet.client.dto;
/**
* Communication result holding all response data and additionally also all request data.
* There are defined some additional helper methods for easier access to usual fields (FIK, PKP, BKP)
*/
public class SubmitResult extends OdpovedType {
private final TrzbaType request;
public SubmitResult(final TrzbaType request, final OdpovedType response) {
super();
setChyba(response.getChyba());
setHlavicka(response.getHlavicka());
setPotvrzeni(response.getPotvrzeni());
withVarovani(response.getVarovani());
this.request = request;
}
/**
* Get the original request to this response
*/
public TrzbaType getRequest() {
return request;
}
/**
* Convert the current request to a String representation. Useful for persisting and/or logging purposes.
* @return String representation of current request.
*/
public String serializeRequest() { | // Path: src/main/java/cz/tomasdvorak/eet/client/persistence/RequestSerializer.java
// public class RequestSerializer {
//
// /**
// * Convert request to a String representation.
// */
// public static String toString(TrzbaType request) {
// try {
// final JAXBElement<TrzbaType> trzba = new ObjectFactory().createTrzba(request);
// JAXBContext context = JAXBContext.newInstance(TrzbaType.class);
// StringWriter sw = new StringWriter();
// context.createMarshaller().marshal(trzba, sw);
// return sw.toString();
// } catch (JAXBException e) {
// throw new RequestSerializationException("Failed to serialize EET request to String", e);
// }
// }
//
// /**
// * Restore request from a String back to object.
// */
// public static TrzbaType fromString(String request) {
// try {
// JAXBContext jaxbContext = JAXBContext.newInstance(TrzbaType.class);
// Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
// InputStream is = new ByteArrayInputStream(request.getBytes());
// JAXBElement<TrzbaType> reqestElement = jaxbUnmarshaller.unmarshal(new StreamSource(is), TrzbaType.class);
// return reqestElement.getValue();
// } catch (JAXBException e) {
// throw new RequestSerializationException("Failed to deserialize EET request from String", e);
// }
// }
// }
// Path: src/main/java/cz/tomasdvorak/eet/client/dto/SubmitResult.java
import cz.etrzby.xml.OdpovedType;
import cz.etrzby.xml.TrzbaType;
import cz.tomasdvorak.eet.client.persistence.RequestSerializer;
import cz.tomasdvorak.eet.client.utils.StringUtils;
package cz.tomasdvorak.eet.client.dto;
/**
* Communication result holding all response data and additionally also all request data.
* There are defined some additional helper methods for easier access to usual fields (FIK, PKP, BKP)
*/
public class SubmitResult extends OdpovedType {
private final TrzbaType request;
public SubmitResult(final TrzbaType request, final OdpovedType response) {
super();
setChyba(response.getChyba());
setHlavicka(response.getHlavicka());
setPotvrzeni(response.getPotvrzeni());
withVarovani(response.getVarovani());
this.request = request;
}
/**
* Get the original request to this response
*/
public TrzbaType getRequest() {
return request;
}
/**
* Convert the current request to a String representation. Useful for persisting and/or logging purposes.
* @return String representation of current request.
*/
public String serializeRequest() { | return RequestSerializer.toString(request); |
todvora/eet-client | src/main/java/cz/tomasdvorak/eet/client/networking/DnsLookupWithTimeout.java | // Path: src/main/java/cz/tomasdvorak/eet/client/dto/DnsResolver.java
// public interface DnsResolver {
//
// /**
// * Convert a domain name to IP address.
// *
// * @param hostname Pure hostname, without protocol or path. For example pg.eet.cz
// * @return IP address as a String
// * @throws UnknownHostException in case DNS lookup fails.
// */
// String getHostAddress(String hostname) throws UnknownHostException;
// }
| import cz.tomasdvorak.eet.client.dto.DnsResolver;
import cz.tomasdvorak.eet.client.exceptions.DnsLookupFailedException;
import cz.tomasdvorak.eet.client.exceptions.DnsTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.*; | package cz.tomasdvorak.eet.client.networking;
public class DnsLookupWithTimeout implements DnsLookup {
private static final Logger logger = LoggerFactory.getLogger(DnsLookupWithTimeout.class);
private final long timeoutMillis; | // Path: src/main/java/cz/tomasdvorak/eet/client/dto/DnsResolver.java
// public interface DnsResolver {
//
// /**
// * Convert a domain name to IP address.
// *
// * @param hostname Pure hostname, without protocol or path. For example pg.eet.cz
// * @return IP address as a String
// * @throws UnknownHostException in case DNS lookup fails.
// */
// String getHostAddress(String hostname) throws UnknownHostException;
// }
// Path: src/main/java/cz/tomasdvorak/eet/client/networking/DnsLookupWithTimeout.java
import cz.tomasdvorak.eet.client.dto.DnsResolver;
import cz.tomasdvorak.eet.client.exceptions.DnsLookupFailedException;
import cz.tomasdvorak.eet.client.exceptions.DnsTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.*;
package cz.tomasdvorak.eet.client.networking;
public class DnsLookupWithTimeout implements DnsLookup {
private static final Logger logger = LoggerFactory.getLogger(DnsLookupWithTimeout.class);
private final long timeoutMillis; | private final DnsResolver dnsResolver; |
todvora/eet-client | src/main/java/cz/tomasdvorak/eet/client/persistence/RequestSerializer.java | // Path: src/main/java/cz/tomasdvorak/eet/client/exceptions/RequestSerializationException.java
// public class RequestSerializationException extends RuntimeException {
// public RequestSerializationException(final String message, final JAXBException cause) {
// super(message, cause);
//
// }
// }
| import cz.etrzby.xml.ObjectFactory;
import cz.etrzby.xml.TrzbaType;
import cz.tomasdvorak.eet.client.exceptions.RequestSerializationException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.*; | package cz.tomasdvorak.eet.client.persistence;
/**
* EET request serializer / deserializer. May serve for persistence or logging.
*/
public class RequestSerializer {
/**
* Convert request to a String representation.
*/
public static String toString(TrzbaType request) {
try {
final JAXBElement<TrzbaType> trzba = new ObjectFactory().createTrzba(request);
JAXBContext context = JAXBContext.newInstance(TrzbaType.class);
StringWriter sw = new StringWriter();
context.createMarshaller().marshal(trzba, sw);
return sw.toString();
} catch (JAXBException e) { | // Path: src/main/java/cz/tomasdvorak/eet/client/exceptions/RequestSerializationException.java
// public class RequestSerializationException extends RuntimeException {
// public RequestSerializationException(final String message, final JAXBException cause) {
// super(message, cause);
//
// }
// }
// Path: src/main/java/cz/tomasdvorak/eet/client/persistence/RequestSerializer.java
import cz.etrzby.xml.ObjectFactory;
import cz.etrzby.xml.TrzbaType;
import cz.tomasdvorak.eet.client.exceptions.RequestSerializationException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
package cz.tomasdvorak.eet.client.persistence;
/**
* EET request serializer / deserializer. May serve for persistence or logging.
*/
public class RequestSerializer {
/**
* Convert request to a String representation.
*/
public static String toString(TrzbaType request) {
try {
final JAXBElement<TrzbaType> trzba = new ObjectFactory().createTrzba(request);
JAXBContext context = JAXBContext.newInstance(TrzbaType.class);
StringWriter sw = new StringWriter();
context.createMarshaller().marshal(trzba, sw);
return sw.toString();
} catch (JAXBException e) { | throw new RequestSerializationException("Failed to serialize EET request to String", e); |
todvora/eet-client | src/test/java/cz/tomasdvorak/eet/client/networking/DnsLookupWithTimeoutTest.java | // Path: src/main/java/cz/tomasdvorak/eet/client/dto/DnsResolver.java
// public interface DnsResolver {
//
// /**
// * Convert a domain name to IP address.
// *
// * @param hostname Pure hostname, without protocol or path. For example pg.eet.cz
// * @return IP address as a String
// * @throws UnknownHostException in case DNS lookup fails.
// */
// String getHostAddress(String hostname) throws UnknownHostException;
// }
| import cz.tomasdvorak.eet.client.config.EndpointType;
import cz.tomasdvorak.eet.client.dto.DnsResolver;
import cz.tomasdvorak.eet.client.exceptions.DnsLookupFailedException;
import cz.tomasdvorak.eet.client.exceptions.DnsTimeoutException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException; | package cz.tomasdvorak.eet.client.networking;
public class DnsLookupWithTimeoutTest {
private DnsLookup resolver;
@Before
public void setUp() throws Exception {
| // Path: src/main/java/cz/tomasdvorak/eet/client/dto/DnsResolver.java
// public interface DnsResolver {
//
// /**
// * Convert a domain name to IP address.
// *
// * @param hostname Pure hostname, without protocol or path. For example pg.eet.cz
// * @return IP address as a String
// * @throws UnknownHostException in case DNS lookup fails.
// */
// String getHostAddress(String hostname) throws UnknownHostException;
// }
// Path: src/test/java/cz/tomasdvorak/eet/client/networking/DnsLookupWithTimeoutTest.java
import cz.tomasdvorak.eet.client.config.EndpointType;
import cz.tomasdvorak.eet.client.dto.DnsResolver;
import cz.tomasdvorak.eet.client.exceptions.DnsLookupFailedException;
import cz.tomasdvorak.eet.client.exceptions.DnsTimeoutException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;
package cz.tomasdvorak.eet.client.networking;
public class DnsLookupWithTimeoutTest {
private DnsLookup resolver;
@Before
public void setUp() throws Exception {
| final DnsResolver resolverImpl = new DnsResolver() { |
todvora/eet-client | src/main/java/cz/tomasdvorak/eet/client/EETClient.java | // Path: src/main/java/cz/tomasdvorak/eet/client/config/SubmissionType.java
// @Deprecated
// public enum SubmissionType {
// FIRST_ATTEMPT(true),
// REPEATED_ATTEMPT(false);
//
// private final boolean isFirstSubmission;
//
// SubmissionType(final boolean isFirstSubmission) {
// this.isFirstSubmission = isFirstSubmission;
// }
//
// public boolean isFirstSubmission() {
// return isFirstSubmission;
// }
// }
//
// Path: src/main/java/cz/tomasdvorak/eet/client/dto/SubmitResult.java
// public class SubmitResult extends OdpovedType {
//
// private final TrzbaType request;
//
// public SubmitResult(final TrzbaType request, final OdpovedType response) {
// super();
// setChyba(response.getChyba());
// setHlavicka(response.getHlavicka());
// setPotvrzeni(response.getPotvrzeni());
// withVarovani(response.getVarovani());
// this.request = request;
// }
//
// /**
// * Get the original request to this response
// */
// public TrzbaType getRequest() {
// return request;
// }
//
// /**
// * Convert the current request to a String representation. Useful for persisting and/or logging purposes.
// * @return String representation of current request.
// */
// public String serializeRequest() {
// return RequestSerializer.toString(request);
// }
//
// /**
// * Utility method for easier access to BKP (Taxpayer's Security Code) security code
// * @return BKP code from the request
// */
// public String getBKP() {
// return request.getKontrolniKody().getBkp().getValue();
// }
//
// /**
// * Utility method for easier access to PKP (Taxpayer's Signature Code) security code
// * @return PKP code, encoded as Base64, suitable for printing on the receipt in case of communication failure.
// */
// public String getPKP() {
// return StringUtils.toBase64(request.getKontrolniKody().getPkp().getValue());
// }
//
// /**
// * Utility method for easier access to FIK (Fiscal Identification Code)
// * @return FIK code from the response. May be {@code null}, if the response contains errors
// */
// public String getFik() {
// return getPotvrzeni() == null ? null : getPotvrzeni().getFik();
// }
// }
| import cz.etrzby.xml.TrzbaDataType;
import cz.etrzby.xml.TrzbaType;
import cz.tomasdvorak.eet.client.config.CommunicationMode;
import cz.tomasdvorak.eet.client.config.EndpointType;
import cz.tomasdvorak.eet.client.config.SubmissionType;
import cz.tomasdvorak.eet.client.dto.ResponseCallback;
import cz.tomasdvorak.eet.client.dto.SubmitResult;
import cz.tomasdvorak.eet.client.exceptions.DataSigningException;
import cz.tomasdvorak.eet.client.exceptions.CommunicationException;
import java.util.concurrent.Future; | package cz.tomasdvorak.eet.client;
/**
* EET client implementation, handling computation of security codes, signing of requests, validation of responses.
*/
public interface EETClient {
/**
* Prepare request for <strong>first submit</strong> to EET Service.
* @param receiptData Receipt data like price, VAT or Tax ID.
* @param mode test or real communication (will be encoded in header
* @return complete request, including computed security codes, added random message UUID, current date.
* @throws DataSigningException if problem with signing occurs. Should be related to client key in that case
*/
TrzbaType prepareFirstRequest(final TrzbaDataType receiptData, final CommunicationMode mode) throws DataSigningException;
/**
* Prepare request for <strong>second or every other</strong> submit to EET service.
* @param request the original request, which has been already constructed and sent to EET servers.
* @return Updated request, re-generated message UUID, send date, set first-submission flag to false, recomputed
* security codes if they change meanwhile (new client certificate used for this submission)
* @throws DataSigningException if problem with signing occurs. Should be related to client key in that case
*/
TrzbaType prepareRepeatedRequest(final TrzbaType request) throws DataSigningException;
/**
* Submit synchronously a receipt to EET servers.
* @param request prepared by calling one of {@link #prepareFirstRequest(TrzbaDataType, CommunicationMode)} or {@link #prepareRepeatedRequest(TrzbaType)} method.
* @param endpointType real or test endpoint
* @return result provided by EET servers.
* @throws CommunicationException if something fails. It may be timeout, not accessible servers, invalid message, invalid signature of response.
*/ | // Path: src/main/java/cz/tomasdvorak/eet/client/config/SubmissionType.java
// @Deprecated
// public enum SubmissionType {
// FIRST_ATTEMPT(true),
// REPEATED_ATTEMPT(false);
//
// private final boolean isFirstSubmission;
//
// SubmissionType(final boolean isFirstSubmission) {
// this.isFirstSubmission = isFirstSubmission;
// }
//
// public boolean isFirstSubmission() {
// return isFirstSubmission;
// }
// }
//
// Path: src/main/java/cz/tomasdvorak/eet/client/dto/SubmitResult.java
// public class SubmitResult extends OdpovedType {
//
// private final TrzbaType request;
//
// public SubmitResult(final TrzbaType request, final OdpovedType response) {
// super();
// setChyba(response.getChyba());
// setHlavicka(response.getHlavicka());
// setPotvrzeni(response.getPotvrzeni());
// withVarovani(response.getVarovani());
// this.request = request;
// }
//
// /**
// * Get the original request to this response
// */
// public TrzbaType getRequest() {
// return request;
// }
//
// /**
// * Convert the current request to a String representation. Useful for persisting and/or logging purposes.
// * @return String representation of current request.
// */
// public String serializeRequest() {
// return RequestSerializer.toString(request);
// }
//
// /**
// * Utility method for easier access to BKP (Taxpayer's Security Code) security code
// * @return BKP code from the request
// */
// public String getBKP() {
// return request.getKontrolniKody().getBkp().getValue();
// }
//
// /**
// * Utility method for easier access to PKP (Taxpayer's Signature Code) security code
// * @return PKP code, encoded as Base64, suitable for printing on the receipt in case of communication failure.
// */
// public String getPKP() {
// return StringUtils.toBase64(request.getKontrolniKody().getPkp().getValue());
// }
//
// /**
// * Utility method for easier access to FIK (Fiscal Identification Code)
// * @return FIK code from the response. May be {@code null}, if the response contains errors
// */
// public String getFik() {
// return getPotvrzeni() == null ? null : getPotvrzeni().getFik();
// }
// }
// Path: src/main/java/cz/tomasdvorak/eet/client/EETClient.java
import cz.etrzby.xml.TrzbaDataType;
import cz.etrzby.xml.TrzbaType;
import cz.tomasdvorak.eet.client.config.CommunicationMode;
import cz.tomasdvorak.eet.client.config.EndpointType;
import cz.tomasdvorak.eet.client.config.SubmissionType;
import cz.tomasdvorak.eet.client.dto.ResponseCallback;
import cz.tomasdvorak.eet.client.dto.SubmitResult;
import cz.tomasdvorak.eet.client.exceptions.DataSigningException;
import cz.tomasdvorak.eet.client.exceptions.CommunicationException;
import java.util.concurrent.Future;
package cz.tomasdvorak.eet.client;
/**
* EET client implementation, handling computation of security codes, signing of requests, validation of responses.
*/
public interface EETClient {
/**
* Prepare request for <strong>first submit</strong> to EET Service.
* @param receiptData Receipt data like price, VAT or Tax ID.
* @param mode test or real communication (will be encoded in header
* @return complete request, including computed security codes, added random message UUID, current date.
* @throws DataSigningException if problem with signing occurs. Should be related to client key in that case
*/
TrzbaType prepareFirstRequest(final TrzbaDataType receiptData, final CommunicationMode mode) throws DataSigningException;
/**
* Prepare request for <strong>second or every other</strong> submit to EET service.
* @param request the original request, which has been already constructed and sent to EET servers.
* @return Updated request, re-generated message UUID, send date, set first-submission flag to false, recomputed
* security codes if they change meanwhile (new client certificate used for this submission)
* @throws DataSigningException if problem with signing occurs. Should be related to client key in that case
*/
TrzbaType prepareRepeatedRequest(final TrzbaType request) throws DataSigningException;
/**
* Submit synchronously a receipt to EET servers.
* @param request prepared by calling one of {@link #prepareFirstRequest(TrzbaDataType, CommunicationMode)} or {@link #prepareRepeatedRequest(TrzbaType)} method.
* @param endpointType real or test endpoint
* @return result provided by EET servers.
* @throws CommunicationException if something fails. It may be timeout, not accessible servers, invalid message, invalid signature of response.
*/ | SubmitResult sendSync(final TrzbaType request, final EndpointType endpointType) throws CommunicationException; |
todvora/eet-client | src/main/java/cz/tomasdvorak/eet/client/EETClient.java | // Path: src/main/java/cz/tomasdvorak/eet/client/config/SubmissionType.java
// @Deprecated
// public enum SubmissionType {
// FIRST_ATTEMPT(true),
// REPEATED_ATTEMPT(false);
//
// private final boolean isFirstSubmission;
//
// SubmissionType(final boolean isFirstSubmission) {
// this.isFirstSubmission = isFirstSubmission;
// }
//
// public boolean isFirstSubmission() {
// return isFirstSubmission;
// }
// }
//
// Path: src/main/java/cz/tomasdvorak/eet/client/dto/SubmitResult.java
// public class SubmitResult extends OdpovedType {
//
// private final TrzbaType request;
//
// public SubmitResult(final TrzbaType request, final OdpovedType response) {
// super();
// setChyba(response.getChyba());
// setHlavicka(response.getHlavicka());
// setPotvrzeni(response.getPotvrzeni());
// withVarovani(response.getVarovani());
// this.request = request;
// }
//
// /**
// * Get the original request to this response
// */
// public TrzbaType getRequest() {
// return request;
// }
//
// /**
// * Convert the current request to a String representation. Useful for persisting and/or logging purposes.
// * @return String representation of current request.
// */
// public String serializeRequest() {
// return RequestSerializer.toString(request);
// }
//
// /**
// * Utility method for easier access to BKP (Taxpayer's Security Code) security code
// * @return BKP code from the request
// */
// public String getBKP() {
// return request.getKontrolniKody().getBkp().getValue();
// }
//
// /**
// * Utility method for easier access to PKP (Taxpayer's Signature Code) security code
// * @return PKP code, encoded as Base64, suitable for printing on the receipt in case of communication failure.
// */
// public String getPKP() {
// return StringUtils.toBase64(request.getKontrolniKody().getPkp().getValue());
// }
//
// /**
// * Utility method for easier access to FIK (Fiscal Identification Code)
// * @return FIK code from the response. May be {@code null}, if the response contains errors
// */
// public String getFik() {
// return getPotvrzeni() == null ? null : getPotvrzeni().getFik();
// }
// }
| import cz.etrzby.xml.TrzbaDataType;
import cz.etrzby.xml.TrzbaType;
import cz.tomasdvorak.eet.client.config.CommunicationMode;
import cz.tomasdvorak.eet.client.config.EndpointType;
import cz.tomasdvorak.eet.client.config.SubmissionType;
import cz.tomasdvorak.eet.client.dto.ResponseCallback;
import cz.tomasdvorak.eet.client.dto.SubmitResult;
import cz.tomasdvorak.eet.client.exceptions.DataSigningException;
import cz.tomasdvorak.eet.client.exceptions.CommunicationException;
import java.util.concurrent.Future; | package cz.tomasdvorak.eet.client;
/**
* EET client implementation, handling computation of security codes, signing of requests, validation of responses.
*/
public interface EETClient {
/**
* Prepare request for <strong>first submit</strong> to EET Service.
* @param receiptData Receipt data like price, VAT or Tax ID.
* @param mode test or real communication (will be encoded in header
* @return complete request, including computed security codes, added random message UUID, current date.
* @throws DataSigningException if problem with signing occurs. Should be related to client key in that case
*/
TrzbaType prepareFirstRequest(final TrzbaDataType receiptData, final CommunicationMode mode) throws DataSigningException;
/**
* Prepare request for <strong>second or every other</strong> submit to EET service.
* @param request the original request, which has been already constructed and sent to EET servers.
* @return Updated request, re-generated message UUID, send date, set first-submission flag to false, recomputed
* security codes if they change meanwhile (new client certificate used for this submission)
* @throws DataSigningException if problem with signing occurs. Should be related to client key in that case
*/
TrzbaType prepareRepeatedRequest(final TrzbaType request) throws DataSigningException;
/**
* Submit synchronously a receipt to EET servers.
* @param request prepared by calling one of {@link #prepareFirstRequest(TrzbaDataType, CommunicationMode)} or {@link #prepareRepeatedRequest(TrzbaType)} method.
* @param endpointType real or test endpoint
* @return result provided by EET servers.
* @throws CommunicationException if something fails. It may be timeout, not accessible servers, invalid message, invalid signature of response.
*/
SubmitResult sendSync(final TrzbaType request, final EndpointType endpointType) throws CommunicationException;
/**
* Submit asynchronously a receipt to EET servers.
* @param request prepared by calling one of {@link #prepareFirstRequest(TrzbaDataType, CommunicationMode)} or {@link #prepareRepeatedRequest(TrzbaType)} method.
* @param endpointType real or test endpoint
* @param handler callback for response or failure of the call
* @return result future you can wait on
*/
Future<?> sendAsync(final TrzbaType request, final EndpointType endpointType, final ResponseCallback handler);
/**
* Central method of EET. Send the receipt data to selected endpoint, select if it's first or repeated
* submission and if the communication is test only or real.
*
* This method is DEPRECATED. Prepare data using prepareFirstRequest first, then send them using one of send* methods.
*
* @param receipt Receipt data - price, date, tax numbers, ...
* @param mode real or test submission
* @param endpointType playground or real endpoint
* @param submissionType first or repeated submission
* @return EET response with added request needed to access security codes and other data in case of failed submission
* @throws DataSigningException Failed to compute PKP or BKP
* @throws CommunicationException Failed to send or receive data from EET endpoint
*/
@Deprecated | // Path: src/main/java/cz/tomasdvorak/eet/client/config/SubmissionType.java
// @Deprecated
// public enum SubmissionType {
// FIRST_ATTEMPT(true),
// REPEATED_ATTEMPT(false);
//
// private final boolean isFirstSubmission;
//
// SubmissionType(final boolean isFirstSubmission) {
// this.isFirstSubmission = isFirstSubmission;
// }
//
// public boolean isFirstSubmission() {
// return isFirstSubmission;
// }
// }
//
// Path: src/main/java/cz/tomasdvorak/eet/client/dto/SubmitResult.java
// public class SubmitResult extends OdpovedType {
//
// private final TrzbaType request;
//
// public SubmitResult(final TrzbaType request, final OdpovedType response) {
// super();
// setChyba(response.getChyba());
// setHlavicka(response.getHlavicka());
// setPotvrzeni(response.getPotvrzeni());
// withVarovani(response.getVarovani());
// this.request = request;
// }
//
// /**
// * Get the original request to this response
// */
// public TrzbaType getRequest() {
// return request;
// }
//
// /**
// * Convert the current request to a String representation. Useful for persisting and/or logging purposes.
// * @return String representation of current request.
// */
// public String serializeRequest() {
// return RequestSerializer.toString(request);
// }
//
// /**
// * Utility method for easier access to BKP (Taxpayer's Security Code) security code
// * @return BKP code from the request
// */
// public String getBKP() {
// return request.getKontrolniKody().getBkp().getValue();
// }
//
// /**
// * Utility method for easier access to PKP (Taxpayer's Signature Code) security code
// * @return PKP code, encoded as Base64, suitable for printing on the receipt in case of communication failure.
// */
// public String getPKP() {
// return StringUtils.toBase64(request.getKontrolniKody().getPkp().getValue());
// }
//
// /**
// * Utility method for easier access to FIK (Fiscal Identification Code)
// * @return FIK code from the response. May be {@code null}, if the response contains errors
// */
// public String getFik() {
// return getPotvrzeni() == null ? null : getPotvrzeni().getFik();
// }
// }
// Path: src/main/java/cz/tomasdvorak/eet/client/EETClient.java
import cz.etrzby.xml.TrzbaDataType;
import cz.etrzby.xml.TrzbaType;
import cz.tomasdvorak.eet.client.config.CommunicationMode;
import cz.tomasdvorak.eet.client.config.EndpointType;
import cz.tomasdvorak.eet.client.config.SubmissionType;
import cz.tomasdvorak.eet.client.dto.ResponseCallback;
import cz.tomasdvorak.eet.client.dto.SubmitResult;
import cz.tomasdvorak.eet.client.exceptions.DataSigningException;
import cz.tomasdvorak.eet.client.exceptions.CommunicationException;
import java.util.concurrent.Future;
package cz.tomasdvorak.eet.client;
/**
* EET client implementation, handling computation of security codes, signing of requests, validation of responses.
*/
public interface EETClient {
/**
* Prepare request for <strong>first submit</strong> to EET Service.
* @param receiptData Receipt data like price, VAT or Tax ID.
* @param mode test or real communication (will be encoded in header
* @return complete request, including computed security codes, added random message UUID, current date.
* @throws DataSigningException if problem with signing occurs. Should be related to client key in that case
*/
TrzbaType prepareFirstRequest(final TrzbaDataType receiptData, final CommunicationMode mode) throws DataSigningException;
/**
* Prepare request for <strong>second or every other</strong> submit to EET service.
* @param request the original request, which has been already constructed and sent to EET servers.
* @return Updated request, re-generated message UUID, send date, set first-submission flag to false, recomputed
* security codes if they change meanwhile (new client certificate used for this submission)
* @throws DataSigningException if problem with signing occurs. Should be related to client key in that case
*/
TrzbaType prepareRepeatedRequest(final TrzbaType request) throws DataSigningException;
/**
* Submit synchronously a receipt to EET servers.
* @param request prepared by calling one of {@link #prepareFirstRequest(TrzbaDataType, CommunicationMode)} or {@link #prepareRepeatedRequest(TrzbaType)} method.
* @param endpointType real or test endpoint
* @return result provided by EET servers.
* @throws CommunicationException if something fails. It may be timeout, not accessible servers, invalid message, invalid signature of response.
*/
SubmitResult sendSync(final TrzbaType request, final EndpointType endpointType) throws CommunicationException;
/**
* Submit asynchronously a receipt to EET servers.
* @param request prepared by calling one of {@link #prepareFirstRequest(TrzbaDataType, CommunicationMode)} or {@link #prepareRepeatedRequest(TrzbaType)} method.
* @param endpointType real or test endpoint
* @param handler callback for response or failure of the call
* @return result future you can wait on
*/
Future<?> sendAsync(final TrzbaType request, final EndpointType endpointType, final ResponseCallback handler);
/**
* Central method of EET. Send the receipt data to selected endpoint, select if it's first or repeated
* submission and if the communication is test only or real.
*
* This method is DEPRECATED. Prepare data using prepareFirstRequest first, then send them using one of send* methods.
*
* @param receipt Receipt data - price, date, tax numbers, ...
* @param mode real or test submission
* @param endpointType playground or real endpoint
* @param submissionType first or repeated submission
* @return EET response with added request needed to access security codes and other data in case of failed submission
* @throws DataSigningException Failed to compute PKP or BKP
* @throws CommunicationException Failed to send or receive data from EET endpoint
*/
@Deprecated | SubmitResult submitReceipt(final TrzbaDataType receipt, final CommunicationMode mode, final EndpointType endpointType, final SubmissionType submissionType) throws DataSigningException, CommunicationException; |
todvora/eet-client | src/main/java/cz/tomasdvorak/eet/client/dto/WebserviceConfiguration.java | // Path: src/main/java/cz/tomasdvorak/eet/client/networking/InetAddressDnsResolver.java
// public class InetAddressDnsResolver implements DnsResolver {
//
// @Override
// public String getHostAddress(final String hostname) throws UnknownHostException {
// InetAddress address = InetAddress.getByName(hostname);
// return address.getHostAddress();
// }
// }
| import cz.tomasdvorak.eet.client.networking.InetAddressDnsResolver; | package cz.tomasdvorak.eet.client.dto;
/**
* TODO: create builder for the configuration!
*/
public class WebserviceConfiguration {
public static final long RECEIVE_TIMEOUT = 2000L;
public static final long DNS_LOOKUP_TIMEOUT = 2000L;
public static final WebserviceConfiguration DEFAULT = new WebserviceConfiguration(
RECEIVE_TIMEOUT, // timeout for webservice call in millis = 2s, required by the current laws
DNS_LOOKUP_TIMEOUT // timeout for DNS lookup in millis = 2s
);
private long receiveTimeout;
private long dnsLookupTimeout;
private DnsResolver dnsResolver;
/**
* @param receiveTimeout receiving timeout of the Webservice call in millis
*/
public WebserviceConfiguration(final long receiveTimeout) {
this(receiveTimeout, DNS_LOOKUP_TIMEOUT);
}
/**
* @param receiveTimeout receiving timeout of the Webservice call in millis
* @param dnsLookupTimeout timeout for DNS lookup in millis
*/
public WebserviceConfiguration(final long receiveTimeout, final long dnsLookupTimeout) {
this.receiveTimeout = receiveTimeout;
this.dnsLookupTimeout = dnsLookupTimeout; | // Path: src/main/java/cz/tomasdvorak/eet/client/networking/InetAddressDnsResolver.java
// public class InetAddressDnsResolver implements DnsResolver {
//
// @Override
// public String getHostAddress(final String hostname) throws UnknownHostException {
// InetAddress address = InetAddress.getByName(hostname);
// return address.getHostAddress();
// }
// }
// Path: src/main/java/cz/tomasdvorak/eet/client/dto/WebserviceConfiguration.java
import cz.tomasdvorak.eet.client.networking.InetAddressDnsResolver;
package cz.tomasdvorak.eet.client.dto;
/**
* TODO: create builder for the configuration!
*/
public class WebserviceConfiguration {
public static final long RECEIVE_TIMEOUT = 2000L;
public static final long DNS_LOOKUP_TIMEOUT = 2000L;
public static final WebserviceConfiguration DEFAULT = new WebserviceConfiguration(
RECEIVE_TIMEOUT, // timeout for webservice call in millis = 2s, required by the current laws
DNS_LOOKUP_TIMEOUT // timeout for DNS lookup in millis = 2s
);
private long receiveTimeout;
private long dnsLookupTimeout;
private DnsResolver dnsResolver;
/**
* @param receiveTimeout receiving timeout of the Webservice call in millis
*/
public WebserviceConfiguration(final long receiveTimeout) {
this(receiveTimeout, DNS_LOOKUP_TIMEOUT);
}
/**
* @param receiveTimeout receiving timeout of the Webservice call in millis
* @param dnsLookupTimeout timeout for DNS lookup in millis
*/
public WebserviceConfiguration(final long receiveTimeout, final long dnsLookupTimeout) {
this.receiveTimeout = receiveTimeout;
this.dnsLookupTimeout = dnsLookupTimeout; | this.dnsResolver = new InetAddressDnsResolver(); |
xvik/dropwizard-orient-server | src/main/java/ru/vyarus/dropwizard/orient/internal/OrientStudioInstaller.java | // Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public class StudioVirtualFolder implements OCallable<Object, String> {
//
// public static final String STUDIO_PATH = "/www/";
// public static final String STUDIO_INDEX = "index.html";
//
// @Override
// public Object call(final String iArgument) {
// final String fileName = STUDIO_PATH
// + MoreObjects.firstNonNull(Strings.emptyToNull(iArgument), STUDIO_INDEX);
// final URL url = getClass().getResource(fileName);
// if (url != null) {
// final OServerCommandGetStaticContent.OStaticContent content =
// new OServerCommandGetStaticContent.OStaticContent();
// content.is = new BufferedInputStream(getClass().getResourceAsStream(fileName));
// content.contentSize = -1;
// content.type = OServerCommandGetStaticContent.getContentType(url.getFile());
// return content;
// }
// return null;
// }
// }
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_INDEX = "index.html";
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_PATH = "/www/";
| import com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder;
import java.io.IOException;
import java.net.URL;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_INDEX;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_PATH; | package ru.vyarus.dropwizard.orient.internal;
/**
* Installs studio if studio jar is available on classpath (searches for 'www/index.html' in classpath,
* assuming it's a studio).
* Studio is available on url http://localhost:2480/studio/.
*
* @author Vyacheslav Rusakov
* @since 21.08.2015
*/
public class OrientStudioInstaller {
private final Logger logger = LoggerFactory.getLogger(OrientStudioInstaller.class);
private final OServerCommandGetStaticContent command;
public OrientStudioInstaller(final OServerCommandGetStaticContent command) {
this.command = command;
}
/**
* Searches for studio webjar and if found installs studio.
*
* @return true if studio installed, false otherwise
* @throws Exception if installation fails
*/
public boolean install() throws Exception {
final boolean detected = detect();
if (detected) {
registerStudio();
}
return detected;
}
private void registerStudio() throws Exception {
logger.debug("Registering studio application"); | // Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public class StudioVirtualFolder implements OCallable<Object, String> {
//
// public static final String STUDIO_PATH = "/www/";
// public static final String STUDIO_INDEX = "index.html";
//
// @Override
// public Object call(final String iArgument) {
// final String fileName = STUDIO_PATH
// + MoreObjects.firstNonNull(Strings.emptyToNull(iArgument), STUDIO_INDEX);
// final URL url = getClass().getResource(fileName);
// if (url != null) {
// final OServerCommandGetStaticContent.OStaticContent content =
// new OServerCommandGetStaticContent.OStaticContent();
// content.is = new BufferedInputStream(getClass().getResourceAsStream(fileName));
// content.contentSize = -1;
// content.type = OServerCommandGetStaticContent.getContentType(url.getFile());
// return content;
// }
// return null;
// }
// }
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_INDEX = "index.html";
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_PATH = "/www/";
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/OrientStudioInstaller.java
import com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder;
import java.io.IOException;
import java.net.URL;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_INDEX;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_PATH;
package ru.vyarus.dropwizard.orient.internal;
/**
* Installs studio if studio jar is available on classpath (searches for 'www/index.html' in classpath,
* assuming it's a studio).
* Studio is available on url http://localhost:2480/studio/.
*
* @author Vyacheslav Rusakov
* @since 21.08.2015
*/
public class OrientStudioInstaller {
private final Logger logger = LoggerFactory.getLogger(OrientStudioInstaller.class);
private final OServerCommandGetStaticContent command;
public OrientStudioInstaller(final OServerCommandGetStaticContent command) {
this.command = command;
}
/**
* Searches for studio webjar and if found installs studio.
*
* @return true if studio installed, false otherwise
* @throws Exception if installation fails
*/
public boolean install() throws Exception {
final boolean detected = detect();
if (detected) {
registerStudio();
}
return detected;
}
private void registerStudio() throws Exception {
logger.debug("Registering studio application"); | command.registerVirtualFolder("studio", new StudioVirtualFolder()); |
xvik/dropwizard-orient-server | src/main/java/ru/vyarus/dropwizard/orient/internal/OrientStudioInstaller.java | // Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public class StudioVirtualFolder implements OCallable<Object, String> {
//
// public static final String STUDIO_PATH = "/www/";
// public static final String STUDIO_INDEX = "index.html";
//
// @Override
// public Object call(final String iArgument) {
// final String fileName = STUDIO_PATH
// + MoreObjects.firstNonNull(Strings.emptyToNull(iArgument), STUDIO_INDEX);
// final URL url = getClass().getResource(fileName);
// if (url != null) {
// final OServerCommandGetStaticContent.OStaticContent content =
// new OServerCommandGetStaticContent.OStaticContent();
// content.is = new BufferedInputStream(getClass().getResourceAsStream(fileName));
// content.contentSize = -1;
// content.type = OServerCommandGetStaticContent.getContentType(url.getFile());
// return content;
// }
// return null;
// }
// }
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_INDEX = "index.html";
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_PATH = "/www/";
| import com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder;
import java.io.IOException;
import java.net.URL;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_INDEX;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_PATH; | package ru.vyarus.dropwizard.orient.internal;
/**
* Installs studio if studio jar is available on classpath (searches for 'www/index.html' in classpath,
* assuming it's a studio).
* Studio is available on url http://localhost:2480/studio/.
*
* @author Vyacheslav Rusakov
* @since 21.08.2015
*/
public class OrientStudioInstaller {
private final Logger logger = LoggerFactory.getLogger(OrientStudioInstaller.class);
private final OServerCommandGetStaticContent command;
public OrientStudioInstaller(final OServerCommandGetStaticContent command) {
this.command = command;
}
/**
* Searches for studio webjar and if found installs studio.
*
* @return true if studio installed, false otherwise
* @throws Exception if installation fails
*/
public boolean install() throws Exception {
final boolean detected = detect();
if (detected) {
registerStudio();
}
return detected;
}
private void registerStudio() throws Exception {
logger.debug("Registering studio application");
command.registerVirtualFolder("studio", new StudioVirtualFolder());
}
private boolean detect() throws IOException { | // Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public class StudioVirtualFolder implements OCallable<Object, String> {
//
// public static final String STUDIO_PATH = "/www/";
// public static final String STUDIO_INDEX = "index.html";
//
// @Override
// public Object call(final String iArgument) {
// final String fileName = STUDIO_PATH
// + MoreObjects.firstNonNull(Strings.emptyToNull(iArgument), STUDIO_INDEX);
// final URL url = getClass().getResource(fileName);
// if (url != null) {
// final OServerCommandGetStaticContent.OStaticContent content =
// new OServerCommandGetStaticContent.OStaticContent();
// content.is = new BufferedInputStream(getClass().getResourceAsStream(fileName));
// content.contentSize = -1;
// content.type = OServerCommandGetStaticContent.getContentType(url.getFile());
// return content;
// }
// return null;
// }
// }
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_INDEX = "index.html";
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_PATH = "/www/";
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/OrientStudioInstaller.java
import com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder;
import java.io.IOException;
import java.net.URL;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_INDEX;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_PATH;
package ru.vyarus.dropwizard.orient.internal;
/**
* Installs studio if studio jar is available on classpath (searches for 'www/index.html' in classpath,
* assuming it's a studio).
* Studio is available on url http://localhost:2480/studio/.
*
* @author Vyacheslav Rusakov
* @since 21.08.2015
*/
public class OrientStudioInstaller {
private final Logger logger = LoggerFactory.getLogger(OrientStudioInstaller.class);
private final OServerCommandGetStaticContent command;
public OrientStudioInstaller(final OServerCommandGetStaticContent command) {
this.command = command;
}
/**
* Searches for studio webjar and if found installs studio.
*
* @return true if studio installed, false otherwise
* @throws Exception if installation fails
*/
public boolean install() throws Exception {
final boolean detected = detect();
if (detected) {
registerStudio();
}
return detected;
}
private void registerStudio() throws Exception {
logger.debug("Registering studio application");
command.registerVirtualFolder("studio", new StudioVirtualFolder());
}
private boolean detect() throws IOException { | final URL studioIndex = getClass().getResource(STUDIO_PATH + STUDIO_INDEX); |
xvik/dropwizard-orient-server | src/main/java/ru/vyarus/dropwizard/orient/internal/OrientStudioInstaller.java | // Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public class StudioVirtualFolder implements OCallable<Object, String> {
//
// public static final String STUDIO_PATH = "/www/";
// public static final String STUDIO_INDEX = "index.html";
//
// @Override
// public Object call(final String iArgument) {
// final String fileName = STUDIO_PATH
// + MoreObjects.firstNonNull(Strings.emptyToNull(iArgument), STUDIO_INDEX);
// final URL url = getClass().getResource(fileName);
// if (url != null) {
// final OServerCommandGetStaticContent.OStaticContent content =
// new OServerCommandGetStaticContent.OStaticContent();
// content.is = new BufferedInputStream(getClass().getResourceAsStream(fileName));
// content.contentSize = -1;
// content.type = OServerCommandGetStaticContent.getContentType(url.getFile());
// return content;
// }
// return null;
// }
// }
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_INDEX = "index.html";
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_PATH = "/www/";
| import com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder;
import java.io.IOException;
import java.net.URL;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_INDEX;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_PATH; | package ru.vyarus.dropwizard.orient.internal;
/**
* Installs studio if studio jar is available on classpath (searches for 'www/index.html' in classpath,
* assuming it's a studio).
* Studio is available on url http://localhost:2480/studio/.
*
* @author Vyacheslav Rusakov
* @since 21.08.2015
*/
public class OrientStudioInstaller {
private final Logger logger = LoggerFactory.getLogger(OrientStudioInstaller.class);
private final OServerCommandGetStaticContent command;
public OrientStudioInstaller(final OServerCommandGetStaticContent command) {
this.command = command;
}
/**
* Searches for studio webjar and if found installs studio.
*
* @return true if studio installed, false otherwise
* @throws Exception if installation fails
*/
public boolean install() throws Exception {
final boolean detected = detect();
if (detected) {
registerStudio();
}
return detected;
}
private void registerStudio() throws Exception {
logger.debug("Registering studio application");
command.registerVirtualFolder("studio", new StudioVirtualFolder());
}
private boolean detect() throws IOException { | // Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public class StudioVirtualFolder implements OCallable<Object, String> {
//
// public static final String STUDIO_PATH = "/www/";
// public static final String STUDIO_INDEX = "index.html";
//
// @Override
// public Object call(final String iArgument) {
// final String fileName = STUDIO_PATH
// + MoreObjects.firstNonNull(Strings.emptyToNull(iArgument), STUDIO_INDEX);
// final URL url = getClass().getResource(fileName);
// if (url != null) {
// final OServerCommandGetStaticContent.OStaticContent content =
// new OServerCommandGetStaticContent.OStaticContent();
// content.is = new BufferedInputStream(getClass().getResourceAsStream(fileName));
// content.contentSize = -1;
// content.type = OServerCommandGetStaticContent.getContentType(url.getFile());
// return content;
// }
// return null;
// }
// }
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_INDEX = "index.html";
//
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/cmd/StudioVirtualFolder.java
// public static final String STUDIO_PATH = "/www/";
// Path: src/main/java/ru/vyarus/dropwizard/orient/internal/OrientStudioInstaller.java
import com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder;
import java.io.IOException;
import java.net.URL;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_INDEX;
import static ru.vyarus.dropwizard.orient.internal.cmd.StudioVirtualFolder.STUDIO_PATH;
package ru.vyarus.dropwizard.orient.internal;
/**
* Installs studio if studio jar is available on classpath (searches for 'www/index.html' in classpath,
* assuming it's a studio).
* Studio is available on url http://localhost:2480/studio/.
*
* @author Vyacheslav Rusakov
* @since 21.08.2015
*/
public class OrientStudioInstaller {
private final Logger logger = LoggerFactory.getLogger(OrientStudioInstaller.class);
private final OServerCommandGetStaticContent command;
public OrientStudioInstaller(final OServerCommandGetStaticContent command) {
this.command = command;
}
/**
* Searches for studio webjar and if found installs studio.
*
* @return true if studio installed, false otherwise
* @throws Exception if installation fails
*/
public boolean install() throws Exception {
final boolean detected = detect();
if (detected) {
registerStudio();
}
return detected;
}
private void registerStudio() throws Exception {
logger.debug("Registering studio application");
command.registerVirtualFolder("studio", new StudioVirtualFolder());
}
private boolean detect() throws IOException { | final URL studioIndex = getClass().getResource(STUDIO_PATH + STUDIO_INDEX); |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/ui/SettingUI.java | // Path: app/src/main/java/com/ubiqlog/core/ArchiveableCheck.java
// public class ArchiveableCheck {
// private IOManager ioman;
// private FileWriter writer;
// private String TAG = "ArchiveableCheck";
//
// public void checkAllfile() {
// try {
// File dir = new File(Setting.LOG_FOLDER);
// if (dir.isDirectory()) {
// Log.e(TAG, "---------YES YES IT IS DIRECTORY");
// File archFile = new File(Setting.LOG_FOLDER + "/"+ Setting.ARCH_FILE);
// writer = new FileWriter(archFile, true);
// if (!archFile.exists()) {
// archFile.createNewFile();
// }
//
// // writer.append(inArr.get(i) +
// // System.getProperty("line.separator"));
// File folder = new File(Setting.LOG_FOLDER);
// File[] listOfFiles = folder.listFiles();
// if (listOfFiles != null && listOfFiles.length > 0) {
// String[] fileNames = new String[listOfFiles.length];
// for (int i = 0; i < listOfFiles.length; i++) {
// String tmpName = listOfFiles[i].getName();
// if (!(tmpName.substring(tmpName.length() - 3,tmpName.length()).equalsIgnoreCase("txt") ||
// tmpName.substring(tmpName.length() - 3,tmpName.length()).equalsIgnoreCase("log"))) {
// String post = tmpName.substring(tmpName.length() - 3, tmpName.length());
// boolean ispreservable = false;
// for (int j = 0; j < Setting.PRESERVABLE.length; j++) {
// if (post.equalsIgnoreCase(Setting.PRESERVABLE[j])) {
// writer.append("file_name:"+ tmpName+ ", preservable:yes"+ System.getProperty("line.separator"));
// ispreservable = true;
// break;
// } else if (!(ispreservable)) {
// writer.append("file_name:"+ tmpName+ ", preservable:no"+ System.getProperty("line.separator"));
// break;
// }
// }
// }
// }
// }
// writer.flush();
// writer.close();
// writer = null;
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
| import com.ubiqlog.core.ArchiveableCheck;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView; | addView(man);
}
};
DataManagementUI.OnClosedListener dataManagementClosed = new DataManagementUI.OnClosedListener() {
//@Override
public void onClosed() {
LoadDefaultContent();
}
};
private View.OnClickListener btnNetworkListener = new View.OnClickListener() {
public void onClick(View v) {
NetworkSettingsUI man = new NetworkSettingsUI(ctx, networkSettingsClosed);
removeAllViews();
man.setPadding(10, 10, 10, 10);
addView(man);
}
};
NetworkSettingsUI.OnClosedListener networkSettingsClosed = new NetworkSettingsUI.OnClosedListener() {
public void onClosed() {
LoadDefaultContent();
}
};
private View.OnClickListener btnArchiveListener = new View.OnClickListener() {
public void onClick(View v) { | // Path: app/src/main/java/com/ubiqlog/core/ArchiveableCheck.java
// public class ArchiveableCheck {
// private IOManager ioman;
// private FileWriter writer;
// private String TAG = "ArchiveableCheck";
//
// public void checkAllfile() {
// try {
// File dir = new File(Setting.LOG_FOLDER);
// if (dir.isDirectory()) {
// Log.e(TAG, "---------YES YES IT IS DIRECTORY");
// File archFile = new File(Setting.LOG_FOLDER + "/"+ Setting.ARCH_FILE);
// writer = new FileWriter(archFile, true);
// if (!archFile.exists()) {
// archFile.createNewFile();
// }
//
// // writer.append(inArr.get(i) +
// // System.getProperty("line.separator"));
// File folder = new File(Setting.LOG_FOLDER);
// File[] listOfFiles = folder.listFiles();
// if (listOfFiles != null && listOfFiles.length > 0) {
// String[] fileNames = new String[listOfFiles.length];
// for (int i = 0; i < listOfFiles.length; i++) {
// String tmpName = listOfFiles[i].getName();
// if (!(tmpName.substring(tmpName.length() - 3,tmpName.length()).equalsIgnoreCase("txt") ||
// tmpName.substring(tmpName.length() - 3,tmpName.length()).equalsIgnoreCase("log"))) {
// String post = tmpName.substring(tmpName.length() - 3, tmpName.length());
// boolean ispreservable = false;
// for (int j = 0; j < Setting.PRESERVABLE.length; j++) {
// if (post.equalsIgnoreCase(Setting.PRESERVABLE[j])) {
// writer.append("file_name:"+ tmpName+ ", preservable:yes"+ System.getProperty("line.separator"));
// ispreservable = true;
// break;
// } else if (!(ispreservable)) {
// writer.append("file_name:"+ tmpName+ ", preservable:no"+ System.getProperty("line.separator"));
// break;
// }
// }
// }
// }
// }
// writer.flush();
// writer.close();
// writer = null;
// }
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/com/ubiqlog/ui/SettingUI.java
import com.ubiqlog.core.ArchiveableCheck;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
addView(man);
}
};
DataManagementUI.OnClosedListener dataManagementClosed = new DataManagementUI.OnClosedListener() {
//@Override
public void onClosed() {
LoadDefaultContent();
}
};
private View.OnClickListener btnNetworkListener = new View.OnClickListener() {
public void onClick(View v) {
NetworkSettingsUI man = new NetworkSettingsUI(ctx, networkSettingsClosed);
removeAllViews();
man.setPadding(10, 10, 10, 10);
addView(man);
}
};
NetworkSettingsUI.OnClosedListener networkSettingsClosed = new NetworkSettingsUI.OnClosedListener() {
public void onClosed() {
LoadDefaultContent();
}
};
private View.OnClickListener btnArchiveListener = new View.OnClickListener() {
public void onClick(View v) { | ArchiveableCheck arch = new ArchiveableCheck(); |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/extras/bluetooth/BluetoothDetectionContainer.java | // Path: app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java
// public class JsonEncodeDecode
// {
// public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
// + deviceName
// + "\",\"address\":\""
// + deviceAddress
// + "\",\"bond status\":\""
// + bindState
// + "\",\"time\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeBluetooth(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[4];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
// decodedString[3] = split[17];
//
// return decodedString;
// }
//
// public static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Movement\":{\"start\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampStart)
// + "\",\"end\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampEnd)
// + "\",\"state\":\""
// + movementState
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeMovement(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[3];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
//
// return decodedString;
// }
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
| import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import com.ubiqlog.vis.utils.JsonEncodeDecode;
import com.ubiqlog.vis.utils.SensorState.Bluetooth; | package com.ubiqlog.vis.extras.bluetooth;
/**
*
* @author Dorin Gugonatu
*
*/
public class BluetoothDetectionContainer
{
private Hashtable<String, BluetoothDetection> hashDetections;
private ArrayList<String> listDevicesAddresses;
private Calendar dateLow;
private Calendar dateHigh;
private boolean bIsEmpty;
public BluetoothDetectionContainer(Date startDate, Date endDate)
{
this.hashDetections = new Hashtable<String, BluetoothDetection>();
this.listDevicesAddresses = new ArrayList<String>();
this.dateLow = Calendar.getInstance();
this.dateLow.setTime(startDate);
this.dateHigh = Calendar.getInstance();
this.dateHigh.setTime(endDate);
this.bIsEmpty = true;
}
public void parseJsonList(String[] jsonStringList)
{
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
try
{
for (String jsonString : jsonStringList)
{ | // Path: app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java
// public class JsonEncodeDecode
// {
// public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
// + deviceName
// + "\",\"address\":\""
// + deviceAddress
// + "\",\"bond status\":\""
// + bindState
// + "\",\"time\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeBluetooth(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[4];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
// decodedString[3] = split[17];
//
// return decodedString;
// }
//
// public static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Movement\":{\"start\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampStart)
// + "\",\"end\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampEnd)
// + "\",\"state\":\""
// + movementState
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeMovement(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[3];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
//
// return decodedString;
// }
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// Path: app/src/main/java/com/ubiqlog/vis/extras/bluetooth/BluetoothDetectionContainer.java
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import com.ubiqlog.vis.utils.JsonEncodeDecode;
import com.ubiqlog.vis.utils.SensorState.Bluetooth;
package com.ubiqlog.vis.extras.bluetooth;
/**
*
* @author Dorin Gugonatu
*
*/
public class BluetoothDetectionContainer
{
private Hashtable<String, BluetoothDetection> hashDetections;
private ArrayList<String> listDevicesAddresses;
private Calendar dateLow;
private Calendar dateHigh;
private boolean bIsEmpty;
public BluetoothDetectionContainer(Date startDate, Date endDate)
{
this.hashDetections = new Hashtable<String, BluetoothDetection>();
this.listDevicesAddresses = new ArrayList<String>();
this.dateLow = Calendar.getInstance();
this.dateLow.setTime(startDate);
this.dateHigh = Calendar.getInstance();
this.dateHigh.setTime(endDate);
this.bIsEmpty = true;
}
public void parseJsonList(String[] jsonStringList)
{
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
try
{
for (String jsonString : jsonStringList)
{ | String[] jsonDecoded = JsonEncodeDecode.DecodeBluetooth(jsonString); |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/extras/bluetooth/BluetoothDetectionContainer.java | // Path: app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java
// public class JsonEncodeDecode
// {
// public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
// + deviceName
// + "\",\"address\":\""
// + deviceAddress
// + "\",\"bond status\":\""
// + bindState
// + "\",\"time\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeBluetooth(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[4];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
// decodedString[3] = split[17];
//
// return decodedString;
// }
//
// public static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Movement\":{\"start\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampStart)
// + "\",\"end\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampEnd)
// + "\",\"state\":\""
// + movementState
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeMovement(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[3];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
//
// return decodedString;
// }
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
| import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import com.ubiqlog.vis.utils.JsonEncodeDecode;
import com.ubiqlog.vis.utils.SensorState.Bluetooth; | public void parseJsonList(String[] jsonStringList)
{
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
try
{
for (String jsonString : jsonStringList)
{
String[] jsonDecoded = JsonEncodeDecode.DecodeBluetooth(jsonString);
String deviceName = jsonDecoded[0];
String deviceAddress = jsonDecoded[1];
String deviceState = jsonDecoded[2];
String timestampCurrent = jsonDecoded[3];
Calendar currentEventCalendar = (Calendar)Calendar.getInstance().clone();
currentEventCalendar.setTime(df.parse(timestampCurrent));
if ((currentEventCalendar.compareTo(dateLow) >=0) && (currentEventCalendar.compareTo(dateHigh) <= 0))
{
BluetoothDetection currentDetection;
if ((currentDetection = hashDetections.get(deviceAddress)) == null)
{
currentDetection = new BluetoothDetection(deviceName, deviceAddress);
hashDetections.put(deviceAddress, currentDetection);
listDevicesAddresses.add(deviceAddress);
}
| // Path: app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java
// public class JsonEncodeDecode
// {
// public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
// + deviceName
// + "\",\"address\":\""
// + deviceAddress
// + "\",\"bond status\":\""
// + bindState
// + "\",\"time\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeBluetooth(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[4];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
// decodedString[3] = split[17];
//
// return decodedString;
// }
//
// public static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Movement\":{\"start\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampStart)
// + "\",\"end\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampEnd)
// + "\",\"state\":\""
// + movementState
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeMovement(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[3];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
//
// return decodedString;
// }
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// Path: app/src/main/java/com/ubiqlog/vis/extras/bluetooth/BluetoothDetectionContainer.java
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import com.ubiqlog.vis.utils.JsonEncodeDecode;
import com.ubiqlog.vis.utils.SensorState.Bluetooth;
public void parseJsonList(String[] jsonStringList)
{
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
try
{
for (String jsonString : jsonStringList)
{
String[] jsonDecoded = JsonEncodeDecode.DecodeBluetooth(jsonString);
String deviceName = jsonDecoded[0];
String deviceAddress = jsonDecoded[1];
String deviceState = jsonDecoded[2];
String timestampCurrent = jsonDecoded[3];
Calendar currentEventCalendar = (Calendar)Calendar.getInstance().clone();
currentEventCalendar.setTime(df.parse(timestampCurrent));
if ((currentEventCalendar.compareTo(dateLow) >=0) && (currentEventCalendar.compareTo(dateHigh) <= 0))
{
BluetoothDetection currentDetection;
if ((currentDetection = hashDetections.get(deviceAddress)) == null)
{
currentDetection = new BluetoothDetection(deviceName, deviceAddress);
hashDetections.put(deviceAddress, currentDetection);
listDevicesAddresses.add(deviceAddress);
}
| Bluetooth bluetoothState = Bluetooth.valueOf(deviceState.toUpperCase()); |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/sensors/ActivityRecognitionScan.java | // Path: app/src/main/java/com/ubiqlog/utils/IOManager.java
// public class IOManager {
// String datenow = new String();
// private String currentFileName = new String();
// private String strPath;
//
// public IOManager() {
// this.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Setting.DEFAULT_FOLDER;
// }
//
// public IOManager(String filename, String homeFolder) {
// this.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + homeFolder;
// this.currentFileName = filename;
// }
//
// public String getPath() {
// return strPath;
// }
//
// public String getCurrentFilename() {
// return currentFileName + ".txt";
// }
//
//
//
// public void logData(ArrayList<String> inArr) {
// FileWriter writer;
// datenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());
// SimpleDateFormat dateformat = new SimpleDateFormat("M-d-yyyy");
// //datenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());
// //datenow = datenow.replace("/", "-");
// try {
// File logFile = new File(Setting.Instance(null).getLogFolder() + "/" + "log_" + dateformat.format(new Date()) + ".txt"); //datenow+ ".txt");
// writer = new FileWriter(logFile, true);
// if (!logFile.exists()) {
// logFile.createNewFile();
// }
// Iterator<String> it = inArr.iterator();
// while (it.hasNext()) {
// String aaa = it.next();
// writer.append(aaa+ System.getProperty("line.separator"));
// }
// writer.flush();
// writer.close();
// writer = null;
//
// } catch (Exception e) {
//
// Log.e("DataAggregator", "--------Failed to write in a file-----" + e.getMessage() + "; Stack: " + Log.getStackTraceString(e));
//
// }
// }
//
//
// // Added by AP
// // Uses a file name passed into the IOManager
// public boolean logData(DataAcquisitor dataAcq, boolean append) {
// if (dataAcq.getDataBuffer().size() <= 0) {
// return false;
// }
// //File dirs = new File(getPath() + dataAcq.getFolderName());
// File dirs = new File(getPath());
// if (!dirs.exists()) {
// dirs.mkdirs();
// }
//
// String fileName = Setting.filenameFormat.format(new Date()) + "_" + getCurrentFilename();
// File logFile = new File(dirs, fileName);
// try {
// FileWriter writer = new FileWriter(logFile, append);
// for (String s : dataAcq.getDataBuffer()) {
// writer.append(s + System.getProperty("line.separator"));
// }
// writer.flush();
// writer.close();
// return true;
//
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// }
//
// public void logError(String msg) {
// PrintWriter printWr;
// Date a = new Date (System.currentTimeMillis());
// String errorDate = a.getDate()+"-"+a.getMonth()+"-"+a.getYear();
// File errorFile = new File(Setting.Instance(null).getLogFolder(), "error_"+errorDate+".txt");
// try {
// printWr = new PrintWriter(new FileWriter(errorFile, true));
// printWr.append(msg + System.getProperty("line.separator"));
// printWr.flush();
// printWr.close();
// printWr = null;
// } catch (Exception ex) {
// Log.e("IOManager.logError", ex.getMessage(), ex);
// }
// }
//
// }
| import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.ActivityRecognition;
import com.ubiqlog.utils.IOManager; | package com.ubiqlog.sensors;
//import com.google.android.gms.common.GooglePlayServicesClient;
//import com.google.android.gms.location.ActivityRecognitionClient;
/**
* check this sample:
* https://github.com/diegofigueroa/activity-recognition-sample/blob/master/eclipse/activity-recognition-practice/src/com/example/arp/ActivityRecognitionManager.java
* @author rr4874
*
*/
public class ActivityRecognitionScan implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
| // Path: app/src/main/java/com/ubiqlog/utils/IOManager.java
// public class IOManager {
// String datenow = new String();
// private String currentFileName = new String();
// private String strPath;
//
// public IOManager() {
// this.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Setting.DEFAULT_FOLDER;
// }
//
// public IOManager(String filename, String homeFolder) {
// this.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + homeFolder;
// this.currentFileName = filename;
// }
//
// public String getPath() {
// return strPath;
// }
//
// public String getCurrentFilename() {
// return currentFileName + ".txt";
// }
//
//
//
// public void logData(ArrayList<String> inArr) {
// FileWriter writer;
// datenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());
// SimpleDateFormat dateformat = new SimpleDateFormat("M-d-yyyy");
// //datenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());
// //datenow = datenow.replace("/", "-");
// try {
// File logFile = new File(Setting.Instance(null).getLogFolder() + "/" + "log_" + dateformat.format(new Date()) + ".txt"); //datenow+ ".txt");
// writer = new FileWriter(logFile, true);
// if (!logFile.exists()) {
// logFile.createNewFile();
// }
// Iterator<String> it = inArr.iterator();
// while (it.hasNext()) {
// String aaa = it.next();
// writer.append(aaa+ System.getProperty("line.separator"));
// }
// writer.flush();
// writer.close();
// writer = null;
//
// } catch (Exception e) {
//
// Log.e("DataAggregator", "--------Failed to write in a file-----" + e.getMessage() + "; Stack: " + Log.getStackTraceString(e));
//
// }
// }
//
//
// // Added by AP
// // Uses a file name passed into the IOManager
// public boolean logData(DataAcquisitor dataAcq, boolean append) {
// if (dataAcq.getDataBuffer().size() <= 0) {
// return false;
// }
// //File dirs = new File(getPath() + dataAcq.getFolderName());
// File dirs = new File(getPath());
// if (!dirs.exists()) {
// dirs.mkdirs();
// }
//
// String fileName = Setting.filenameFormat.format(new Date()) + "_" + getCurrentFilename();
// File logFile = new File(dirs, fileName);
// try {
// FileWriter writer = new FileWriter(logFile, append);
// for (String s : dataAcq.getDataBuffer()) {
// writer.append(s + System.getProperty("line.separator"));
// }
// writer.flush();
// writer.close();
// return true;
//
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// }
//
// public void logError(String msg) {
// PrintWriter printWr;
// Date a = new Date (System.currentTimeMillis());
// String errorDate = a.getDate()+"-"+a.getMonth()+"-"+a.getYear();
// File errorFile = new File(Setting.Instance(null).getLogFolder(), "error_"+errorDate+".txt");
// try {
// printWr = new PrintWriter(new FileWriter(errorFile, true));
// printWr.append(msg + System.getProperty("line.separator"));
// printWr.flush();
// printWr.close();
// printWr = null;
// } catch (Exception ex) {
// Log.e("IOManager.logError", ex.getMessage(), ex);
// }
// }
//
// }
// Path: app/src/main/java/com/ubiqlog/sensors/ActivityRecognitionScan.java
import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.ActivityRecognition;
import com.ubiqlog.utils.IOManager;
package com.ubiqlog.sensors;
//import com.google.android.gms.common.GooglePlayServicesClient;
//import com.google.android.gms.location.ActivityRecognitionClient;
/**
* check this sample:
* https://github.com/diegofigueroa/activity-recognition-sample/blob/master/eclipse/activity-recognition-practice/src/com/example/arp/ActivityRecognitionManager.java
* @author rr4874
*
*/
public class ActivityRecognitionScan implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
| IOManager ioerror = new IOManager(); // to log error |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/core/DataAcquisitor.java | // Path: app/src/main/java/com/ubiqlog/utils/IOManager.java
// public class IOManager {
// String datenow = new String();
// private String currentFileName = new String();
// private String strPath;
//
// public IOManager() {
// this.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Setting.DEFAULT_FOLDER;
// }
//
// public IOManager(String filename, String homeFolder) {
// this.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + homeFolder;
// this.currentFileName = filename;
// }
//
// public String getPath() {
// return strPath;
// }
//
// public String getCurrentFilename() {
// return currentFileName + ".txt";
// }
//
//
//
// public void logData(ArrayList<String> inArr) {
// FileWriter writer;
// datenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());
// SimpleDateFormat dateformat = new SimpleDateFormat("M-d-yyyy");
// //datenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());
// //datenow = datenow.replace("/", "-");
// try {
// File logFile = new File(Setting.Instance(null).getLogFolder() + "/" + "log_" + dateformat.format(new Date()) + ".txt"); //datenow+ ".txt");
// writer = new FileWriter(logFile, true);
// if (!logFile.exists()) {
// logFile.createNewFile();
// }
// Iterator<String> it = inArr.iterator();
// while (it.hasNext()) {
// String aaa = it.next();
// writer.append(aaa+ System.getProperty("line.separator"));
// }
// writer.flush();
// writer.close();
// writer = null;
//
// } catch (Exception e) {
//
// Log.e("DataAggregator", "--------Failed to write in a file-----" + e.getMessage() + "; Stack: " + Log.getStackTraceString(e));
//
// }
// }
//
//
// // Added by AP
// // Uses a file name passed into the IOManager
// public boolean logData(DataAcquisitor dataAcq, boolean append) {
// if (dataAcq.getDataBuffer().size() <= 0) {
// return false;
// }
// //File dirs = new File(getPath() + dataAcq.getFolderName());
// File dirs = new File(getPath());
// if (!dirs.exists()) {
// dirs.mkdirs();
// }
//
// String fileName = Setting.filenameFormat.format(new Date()) + "_" + getCurrentFilename();
// File logFile = new File(dirs, fileName);
// try {
// FileWriter writer = new FileWriter(logFile, append);
// for (String s : dataAcq.getDataBuffer()) {
// writer.append(s + System.getProperty("line.separator"));
// }
// writer.flush();
// writer.close();
// return true;
//
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// }
//
// public void logError(String msg) {
// PrintWriter printWr;
// Date a = new Date (System.currentTimeMillis());
// String errorDate = a.getDate()+"-"+a.getMonth()+"-"+a.getYear();
// File errorFile = new File(Setting.Instance(null).getLogFolder(), "error_"+errorDate+".txt");
// try {
// printWr = new PrintWriter(new FileWriter(errorFile, true));
// printWr.append(msg + System.getProperty("line.separator"));
// printWr.flush();
// printWr.close();
// printWr = null;
// } catch (Exception ex) {
// Log.e("IOManager.logError", ex.getMessage(), ex);
// }
// }
//
// }
| import com.ubiqlog.utils.IOManager;
import java.util.ArrayList; | public DataAcquisitor(String folderName, String fileName) {
//this.context = context;
this.folderName = folderName;
dataBuffer = new ArrayList<String>();
this.fileName = fileName;
}
public void removeData(Long timeinms) {
}
public ArrayList<String> getDataBuffer() {
return dataBuffer;
}
public String getCurrrentFileName() {
return fileName;
}
public void insert(String s, boolean append, int maxBuffSize) {
//Log.d(LOG_TAG, "Inserting into dBuff");
dataBuffer.add(s);
if (dataBuffer.size() >= maxBuffSize) {
flush(append);
}
}
public void flush(boolean append) {
//Log.d(LOG_TAG, "Flushing buffer" + this.getFolderName()); | // Path: app/src/main/java/com/ubiqlog/utils/IOManager.java
// public class IOManager {
// String datenow = new String();
// private String currentFileName = new String();
// private String strPath;
//
// public IOManager() {
// this.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Setting.DEFAULT_FOLDER;
// }
//
// public IOManager(String filename, String homeFolder) {
// this.strPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + homeFolder;
// this.currentFileName = filename;
// }
//
// public String getPath() {
// return strPath;
// }
//
// public String getCurrentFilename() {
// return currentFileName + ".txt";
// }
//
//
//
// public void logData(ArrayList<String> inArr) {
// FileWriter writer;
// datenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());
// SimpleDateFormat dateformat = new SimpleDateFormat("M-d-yyyy");
// //datenow = DateFormat.getDateInstance(DateFormat.SHORT).format(System.currentTimeMillis());
// //datenow = datenow.replace("/", "-");
// try {
// File logFile = new File(Setting.Instance(null).getLogFolder() + "/" + "log_" + dateformat.format(new Date()) + ".txt"); //datenow+ ".txt");
// writer = new FileWriter(logFile, true);
// if (!logFile.exists()) {
// logFile.createNewFile();
// }
// Iterator<String> it = inArr.iterator();
// while (it.hasNext()) {
// String aaa = it.next();
// writer.append(aaa+ System.getProperty("line.separator"));
// }
// writer.flush();
// writer.close();
// writer = null;
//
// } catch (Exception e) {
//
// Log.e("DataAggregator", "--------Failed to write in a file-----" + e.getMessage() + "; Stack: " + Log.getStackTraceString(e));
//
// }
// }
//
//
// // Added by AP
// // Uses a file name passed into the IOManager
// public boolean logData(DataAcquisitor dataAcq, boolean append) {
// if (dataAcq.getDataBuffer().size() <= 0) {
// return false;
// }
// //File dirs = new File(getPath() + dataAcq.getFolderName());
// File dirs = new File(getPath());
// if (!dirs.exists()) {
// dirs.mkdirs();
// }
//
// String fileName = Setting.filenameFormat.format(new Date()) + "_" + getCurrentFilename();
// File logFile = new File(dirs, fileName);
// try {
// FileWriter writer = new FileWriter(logFile, append);
// for (String s : dataAcq.getDataBuffer()) {
// writer.append(s + System.getProperty("line.separator"));
// }
// writer.flush();
// writer.close();
// return true;
//
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// }
//
// public void logError(String msg) {
// PrintWriter printWr;
// Date a = new Date (System.currentTimeMillis());
// String errorDate = a.getDate()+"-"+a.getMonth()+"-"+a.getYear();
// File errorFile = new File(Setting.Instance(null).getLogFolder(), "error_"+errorDate+".txt");
// try {
// printWr = new PrintWriter(new FileWriter(errorFile, true));
// printWr.append(msg + System.getProperty("line.separator"));
// printWr.flush();
// printWr.close();
// printWr = null;
// } catch (Exception ex) {
// Log.e("IOManager.logError", ex.getMessage(), ex);
// }
// }
//
// }
// Path: app/src/main/java/com/ubiqlog/core/DataAcquisitor.java
import com.ubiqlog.utils.IOManager;
import java.util.ArrayList;
public DataAcquisitor(String folderName, String fileName) {
//this.context = context;
this.folderName = folderName;
dataBuffer = new ArrayList<String>();
this.fileName = fileName;
}
public void removeData(Long timeinms) {
}
public ArrayList<String> getDataBuffer() {
return dataBuffer;
}
public String getCurrrentFileName() {
return fileName;
}
public void insert(String s, boolean append, int maxBuffSize) {
//Log.d(LOG_TAG, "Inserting into dBuff");
dataBuffer.add(s);
if (dataBuffer.size() >= maxBuffSize) {
flush(append);
}
}
public void flush(boolean append) {
//Log.d(LOG_TAG, "Flushing buffer" + this.getFolderName()); | IOManager dataLogger = new IOManager(getCurrrentFileName(), getFolderName()); |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/ui/extras/movement/MovementLogScrollView.java | // Path: app/src/main/java/com/ubiqlog/vis/common/IZoomNotification.java
// public interface IZoomNotification
// {
// public void viewZoomIn(float left, float right);
// public void viewZoomOut(float left, float right);
//
// public void doZoom(float fScale);
//
// public void viewClearZoom();
// }
| import com.ubiqlog.vis.common.IZoomNotification;
import android.content.Context;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView; | package com.ubiqlog.vis.ui.extras.movement;
/**
*
* @author Dorin Gugonatu
*
*/
public class MovementLogScrollView extends HorizontalScrollView
{
private boolean bIsZooming;
private float fZoomInOldDistance;
private float fZoomScale; | // Path: app/src/main/java/com/ubiqlog/vis/common/IZoomNotification.java
// public interface IZoomNotification
// {
// public void viewZoomIn(float left, float right);
// public void viewZoomOut(float left, float right);
//
// public void doZoom(float fScale);
//
// public void viewClearZoom();
// }
// Path: app/src/main/java/com/ubiqlog/vis/ui/extras/movement/MovementLogScrollView.java
import com.ubiqlog.vis.common.IZoomNotification;
import android.content.Context;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
package com.ubiqlog.vis.ui.extras.movement;
/**
*
* @author Dorin Gugonatu
*
*/
public class MovementLogScrollView extends HorizontalScrollView
{
private boolean bIsZooming;
private float fZoomInOldDistance;
private float fZoomScale; | private IZoomNotification zoomNotification; |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/ui/extras/DateTimeSelector/DateTimeIntervalSelector.java | // Path: app/src/main/java/com/ubiqlog/vis/ui/extras/DateTimeSelector/DateTimePickerDialog.java
// public enum Type {
// DATE, TIME, DATETIME
// }
| import java.util.Date;
import android.R.drawable;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.ImageView.ScaleType;
import com.ubiqlog.vis.ui.extras.DateTimeSelector.DateTimePickerDialog.Type; | package com.ubiqlog.vis.ui.extras.DateTimeSelector;
/**
* A simple framelayout that lets the user select a datetime interval.
*
* @author Victor Gugonatu
* @date 10.2010
* @version 1.0
*/
public class DateTimeIntervalSelector extends FrameLayout {
/**
* The callback used to indicate that the data has been changed.
*/
public interface OnDataChangedListener {
public abstract void onDataChanged(Date startDate, Date endDate, | // Path: app/src/main/java/com/ubiqlog/vis/ui/extras/DateTimeSelector/DateTimePickerDialog.java
// public enum Type {
// DATE, TIME, DATETIME
// }
// Path: app/src/main/java/com/ubiqlog/vis/ui/extras/DateTimeSelector/DateTimeIntervalSelector.java
import java.util.Date;
import android.R.drawable;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.ImageView.ScaleType;
import com.ubiqlog.vis.ui.extras.DateTimeSelector.DateTimePickerDialog.Type;
package com.ubiqlog.vis.ui.extras.DateTimeSelector;
/**
* A simple framelayout that lets the user select a datetime interval.
*
* @author Victor Gugonatu
* @date 10.2010
* @version 1.0
*/
public class DateTimeIntervalSelector extends FrameLayout {
/**
* The callback used to indicate that the data has been changed.
*/
public interface OnDataChangedListener {
public abstract void onDataChanged(Date startDate, Date endDate, | Type type); |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/ui/extras/bluetooth/BluetoothLogDataLayout.java | // Path: app/src/main/java/com/ubiqlog/vis/extras/bluetooth/BluetoothDetectionContainer.java
// public class BluetoothDetectionContainer
// {
// private Hashtable<String, BluetoothDetection> hashDetections;
// private ArrayList<String> listDevicesAddresses;
//
// private Calendar dateLow;
// private Calendar dateHigh;
// private boolean bIsEmpty;
//
// public BluetoothDetectionContainer(Date startDate, Date endDate)
// {
// this.hashDetections = new Hashtable<String, BluetoothDetection>();
// this.listDevicesAddresses = new ArrayList<String>();
//
// this.dateLow = Calendar.getInstance();
// this.dateLow.setTime(startDate);
// this.dateHigh = Calendar.getInstance();
// this.dateHigh.setTime(endDate);
// this.bIsEmpty = true;
// }
//
// public void parseJsonList(String[] jsonStringList)
// {
// DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
//
// try
// {
// for (String jsonString : jsonStringList)
// {
// String[] jsonDecoded = JsonEncodeDecode.DecodeBluetooth(jsonString);
//
// String deviceName = jsonDecoded[0];
// String deviceAddress = jsonDecoded[1];
// String deviceState = jsonDecoded[2];
// String timestampCurrent = jsonDecoded[3];
//
// Calendar currentEventCalendar = (Calendar)Calendar.getInstance().clone();
//
// currentEventCalendar.setTime(df.parse(timestampCurrent));
//
// if ((currentEventCalendar.compareTo(dateLow) >=0) && (currentEventCalendar.compareTo(dateHigh) <= 0))
// {
// BluetoothDetection currentDetection;
//
// if ((currentDetection = hashDetections.get(deviceAddress)) == null)
// {
// currentDetection = new BluetoothDetection(deviceName, deviceAddress);
// hashDetections.put(deviceAddress, currentDetection);
// listDevicesAddresses.add(deviceAddress);
// }
//
// Bluetooth bluetoothState = Bluetooth.valueOf(deviceState.toUpperCase());
//
// currentDetection.InsertDetection(currentEventCalendar.getTime().getTime() - dateLow.getTime().getTime(), bluetoothState);
//
// if (bIsEmpty)
// {
// bIsEmpty = !bIsEmpty;
// }
// }
// }
// }
// catch (Exception ex)
// {
// }
// }
//
// public ArrayList<Long> getAllDetectionDates(String deviceAddress, Bluetooth deviceState)
// {
// return hashDetections.get(deviceAddress).getDetectionDates(deviceState);
// }
//
// public int getNumberOfDevices()
// {
// return listDevicesAddresses.size();
// }
//
// public ArrayList<BluetoothDetection> getAllDevicesDetections()
// {
// ArrayList<BluetoothDetection> toReturn = new ArrayList<BluetoothDetection>();
//
// for (BluetoothDetection bluetoothDetection : hashDetections.values())
// {
// toReturn.add(bluetoothDetection);
// }
//
// return toReturn;
// }
//
// public Calendar getLowestDate()
// {
// return this.dateLow;
// }
//
// public Calendar getHighestDate()
// {
// return this.dateHigh;
// }
// }
| import com.ubiqlog.vis.extras.bluetooth.BluetoothDetectionContainer;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.LinearLayout; | package com.ubiqlog.vis.ui.extras.bluetooth;
/**
*
* @author Dorin Gugonatu
*
*/
public class BluetoothLogDataLayout extends LinearLayout
{
private BluetoothLogHorizontalScrollView bluetoothHorizontalScrollView;
private BluetoothLogVerticalScrollView bluetoothVerticalScrollView;
private BluetoothLogDataView bluetoothLogDataView;
private BluetoothLogDevicesView bluetoothLogDevicesView;
public BluetoothLogDataLayout(Context context)
{
super(context);
this.setOrientation(LinearLayout.HORIZONTAL);
bluetoothHorizontalScrollView = new BluetoothLogHorizontalScrollView(context);
bluetoothLogDataView = new BluetoothLogDataView(context, 100, 100);
bluetoothHorizontalScrollView.addView(bluetoothLogDataView);
bluetoothHorizontalScrollView.addZoomNotificationListener(bluetoothLogDataView);
bluetoothVerticalScrollView = new BluetoothLogVerticalScrollView(context);
bluetoothLogDevicesView = new BluetoothLogDevicesView(context, bluetoothLogDataView);
bluetoothVerticalScrollView.addView(bluetoothLogDevicesView);
bluetoothVerticalScrollView.setPadding(0, 100, 0, 100);
addView(bluetoothVerticalScrollView);
addView(bluetoothHorizontalScrollView);
}
| // Path: app/src/main/java/com/ubiqlog/vis/extras/bluetooth/BluetoothDetectionContainer.java
// public class BluetoothDetectionContainer
// {
// private Hashtable<String, BluetoothDetection> hashDetections;
// private ArrayList<String> listDevicesAddresses;
//
// private Calendar dateLow;
// private Calendar dateHigh;
// private boolean bIsEmpty;
//
// public BluetoothDetectionContainer(Date startDate, Date endDate)
// {
// this.hashDetections = new Hashtable<String, BluetoothDetection>();
// this.listDevicesAddresses = new ArrayList<String>();
//
// this.dateLow = Calendar.getInstance();
// this.dateLow.setTime(startDate);
// this.dateHigh = Calendar.getInstance();
// this.dateHigh.setTime(endDate);
// this.bIsEmpty = true;
// }
//
// public void parseJsonList(String[] jsonStringList)
// {
// DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
//
// try
// {
// for (String jsonString : jsonStringList)
// {
// String[] jsonDecoded = JsonEncodeDecode.DecodeBluetooth(jsonString);
//
// String deviceName = jsonDecoded[0];
// String deviceAddress = jsonDecoded[1];
// String deviceState = jsonDecoded[2];
// String timestampCurrent = jsonDecoded[3];
//
// Calendar currentEventCalendar = (Calendar)Calendar.getInstance().clone();
//
// currentEventCalendar.setTime(df.parse(timestampCurrent));
//
// if ((currentEventCalendar.compareTo(dateLow) >=0) && (currentEventCalendar.compareTo(dateHigh) <= 0))
// {
// BluetoothDetection currentDetection;
//
// if ((currentDetection = hashDetections.get(deviceAddress)) == null)
// {
// currentDetection = new BluetoothDetection(deviceName, deviceAddress);
// hashDetections.put(deviceAddress, currentDetection);
// listDevicesAddresses.add(deviceAddress);
// }
//
// Bluetooth bluetoothState = Bluetooth.valueOf(deviceState.toUpperCase());
//
// currentDetection.InsertDetection(currentEventCalendar.getTime().getTime() - dateLow.getTime().getTime(), bluetoothState);
//
// if (bIsEmpty)
// {
// bIsEmpty = !bIsEmpty;
// }
// }
// }
// }
// catch (Exception ex)
// {
// }
// }
//
// public ArrayList<Long> getAllDetectionDates(String deviceAddress, Bluetooth deviceState)
// {
// return hashDetections.get(deviceAddress).getDetectionDates(deviceState);
// }
//
// public int getNumberOfDevices()
// {
// return listDevicesAddresses.size();
// }
//
// public ArrayList<BluetoothDetection> getAllDevicesDetections()
// {
// ArrayList<BluetoothDetection> toReturn = new ArrayList<BluetoothDetection>();
//
// for (BluetoothDetection bluetoothDetection : hashDetections.values())
// {
// toReturn.add(bluetoothDetection);
// }
//
// return toReturn;
// }
//
// public Calendar getLowestDate()
// {
// return this.dateLow;
// }
//
// public Calendar getHighestDate()
// {
// return this.dateHigh;
// }
// }
// Path: app/src/main/java/com/ubiqlog/vis/ui/extras/bluetooth/BluetoothLogDataLayout.java
import com.ubiqlog.vis.extras.bluetooth.BluetoothDetectionContainer;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.LinearLayout;
package com.ubiqlog.vis.ui.extras.bluetooth;
/**
*
* @author Dorin Gugonatu
*
*/
public class BluetoothLogDataLayout extends LinearLayout
{
private BluetoothLogHorizontalScrollView bluetoothHorizontalScrollView;
private BluetoothLogVerticalScrollView bluetoothVerticalScrollView;
private BluetoothLogDataView bluetoothLogDataView;
private BluetoothLogDevicesView bluetoothLogDevicesView;
public BluetoothLogDataLayout(Context context)
{
super(context);
this.setOrientation(LinearLayout.HORIZONTAL);
bluetoothHorizontalScrollView = new BluetoothLogHorizontalScrollView(context);
bluetoothLogDataView = new BluetoothLogDataView(context, 100, 100);
bluetoothHorizontalScrollView.addView(bluetoothLogDataView);
bluetoothHorizontalScrollView.addZoomNotificationListener(bluetoothLogDataView);
bluetoothVerticalScrollView = new BluetoothLogVerticalScrollView(context);
bluetoothLogDevicesView = new BluetoothLogDevicesView(context, bluetoothLogDataView);
bluetoothVerticalScrollView.addView(bluetoothLogDevicesView);
bluetoothVerticalScrollView.setPadding(0, 100, 0, 100);
addView(bluetoothVerticalScrollView);
addView(bluetoothHorizontalScrollView);
}
| public void setData(BluetoothDetectionContainer bluetoothContainer) |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/extras/search/Searcher.java | // Path: app/src/main/java/com/ubiqlog/vis/common/Settings.java
// public class Settings {
//
// public static final String googleMapKey = "0U0FROSv7CVVKcfYcZY_7wDf4OBYAgX9HsueySA";
// public static final String PREF_FILE_NAME = "UbiqlogVisPrefFile";
// public static final String LOG_FOLDER = Setting.LOG_FOLDER;
// public static final String SensorLocation = "Location";
// public static final String SensorApplication = "Application";
// public static final String SensorCall = "Call";
// public static final String SensorSms = "SMS";
// public static final int application_timeinterval = 11000;
//
// public static int location_timeFrame = 5000;
// public static int call_timeFrame = 5000;
// public static int sms_timeFrame = 5000;
//
// // Initialize preferences (from pref file or default)
// public static void initialise(Context context) {
// SharedPreferences settings = context.getSharedPreferences(
// PREF_FILE_NAME, 0);
// location_timeFrame = settings.getInt("location_timeFrame",
// location_timeFrame);
// call_timeFrame = settings.getInt("call_timeFrame", call_timeFrame);
// sms_timeFrame = settings.getInt("sms_timeFrame", sms_timeFrame);
// }
//
// // save preferences in pref file
// public static void savePreferences(Context context,
// int _location_timeFrame, int _call_timeFrame, int _sms_timeFrame) {
// SharedPreferences settings = context.getSharedPreferences(
// PREF_FILE_NAME, 0);
// SharedPreferences.Editor editor = settings.edit();
//
// location_timeFrame = _location_timeFrame;
// call_timeFrame = _call_timeFrame;
// sms_timeFrame = _sms_timeFrame;
//
// editor.putInt("location_timeFrame", _location_timeFrame);
// editor.putInt("call_timeFrame", _call_timeFrame);
// editor.putInt("sms_timeFrame", _sms_timeFrame);
//
// // Commit the edits!
// editor.commit();
//
// }
//
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/UserFriendlyException.java
// public class UserFriendlyException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserFriendlyException(String message) {
// super(message);
// }
//
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.content.Context;
import com.ubiqlog.ui.R;
import com.ubiqlog.vis.common.Settings;
import com.ubiqlog.vis.utils.UserFriendlyException; | package com.ubiqlog.vis.extras.search;
/**
* @author Soheil KHOSRAVIPOUR
* @modified by Victor Gugonatu
* @modified on 12.2010
* @date 07.2010
* @version 1.0
*/
public class Searcher {
// This function receives sensor, and address of the file and returns the
// search results in an array list
public ArrayList<String> searchFile(String sensor, String fileAddress) {
FileInputStream in;
ArrayList<String> result = new ArrayList<String>(); // The Result array list
try {
in = new FileInputStream(new File(fileAddress));
} catch (FileNotFoundException e) {
// file not found -> ignore
return new ArrayList<String>();
}
InputStreamReader inputreader = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, one line at the
// time
try {
while ((line = buffreader.readLine()) != null) {
if (line.startsWith("{\"" + sensor) || line.startsWith("\"" + sensor)) {
// Found a record
result.add(line);
}
}
} catch (IOException e) {
// ignore
}
return result;
}
// This function receives a sensor, dates and creates address of the files
// and returns the search results using searchFile
public ArrayList<String> searchFolder(String sensor, String date1,String date2, Context _context) | // Path: app/src/main/java/com/ubiqlog/vis/common/Settings.java
// public class Settings {
//
// public static final String googleMapKey = "0U0FROSv7CVVKcfYcZY_7wDf4OBYAgX9HsueySA";
// public static final String PREF_FILE_NAME = "UbiqlogVisPrefFile";
// public static final String LOG_FOLDER = Setting.LOG_FOLDER;
// public static final String SensorLocation = "Location";
// public static final String SensorApplication = "Application";
// public static final String SensorCall = "Call";
// public static final String SensorSms = "SMS";
// public static final int application_timeinterval = 11000;
//
// public static int location_timeFrame = 5000;
// public static int call_timeFrame = 5000;
// public static int sms_timeFrame = 5000;
//
// // Initialize preferences (from pref file or default)
// public static void initialise(Context context) {
// SharedPreferences settings = context.getSharedPreferences(
// PREF_FILE_NAME, 0);
// location_timeFrame = settings.getInt("location_timeFrame",
// location_timeFrame);
// call_timeFrame = settings.getInt("call_timeFrame", call_timeFrame);
// sms_timeFrame = settings.getInt("sms_timeFrame", sms_timeFrame);
// }
//
// // save preferences in pref file
// public static void savePreferences(Context context,
// int _location_timeFrame, int _call_timeFrame, int _sms_timeFrame) {
// SharedPreferences settings = context.getSharedPreferences(
// PREF_FILE_NAME, 0);
// SharedPreferences.Editor editor = settings.edit();
//
// location_timeFrame = _location_timeFrame;
// call_timeFrame = _call_timeFrame;
// sms_timeFrame = _sms_timeFrame;
//
// editor.putInt("location_timeFrame", _location_timeFrame);
// editor.putInt("call_timeFrame", _call_timeFrame);
// editor.putInt("sms_timeFrame", _sms_timeFrame);
//
// // Commit the edits!
// editor.commit();
//
// }
//
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/UserFriendlyException.java
// public class UserFriendlyException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserFriendlyException(String message) {
// super(message);
// }
//
// }
// Path: app/src/main/java/com/ubiqlog/vis/extras/search/Searcher.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.content.Context;
import com.ubiqlog.ui.R;
import com.ubiqlog.vis.common.Settings;
import com.ubiqlog.vis.utils.UserFriendlyException;
package com.ubiqlog.vis.extras.search;
/**
* @author Soheil KHOSRAVIPOUR
* @modified by Victor Gugonatu
* @modified on 12.2010
* @date 07.2010
* @version 1.0
*/
public class Searcher {
// This function receives sensor, and address of the file and returns the
// search results in an array list
public ArrayList<String> searchFile(String sensor, String fileAddress) {
FileInputStream in;
ArrayList<String> result = new ArrayList<String>(); // The Result array list
try {
in = new FileInputStream(new File(fileAddress));
} catch (FileNotFoundException e) {
// file not found -> ignore
return new ArrayList<String>();
}
InputStreamReader inputreader = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, one line at the
// time
try {
while ((line = buffreader.readLine()) != null) {
if (line.startsWith("{\"" + sensor) || line.startsWith("\"" + sensor)) {
// Found a record
result.add(line);
}
}
} catch (IOException e) {
// ignore
}
return result;
}
// This function receives a sensor, dates and creates address of the files
// and returns the search results using searchFile
public ArrayList<String> searchFolder(String sensor, String date1,String date2, Context _context) | throws UserFriendlyException { |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/extras/search/Searcher.java | // Path: app/src/main/java/com/ubiqlog/vis/common/Settings.java
// public class Settings {
//
// public static final String googleMapKey = "0U0FROSv7CVVKcfYcZY_7wDf4OBYAgX9HsueySA";
// public static final String PREF_FILE_NAME = "UbiqlogVisPrefFile";
// public static final String LOG_FOLDER = Setting.LOG_FOLDER;
// public static final String SensorLocation = "Location";
// public static final String SensorApplication = "Application";
// public static final String SensorCall = "Call";
// public static final String SensorSms = "SMS";
// public static final int application_timeinterval = 11000;
//
// public static int location_timeFrame = 5000;
// public static int call_timeFrame = 5000;
// public static int sms_timeFrame = 5000;
//
// // Initialize preferences (from pref file or default)
// public static void initialise(Context context) {
// SharedPreferences settings = context.getSharedPreferences(
// PREF_FILE_NAME, 0);
// location_timeFrame = settings.getInt("location_timeFrame",
// location_timeFrame);
// call_timeFrame = settings.getInt("call_timeFrame", call_timeFrame);
// sms_timeFrame = settings.getInt("sms_timeFrame", sms_timeFrame);
// }
//
// // save preferences in pref file
// public static void savePreferences(Context context,
// int _location_timeFrame, int _call_timeFrame, int _sms_timeFrame) {
// SharedPreferences settings = context.getSharedPreferences(
// PREF_FILE_NAME, 0);
// SharedPreferences.Editor editor = settings.edit();
//
// location_timeFrame = _location_timeFrame;
// call_timeFrame = _call_timeFrame;
// sms_timeFrame = _sms_timeFrame;
//
// editor.putInt("location_timeFrame", _location_timeFrame);
// editor.putInt("call_timeFrame", _call_timeFrame);
// editor.putInt("sms_timeFrame", _sms_timeFrame);
//
// // Commit the edits!
// editor.commit();
//
// }
//
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/UserFriendlyException.java
// public class UserFriendlyException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserFriendlyException(String message) {
// super(message);
// }
//
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.content.Context;
import com.ubiqlog.ui.R;
import com.ubiqlog.vis.common.Settings;
import com.ubiqlog.vis.utils.UserFriendlyException; | package com.ubiqlog.vis.extras.search;
/**
* @author Soheil KHOSRAVIPOUR
* @modified by Victor Gugonatu
* @modified on 12.2010
* @date 07.2010
* @version 1.0
*/
public class Searcher {
// This function receives sensor, and address of the file and returns the
// search results in an array list
public ArrayList<String> searchFile(String sensor, String fileAddress) {
FileInputStream in;
ArrayList<String> result = new ArrayList<String>(); // The Result array list
try {
in = new FileInputStream(new File(fileAddress));
} catch (FileNotFoundException e) {
// file not found -> ignore
return new ArrayList<String>();
}
InputStreamReader inputreader = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, one line at the
// time
try {
while ((line = buffreader.readLine()) != null) {
if (line.startsWith("{\"" + sensor) || line.startsWith("\"" + sensor)) {
// Found a record
result.add(line);
}
}
} catch (IOException e) {
// ignore
}
return result;
}
// This function receives a sensor, dates and creates address of the files
// and returns the search results using searchFile
public ArrayList<String> searchFolder(String sensor, String date1,String date2, Context _context)
throws UserFriendlyException {
ArrayList<String> result = new ArrayList<String>();
| // Path: app/src/main/java/com/ubiqlog/vis/common/Settings.java
// public class Settings {
//
// public static final String googleMapKey = "0U0FROSv7CVVKcfYcZY_7wDf4OBYAgX9HsueySA";
// public static final String PREF_FILE_NAME = "UbiqlogVisPrefFile";
// public static final String LOG_FOLDER = Setting.LOG_FOLDER;
// public static final String SensorLocation = "Location";
// public static final String SensorApplication = "Application";
// public static final String SensorCall = "Call";
// public static final String SensorSms = "SMS";
// public static final int application_timeinterval = 11000;
//
// public static int location_timeFrame = 5000;
// public static int call_timeFrame = 5000;
// public static int sms_timeFrame = 5000;
//
// // Initialize preferences (from pref file or default)
// public static void initialise(Context context) {
// SharedPreferences settings = context.getSharedPreferences(
// PREF_FILE_NAME, 0);
// location_timeFrame = settings.getInt("location_timeFrame",
// location_timeFrame);
// call_timeFrame = settings.getInt("call_timeFrame", call_timeFrame);
// sms_timeFrame = settings.getInt("sms_timeFrame", sms_timeFrame);
// }
//
// // save preferences in pref file
// public static void savePreferences(Context context,
// int _location_timeFrame, int _call_timeFrame, int _sms_timeFrame) {
// SharedPreferences settings = context.getSharedPreferences(
// PREF_FILE_NAME, 0);
// SharedPreferences.Editor editor = settings.edit();
//
// location_timeFrame = _location_timeFrame;
// call_timeFrame = _call_timeFrame;
// sms_timeFrame = _sms_timeFrame;
//
// editor.putInt("location_timeFrame", _location_timeFrame);
// editor.putInt("call_timeFrame", _call_timeFrame);
// editor.putInt("sms_timeFrame", _sms_timeFrame);
//
// // Commit the edits!
// editor.commit();
//
// }
//
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/UserFriendlyException.java
// public class UserFriendlyException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public UserFriendlyException(String message) {
// super(message);
// }
//
// }
// Path: app/src/main/java/com/ubiqlog/vis/extras/search/Searcher.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.content.Context;
import com.ubiqlog.ui.R;
import com.ubiqlog.vis.common.Settings;
import com.ubiqlog.vis.utils.UserFriendlyException;
package com.ubiqlog.vis.extras.search;
/**
* @author Soheil KHOSRAVIPOUR
* @modified by Victor Gugonatu
* @modified on 12.2010
* @date 07.2010
* @version 1.0
*/
public class Searcher {
// This function receives sensor, and address of the file and returns the
// search results in an array list
public ArrayList<String> searchFile(String sensor, String fileAddress) {
FileInputStream in;
ArrayList<String> result = new ArrayList<String>(); // The Result array list
try {
in = new FileInputStream(new File(fileAddress));
} catch (FileNotFoundException e) {
// file not found -> ignore
return new ArrayList<String>();
}
InputStreamReader inputreader = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, one line at the
// time
try {
while ((line = buffreader.readLine()) != null) {
if (line.startsWith("{\"" + sensor) || line.startsWith("\"" + sensor)) {
// Found a record
result.add(line);
}
}
} catch (IOException e) {
// ignore
}
return result;
}
// This function receives a sensor, dates and creates address of the files
// and returns the search results using searchFile
public ArrayList<String> searchFolder(String sensor, String date1,String date2, Context _context)
throws UserFriendlyException {
ArrayList<String> result = new ArrayList<String>();
| String folderAddress = Settings.LOG_FOLDER + "/"; |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/ui/extras/DateTimeSelector/DateTimeSelector.java | // Path: app/src/main/java/com/ubiqlog/vis/ui/extras/DateTimeSelector/DateTimePickerDialog.java
// public enum Type {
// DATE, TIME, DATETIME
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import com.ubiqlog.vis.ui.extras.DateTimeSelector.DateTimePickerDialog.Type;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker; | package com.ubiqlog.vis.ui.extras.DateTimeSelector;
/**
* A framelayout displaying a button with the a date on it. When the button is
* pressed a DateTimePicker dialog will be displayed and the user can change the
* date and/or time
*
* @author Victor Gugonatu
* @date 10.2010
* @version 1.0
*/
public class DateTimeSelector extends FrameLayout implements
View.OnClickListener {
/**
* The callback used to indicate the user is done filling in the data.
* Refers to {@link DateTimeSelector DateTimeSelector}
*/
public interface OnDataChangedListener {
| // Path: app/src/main/java/com/ubiqlog/vis/ui/extras/DateTimeSelector/DateTimePickerDialog.java
// public enum Type {
// DATE, TIME, DATETIME
// }
// Path: app/src/main/java/com/ubiqlog/vis/ui/extras/DateTimeSelector/DateTimeSelector.java
import java.text.SimpleDateFormat;
import java.util.Date;
import com.ubiqlog.vis.ui.extras.DateTimeSelector.DateTimePickerDialog.Type;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;
package com.ubiqlog.vis.ui.extras.DateTimeSelector;
/**
* A framelayout displaying a button with the a date on it. When the button is
* pressed a DateTimePicker dialog will be displayed and the user can change the
* date and/or time
*
* @author Victor Gugonatu
* @date 10.2010
* @version 1.0
*/
public class DateTimeSelector extends FrameLayout implements
View.OnClickListener {
/**
* The callback used to indicate the user is done filling in the data.
* Refers to {@link DateTimeSelector DateTimeSelector}
*/
public interface OnDataChangedListener {
| public abstract void onDataChanged(Date date, Type type); |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/extras/movement/MovementStateContainer.java | // Path: app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java
// public class JsonEncodeDecode
// {
// public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
// + deviceName
// + "\",\"address\":\""
// + deviceAddress
// + "\",\"bond status\":\""
// + bindState
// + "\",\"time\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeBluetooth(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[4];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
// decodedString[3] = split[17];
//
// return decodedString;
// }
//
// public static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Movement\":{\"start\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampStart)
// + "\",\"end\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampEnd)
// + "\",\"state\":\""
// + movementState
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeMovement(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[3];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
//
// return decodedString;
// }
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public class SensorState
// {
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
//
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// }
| import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import com.ubiqlog.vis.utils.JsonEncodeDecode;
import com.ubiqlog.vis.utils.SensorState; | package com.ubiqlog.vis.extras.movement;
/**
*
* @author Dorin Gugonatu
*
*/
public class MovementStateContainer
{
private ArrayList<MovementState> listMovementStates;
private Calendar dateLow;
private Calendar dateHigh;
private boolean bIsEmpty;
public MovementStateContainer(Date startDate, Date endDate)
{
this.listMovementStates = new ArrayList<MovementState>();
this.dateLow = Calendar.getInstance();
this.dateLow.setTime(startDate);
this.dateHigh = Calendar.getInstance();
this.dateHigh.setTime(endDate);
this.bIsEmpty = true;
}
public void parseJsonList(String[] jsonStringList)
{
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
MovementState currentState;
Long dateTimeCurrent;
Hashtable<Long, MovementState> hashMovementStates = new Hashtable<Long, MovementState>();
try
{
for (String jsonString : jsonStringList)
{ | // Path: app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java
// public class JsonEncodeDecode
// {
// public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
// + deviceName
// + "\",\"address\":\""
// + deviceAddress
// + "\",\"bond status\":\""
// + bindState
// + "\",\"time\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeBluetooth(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[4];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
// decodedString[3] = split[17];
//
// return decodedString;
// }
//
// public static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Movement\":{\"start\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampStart)
// + "\",\"end\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampEnd)
// + "\",\"state\":\""
// + movementState
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeMovement(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[3];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
//
// return decodedString;
// }
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public class SensorState
// {
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
//
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// }
// Path: app/src/main/java/com/ubiqlog/vis/extras/movement/MovementStateContainer.java
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import com.ubiqlog.vis.utils.JsonEncodeDecode;
import com.ubiqlog.vis.utils.SensorState;
package com.ubiqlog.vis.extras.movement;
/**
*
* @author Dorin Gugonatu
*
*/
public class MovementStateContainer
{
private ArrayList<MovementState> listMovementStates;
private Calendar dateLow;
private Calendar dateHigh;
private boolean bIsEmpty;
public MovementStateContainer(Date startDate, Date endDate)
{
this.listMovementStates = new ArrayList<MovementState>();
this.dateLow = Calendar.getInstance();
this.dateLow.setTime(startDate);
this.dateHigh = Calendar.getInstance();
this.dateHigh.setTime(endDate);
this.bIsEmpty = true;
}
public void parseJsonList(String[] jsonStringList)
{
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
MovementState currentState;
Long dateTimeCurrent;
Hashtable<Long, MovementState> hashMovementStates = new Hashtable<Long, MovementState>();
try
{
for (String jsonString : jsonStringList)
{ | String[] jsonDecoded = JsonEncodeDecode.DecodeMovement(jsonString); |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/extras/movement/MovementStateContainer.java | // Path: app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java
// public class JsonEncodeDecode
// {
// public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
// + deviceName
// + "\",\"address\":\""
// + deviceAddress
// + "\",\"bond status\":\""
// + bindState
// + "\",\"time\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeBluetooth(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[4];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
// decodedString[3] = split[17];
//
// return decodedString;
// }
//
// public static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Movement\":{\"start\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampStart)
// + "\",\"end\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampEnd)
// + "\",\"state\":\""
// + movementState
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeMovement(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[3];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
//
// return decodedString;
// }
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public class SensorState
// {
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
//
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// }
| import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import com.ubiqlog.vis.utils.JsonEncodeDecode;
import com.ubiqlog.vis.utils.SensorState; | endEventCalendar.setTime(df.parse(timestampEnd));
if (startEventCalendar.before(dateLow) && endEventCalendar.after(dateLow))
{
startEventCalendar.setTime(dateLow.getTime());
}
if (startEventCalendar.before(dateHigh) && endEventCalendar.after(dateHigh))
{
endEventCalendar.setTime(dateHigh.getTime());
}
if ((startEventCalendar.compareTo(dateLow) >=0) && (endEventCalendar.compareTo(dateHigh) <= 0))
{
Calendar currentEventCalendar = (Calendar)startEventCalendar.clone();
currentEventCalendar.set(Calendar.HOUR, 0);
currentEventCalendar.set(Calendar.MINUTE, 0);
currentEventCalendar.set(Calendar.SECOND, 0);
currentEventCalendar.set(Calendar.MILLISECOND, 0);
dateTimeCurrent = currentEventCalendar.getTime().getTime();
if ((currentState = hashMovementStates.get(dateTimeCurrent)) == null)
{
hashMovementStates.put(dateTimeCurrent, new MovementState());
}
currentState = hashMovementStates.get(dateTimeCurrent);
| // Path: app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java
// public class JsonEncodeDecode
// {
// public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
// + deviceName
// + "\",\"address\":\""
// + deviceAddress
// + "\",\"bond status\":\""
// + bindState
// + "\",\"time\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeBluetooth(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[4];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
// decodedString[3] = split[17];
//
// return decodedString;
// }
//
// public static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState)
// {
// StringBuilder encodedString = new StringBuilder("");
// encodedString = encodedString.append("{\"Movement\":{\"start\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampStart)
// + "\",\"end\":\""
// + DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timestampEnd)
// + "\",\"state\":\""
// + movementState
// + "\"}}");
//
// return encodedString.toString();
// }
//
// public static String[] DecodeMovement(String jsonString)
// {
// String[] split = jsonString.split("\"");
//
// String[] decodedString = new String[3];
//
// decodedString[0] = split[5];
// decodedString[1] = split[9];
// decodedString[2] = split[13];
//
// return decodedString;
// }
// }
//
// Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public class SensorState
// {
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
//
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// }
// Path: app/src/main/java/com/ubiqlog/vis/extras/movement/MovementStateContainer.java
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import com.ubiqlog.vis.utils.JsonEncodeDecode;
import com.ubiqlog.vis.utils.SensorState;
endEventCalendar.setTime(df.parse(timestampEnd));
if (startEventCalendar.before(dateLow) && endEventCalendar.after(dateLow))
{
startEventCalendar.setTime(dateLow.getTime());
}
if (startEventCalendar.before(dateHigh) && endEventCalendar.after(dateHigh))
{
endEventCalendar.setTime(dateHigh.getTime());
}
if ((startEventCalendar.compareTo(dateLow) >=0) && (endEventCalendar.compareTo(dateHigh) <= 0))
{
Calendar currentEventCalendar = (Calendar)startEventCalendar.clone();
currentEventCalendar.set(Calendar.HOUR, 0);
currentEventCalendar.set(Calendar.MINUTE, 0);
currentEventCalendar.set(Calendar.SECOND, 0);
currentEventCalendar.set(Calendar.MILLISECOND, 0);
dateTimeCurrent = currentEventCalendar.getTime().getTime();
if ((currentState = hashMovementStates.get(dateTimeCurrent)) == null)
{
hashMovementStates.put(dateTimeCurrent, new MovementState());
}
currentState = hashMovementStates.get(dateTimeCurrent);
| currentState.InsertState(startEventCalendar.getTime(), endEventCalendar.getTime(), dateLow.getTime(), SensorState.Movement.valueOf(movementState)); |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/extras/movement/MovementState.java | // Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
| import java.util.ArrayList;
import java.util.Date;
import com.ubiqlog.vis.utils.SensorState.Movement; | package com.ubiqlog.vis.extras.movement;
/**
*
* @author Dorin Gugonatu
*
*/
public class MovementState
{
private ArrayList<MovementInterval> fastMovement;
private ArrayList<MovementInterval> slowMovement;
private ArrayList<MovementInterval> steadyMovement;
public MovementState()
{
this.fastMovement = new ArrayList<MovementInterval>();
this.slowMovement = new ArrayList<MovementInterval>();
this.steadyMovement = new ArrayList<MovementInterval>();
}
| // Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// Path: app/src/main/java/com/ubiqlog/vis/extras/movement/MovementState.java
import java.util.ArrayList;
import java.util.Date;
import com.ubiqlog.vis.utils.SensorState.Movement;
package com.ubiqlog.vis.extras.movement;
/**
*
* @author Dorin Gugonatu
*
*/
public class MovementState
{
private ArrayList<MovementInterval> fastMovement;
private ArrayList<MovementInterval> slowMovement;
private ArrayList<MovementInterval> steadyMovement;
public MovementState()
{
this.fastMovement = new ArrayList<MovementInterval>();
this.slowMovement = new ArrayList<MovementInterval>();
this.steadyMovement = new ArrayList<MovementInterval>();
}
| public void InsertState(Date timestampStart, Date timestampEnd, Date refDate, Movement state) |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/ui/extras/bluetooth/BluetoothLogHorizontalScrollView.java | // Path: app/src/main/java/com/ubiqlog/vis/common/IZoomNotification.java
// public interface IZoomNotification
// {
// public void viewZoomIn(float left, float right);
// public void viewZoomOut(float left, float right);
//
// public void doZoom(float fScale);
//
// public void viewClearZoom();
// }
| import com.ubiqlog.vis.common.IZoomNotification;
import android.content.Context;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView; | package com.ubiqlog.vis.ui.extras.bluetooth;
/**
*
* @author Dorin Gugonatu
*
*/
public class BluetoothLogHorizontalScrollView extends HorizontalScrollView
{
private boolean bIsZooming;
private float fZoomInOldDistance;
private float fZoomScale; | // Path: app/src/main/java/com/ubiqlog/vis/common/IZoomNotification.java
// public interface IZoomNotification
// {
// public void viewZoomIn(float left, float right);
// public void viewZoomOut(float left, float right);
//
// public void doZoom(float fScale);
//
// public void viewClearZoom();
// }
// Path: app/src/main/java/com/ubiqlog/vis/ui/extras/bluetooth/BluetoothLogHorizontalScrollView.java
import com.ubiqlog.vis.common.IZoomNotification;
import android.content.Context;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
package com.ubiqlog.vis.ui.extras.bluetooth;
/**
*
* @author Dorin Gugonatu
*
*/
public class BluetoothLogHorizontalScrollView extends HorizontalScrollView
{
private boolean bIsZooming;
private float fZoomInOldDistance;
private float fZoomScale; | private IZoomNotification zoomNotification; |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/extras/bluetooth/BluetoothDetection.java | // Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public class SensorState
// {
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
//
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// }
| import java.util.ArrayList;
import java.util.Date;
import com.ubiqlog.vis.utils.SensorState; | package com.ubiqlog.vis.extras.bluetooth;
/**
*
* @author Dorin Gugonatu
*
*/
public class BluetoothDetection
{
private String deviceName;
private String deviceAddress;
private ArrayList<DetectionDate> detectionDates;
public BluetoothDetection(String deviceName, String deviceAddress)
{
this.deviceName = deviceName;
this.deviceAddress = deviceAddress;
this.detectionDates = new ArrayList<DetectionDate>();
}
| // Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public class SensorState
// {
// public static enum Bluetooth
// {
// NONE("none"),
// BONDING("bonding"),
// BONDED("bonded");
//
// private String state;
//
// Bluetooth(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
//
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// }
// Path: app/src/main/java/com/ubiqlog/vis/extras/bluetooth/BluetoothDetection.java
import java.util.ArrayList;
import java.util.Date;
import com.ubiqlog.vis.utils.SensorState;
package com.ubiqlog.vis.extras.bluetooth;
/**
*
* @author Dorin Gugonatu
*
*/
public class BluetoothDetection
{
private String deviceName;
private String deviceAddress;
private ArrayList<DetectionDate> detectionDates;
public BluetoothDetection(String deviceName, String deviceAddress)
{
this.deviceName = deviceName;
this.deviceAddress = deviceAddress;
this.detectionDates = new ArrayList<DetectionDate>();
}
| public void InsertDetection(long detectionTimestamp, SensorState.Bluetooth deviceState) |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java | // Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
| import java.text.DateFormat;
import java.util.Date;
import com.ubiqlog.vis.utils.SensorState.Movement; | package com.ubiqlog.vis.utils;
public class JsonEncodeDecode
{
public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
{
StringBuilder encodedString = new StringBuilder("");
encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
+ deviceName
+ "\",\"address\":\""
+ deviceAddress
+ "\",\"bond status\":\""
+ bindState
+ "\",\"time\":\""
+ DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
+ "\"}}");
return encodedString.toString();
}
public static String[] DecodeBluetooth(String jsonString)
{
String[] split = jsonString.split("\"");
String[] decodedString = new String[4];
decodedString[0] = split[5];
decodedString[1] = split[9];
decodedString[2] = split[13];
decodedString[3] = split[17];
return decodedString;
}
| // Path: app/src/main/java/com/ubiqlog/vis/utils/SensorState.java
// public static enum Movement
// {
// FAST("fast"),
// SLOW("slow"),
// STEADY("steady");
//
// private String state;
//
// Movement(String state)
// {
// this.state = state;
// }
//
// public String getState()
// {
// return state;
// }
// }
// Path: app/src/main/java/com/ubiqlog/vis/utils/JsonEncodeDecode.java
import java.text.DateFormat;
import java.util.Date;
import com.ubiqlog.vis.utils.SensorState.Movement;
package com.ubiqlog.vis.utils;
public class JsonEncodeDecode
{
public static String EncodeBluetooth(String deviceName, String deviceAddress, String bindState, Date timeStamp)
{
StringBuilder encodedString = new StringBuilder("");
encodedString = encodedString.append("{\"Bluetooth\":{\"name\":\""
+ deviceName
+ "\",\"address\":\""
+ deviceAddress
+ "\",\"bond status\":\""
+ bindState
+ "\",\"time\":\""
+ DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(timeStamp)
+ "\"}}");
return encodedString.toString();
}
public static String[] DecodeBluetooth(String jsonString)
{
String[] split = jsonString.split("\"");
String[] decodedString = new String[4];
decodedString[0] = split[5];
decodedString[1] = split[9];
decodedString[2] = split[13];
decodedString[3] = split[17];
return decodedString;
}
| public static String EncodeMovement(Date timestampStart, Date timestampEnd, Movement movementState) |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/service/LockService.java | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java
// public class GankLockReceiver extends BroadcastReceiver {
//
// private static final String TAG = GankLockReceiver.class.getSimpleName();
//
//
// @Override
// public void onReceive(Context context, Intent intent) {
// String action = intent.getAction();
// /*if (action.equals(Intent.ACTION_SCREEN_ON)) {
// LockManager.createLockView();
// onPhoneRing();
// }*/
// if (action.equals(Intent.ACTION_SCREEN_OFF)) {
// Intent mLockIntent = new Intent(context, LockActivity.class);
// mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// context.startActivity(mLockIntent);
// }
// }
//
//
// public void onPhoneRing() {
// //手机处于响铃状态
// if (((TelephonyManager) MyApplication.getContext()
// .getSystemService("phone")).getCallState() == TelephonyManager.CALL_STATE_IDLE) {
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
| import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.receiver.GankLockReceiver;
import me.wavever.ganklock.utils.PreferenceUtil; | package me.wavever.ganklock.service;
/**
* Created by wavever on 2015/12/26.
*/
public class LockService extends Service {
private BroadcastReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF); | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java
// public class GankLockReceiver extends BroadcastReceiver {
//
// private static final String TAG = GankLockReceiver.class.getSimpleName();
//
//
// @Override
// public void onReceive(Context context, Intent intent) {
// String action = intent.getAction();
// /*if (action.equals(Intent.ACTION_SCREEN_ON)) {
// LockManager.createLockView();
// onPhoneRing();
// }*/
// if (action.equals(Intent.ACTION_SCREEN_OFF)) {
// Intent mLockIntent = new Intent(context, LockActivity.class);
// mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// context.startActivity(mLockIntent);
// }
// }
//
//
// public void onPhoneRing() {
// //手机处于响铃状态
// if (((TelephonyManager) MyApplication.getContext()
// .getSystemService("phone")).getCallState() == TelephonyManager.CALL_STATE_IDLE) {
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/service/LockService.java
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.receiver.GankLockReceiver;
import me.wavever.ganklock.utils.PreferenceUtil;
package me.wavever.ganklock.service;
/**
* Created by wavever on 2015/12/26.
*/
public class LockService extends Service {
private BroadcastReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF); | receiver = new GankLockReceiver(); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/service/LockService.java | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java
// public class GankLockReceiver extends BroadcastReceiver {
//
// private static final String TAG = GankLockReceiver.class.getSimpleName();
//
//
// @Override
// public void onReceive(Context context, Intent intent) {
// String action = intent.getAction();
// /*if (action.equals(Intent.ACTION_SCREEN_ON)) {
// LockManager.createLockView();
// onPhoneRing();
// }*/
// if (action.equals(Intent.ACTION_SCREEN_OFF)) {
// Intent mLockIntent = new Intent(context, LockActivity.class);
// mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// context.startActivity(mLockIntent);
// }
// }
//
//
// public void onPhoneRing() {
// //手机处于响铃状态
// if (((TelephonyManager) MyApplication.getContext()
// .getSystemService("phone")).getCallState() == TelephonyManager.CALL_STATE_IDLE) {
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
| import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.receiver.GankLockReceiver;
import me.wavever.ganklock.utils.PreferenceUtil; | package me.wavever.ganklock.service;
/**
* Created by wavever on 2015/12/26.
*/
public class LockService extends Service {
private BroadcastReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
receiver = new GankLockReceiver();
registerReceiver(receiver, intentFilter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy(); | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java
// public class GankLockReceiver extends BroadcastReceiver {
//
// private static final String TAG = GankLockReceiver.class.getSimpleName();
//
//
// @Override
// public void onReceive(Context context, Intent intent) {
// String action = intent.getAction();
// /*if (action.equals(Intent.ACTION_SCREEN_ON)) {
// LockManager.createLockView();
// onPhoneRing();
// }*/
// if (action.equals(Intent.ACTION_SCREEN_OFF)) {
// Intent mLockIntent = new Intent(context, LockActivity.class);
// mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// context.startActivity(mLockIntent);
// }
// }
//
//
// public void onPhoneRing() {
// //手机处于响铃状态
// if (((TelephonyManager) MyApplication.getContext()
// .getSystemService("phone")).getCallState() == TelephonyManager.CALL_STATE_IDLE) {
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/service/LockService.java
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.receiver.GankLockReceiver;
import me.wavever.ganklock.utils.PreferenceUtil;
package me.wavever.ganklock.service;
/**
* Created by wavever on 2015/12/26.
*/
public class LockService extends Service {
private BroadcastReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
receiver = new GankLockReceiver();
registerReceiver(receiver, intentFilter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy(); | if(PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)){ |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/service/LockService.java | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java
// public class GankLockReceiver extends BroadcastReceiver {
//
// private static final String TAG = GankLockReceiver.class.getSimpleName();
//
//
// @Override
// public void onReceive(Context context, Intent intent) {
// String action = intent.getAction();
// /*if (action.equals(Intent.ACTION_SCREEN_ON)) {
// LockManager.createLockView();
// onPhoneRing();
// }*/
// if (action.equals(Intent.ACTION_SCREEN_OFF)) {
// Intent mLockIntent = new Intent(context, LockActivity.class);
// mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// context.startActivity(mLockIntent);
// }
// }
//
//
// public void onPhoneRing() {
// //手机处于响铃状态
// if (((TelephonyManager) MyApplication.getContext()
// .getSystemService("phone")).getCallState() == TelephonyManager.CALL_STATE_IDLE) {
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
| import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.receiver.GankLockReceiver;
import me.wavever.ganklock.utils.PreferenceUtil; | package me.wavever.ganklock.service;
/**
* Created by wavever on 2015/12/26.
*/
public class LockService extends Service {
private BroadcastReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
receiver = new GankLockReceiver();
registerReceiver(receiver, intentFilter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy(); | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java
// public class GankLockReceiver extends BroadcastReceiver {
//
// private static final String TAG = GankLockReceiver.class.getSimpleName();
//
//
// @Override
// public void onReceive(Context context, Intent intent) {
// String action = intent.getAction();
// /*if (action.equals(Intent.ACTION_SCREEN_ON)) {
// LockManager.createLockView();
// onPhoneRing();
// }*/
// if (action.equals(Intent.ACTION_SCREEN_OFF)) {
// Intent mLockIntent = new Intent(context, LockActivity.class);
// mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
// context.startActivity(mLockIntent);
// }
// }
//
//
// public void onPhoneRing() {
// //手机处于响铃状态
// if (((TelephonyManager) MyApplication.getContext()
// .getSystemService("phone")).getCallState() == TelephonyManager.CALL_STATE_IDLE) {
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/service/LockService.java
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.receiver.GankLockReceiver;
import me.wavever.ganklock.utils.PreferenceUtil;
package me.wavever.ganklock.service;
/**
* Created by wavever on 2015/12/26.
*/
public class LockService extends Service {
private BroadcastReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
receiver = new GankLockReceiver();
registerReceiver(receiver, intentFilter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy(); | if(PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)){ |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/model/http/GankService.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankContent.java
// public class GankContent {
//
// @SerializedName(value = "category")
// public List<String> category;
//
// @SerializedName(value = "error")
// public boolean error;
//
// public Result results;
//
// public class Result {
// @SerializedName(value = "Android") public List<Gank> androidList;
// @SerializedName(value = "iOS") public List<Gank> iosList;
// @SerializedName(value = "App") public List<Gank> appList;
// @SerializedName(value = "前端") public List<Gank> htmlList;
// @SerializedName(value = "瞎推荐") public List<Gank> recommendList;
// @SerializedName(value = "休息视频") public List<Gank> restVideoList;
// @SerializedName(value = "拓展资源") public List<Gank> extendRespurseList;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDailyContent.java
// public class GankDailyContent {
//
// @SerializedName(value = "error")
// public String error;
//
// @SerializedName(value = "results")
// public List<GankDaily> results;
//
// }
| import io.reactivex.Observable;
import me.wavever.ganklock.model.bean.GankContent;
import me.wavever.ganklock.model.bean.GankDailyContent;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query; | package me.wavever.ganklock.model.http;
/**
* Created by wavever on 2016/3/4.
*/
public interface GankService {
@GET("day/{date}") | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankContent.java
// public class GankContent {
//
// @SerializedName(value = "category")
// public List<String> category;
//
// @SerializedName(value = "error")
// public boolean error;
//
// public Result results;
//
// public class Result {
// @SerializedName(value = "Android") public List<Gank> androidList;
// @SerializedName(value = "iOS") public List<Gank> iosList;
// @SerializedName(value = "App") public List<Gank> appList;
// @SerializedName(value = "前端") public List<Gank> htmlList;
// @SerializedName(value = "瞎推荐") public List<Gank> recommendList;
// @SerializedName(value = "休息视频") public List<Gank> restVideoList;
// @SerializedName(value = "拓展资源") public List<Gank> extendRespurseList;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDailyContent.java
// public class GankDailyContent {
//
// @SerializedName(value = "error")
// public String error;
//
// @SerializedName(value = "results")
// public List<GankDaily> results;
//
// }
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
import io.reactivex.Observable;
import me.wavever.ganklock.model.bean.GankContent;
import me.wavever.ganklock.model.bean.GankDailyContent;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
package me.wavever.ganklock.model.http;
/**
* Created by wavever on 2016/3/4.
*/
public interface GankService {
@GET("day/{date}") | Observable<GankContent> getGankData(@Path("date") String date); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/model/http/GankService.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankContent.java
// public class GankContent {
//
// @SerializedName(value = "category")
// public List<String> category;
//
// @SerializedName(value = "error")
// public boolean error;
//
// public Result results;
//
// public class Result {
// @SerializedName(value = "Android") public List<Gank> androidList;
// @SerializedName(value = "iOS") public List<Gank> iosList;
// @SerializedName(value = "App") public List<Gank> appList;
// @SerializedName(value = "前端") public List<Gank> htmlList;
// @SerializedName(value = "瞎推荐") public List<Gank> recommendList;
// @SerializedName(value = "休息视频") public List<Gank> restVideoList;
// @SerializedName(value = "拓展资源") public List<Gank> extendRespurseList;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDailyContent.java
// public class GankDailyContent {
//
// @SerializedName(value = "error")
// public String error;
//
// @SerializedName(value = "results")
// public List<GankDaily> results;
//
// }
| import io.reactivex.Observable;
import me.wavever.ganklock.model.bean.GankContent;
import me.wavever.ganklock.model.bean.GankDailyContent;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query; | package me.wavever.ganklock.model.http;
/**
* Created by wavever on 2016/3/4.
*/
public interface GankService {
@GET("day/{date}")
Observable<GankContent> getGankData(@Path("date") String date);
@GET("history/content/{count}/{page}") | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankContent.java
// public class GankContent {
//
// @SerializedName(value = "category")
// public List<String> category;
//
// @SerializedName(value = "error")
// public boolean error;
//
// public Result results;
//
// public class Result {
// @SerializedName(value = "Android") public List<Gank> androidList;
// @SerializedName(value = "iOS") public List<Gank> iosList;
// @SerializedName(value = "App") public List<Gank> appList;
// @SerializedName(value = "前端") public List<Gank> htmlList;
// @SerializedName(value = "瞎推荐") public List<Gank> recommendList;
// @SerializedName(value = "休息视频") public List<Gank> restVideoList;
// @SerializedName(value = "拓展资源") public List<Gank> extendRespurseList;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDailyContent.java
// public class GankDailyContent {
//
// @SerializedName(value = "error")
// public String error;
//
// @SerializedName(value = "results")
// public List<GankDaily> results;
//
// }
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
import io.reactivex.Observable;
import me.wavever.ganklock.model.bean.GankContent;
import me.wavever.ganklock.model.bean.GankDailyContent;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
package me.wavever.ganklock.model.http;
/**
* Created by wavever on 2016/3/4.
*/
public interface GankService {
@GET("day/{date}")
Observable<GankContent> getGankData(@Path("date") String date);
@GET("history/content/{count}/{page}") | Observable<GankDailyContent> getDailyData(@Path("count")int count, @Path("page")int page); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/model/data/ContentGankData.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankContent.java
// public class GankContent {
//
// @SerializedName(value = "category")
// public List<String> category;
//
// @SerializedName(value = "error")
// public boolean error;
//
// public Result results;
//
// public class Result {
// @SerializedName(value = "Android") public List<Gank> androidList;
// @SerializedName(value = "iOS") public List<Gank> iosList;
// @SerializedName(value = "App") public List<Gank> appList;
// @SerializedName(value = "前端") public List<Gank> htmlList;
// @SerializedName(value = "瞎推荐") public List<Gank> recommendList;
// @SerializedName(value = "休息视频") public List<Gank> restVideoList;
// @SerializedName(value = "拓展资源") public List<Gank> extendRespurseList;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
// public interface GankService {
// @GET("day/{date}")
// Observable<GankContent> getGankData(@Path("date") String date);
//
// @GET("history/content/{count}/{page}")
// Observable<GankDailyContent> getDailyData(@Path("count")int count, @Path("page")int page);
//
// @GET("data/福利/{number}/{page}")
// Observable<GankContent> getGirlData(@Path("number") int number, @Path("page") int page);
//
// @GET("category/{}/count/{}/page/{}")
// Observable<GankContent> searchGankData(@Query("category") String category,@Path("count") int count,@Path("page") int page);
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/RetrofitUtil.java
// public class RetrofitUtil {
//
// private static GankService sService;
// private static Gson sGson;
// private static OkHttpClient sOkHttpClient;
//
// static {
// sGson = new GsonBuilder()
// .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
// //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss" + ".SSS'Z'")
// .setDateFormat("yyyy/MM/dd")
// .serializeNulls() //导出null值
// .create();
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// sOkHttpClient = new OkHttpClient.Builder()
// .addInterceptor(loggingInterceptor)
// .retryOnConnectionFailure(true)
// .connectTimeout(15, TimeUnit.SECONDS)
// .build();
// }
//
//
// public static GankService getSingleton() {
//
// if (sService == null) {
// synchronized (RetrofitUtil.class) {
// if (sService == null) {
// String api = GankApi.BASE_URL;
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(api)
// .client(sOkHttpClient)
// .addConverterFactory(GsonConverterFactory.create(sGson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .build();
// sService = retrofit.create(GankService.class);
// }
// }
// }
//
// return sService;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.model.bean.GankContent;
import me.wavever.ganklock.model.http.GankService;
import me.wavever.ganklock.model.http.RetrofitUtil; | package me.wavever.ganklock.model.data;
/**
* Created by wavever on 2016/9/20.
*/
public class ContentGankData {
private GankService service = RetrofitUtil.getSingleton(); | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankContent.java
// public class GankContent {
//
// @SerializedName(value = "category")
// public List<String> category;
//
// @SerializedName(value = "error")
// public boolean error;
//
// public Result results;
//
// public class Result {
// @SerializedName(value = "Android") public List<Gank> androidList;
// @SerializedName(value = "iOS") public List<Gank> iosList;
// @SerializedName(value = "App") public List<Gank> appList;
// @SerializedName(value = "前端") public List<Gank> htmlList;
// @SerializedName(value = "瞎推荐") public List<Gank> recommendList;
// @SerializedName(value = "休息视频") public List<Gank> restVideoList;
// @SerializedName(value = "拓展资源") public List<Gank> extendRespurseList;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
// public interface GankService {
// @GET("day/{date}")
// Observable<GankContent> getGankData(@Path("date") String date);
//
// @GET("history/content/{count}/{page}")
// Observable<GankDailyContent> getDailyData(@Path("count")int count, @Path("page")int page);
//
// @GET("data/福利/{number}/{page}")
// Observable<GankContent> getGirlData(@Path("number") int number, @Path("page") int page);
//
// @GET("category/{}/count/{}/page/{}")
// Observable<GankContent> searchGankData(@Query("category") String category,@Path("count") int count,@Path("page") int page);
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/RetrofitUtil.java
// public class RetrofitUtil {
//
// private static GankService sService;
// private static Gson sGson;
// private static OkHttpClient sOkHttpClient;
//
// static {
// sGson = new GsonBuilder()
// .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
// //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss" + ".SSS'Z'")
// .setDateFormat("yyyy/MM/dd")
// .serializeNulls() //导出null值
// .create();
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// sOkHttpClient = new OkHttpClient.Builder()
// .addInterceptor(loggingInterceptor)
// .retryOnConnectionFailure(true)
// .connectTimeout(15, TimeUnit.SECONDS)
// .build();
// }
//
//
// public static GankService getSingleton() {
//
// if (sService == null) {
// synchronized (RetrofitUtil.class) {
// if (sService == null) {
// String api = GankApi.BASE_URL;
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(api)
// .client(sOkHttpClient)
// .addConverterFactory(GsonConverterFactory.create(sGson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .build();
// sService = retrofit.create(GankService.class);
// }
// }
// }
//
// return sService;
// }
//
// }
// Path: app/src/main/java/me/wavever/ganklock/model/data/ContentGankData.java
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.model.bean.GankContent;
import me.wavever.ganklock.model.http.GankService;
import me.wavever.ganklock.model.http.RetrofitUtil;
package me.wavever.ganklock.model.data;
/**
* Created by wavever on 2016/9/20.
*/
public class ContentGankData {
private GankService service = RetrofitUtil.getSingleton(); | private List<Gank> mList = new ArrayList<>(); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/model/data/ContentGankData.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankContent.java
// public class GankContent {
//
// @SerializedName(value = "category")
// public List<String> category;
//
// @SerializedName(value = "error")
// public boolean error;
//
// public Result results;
//
// public class Result {
// @SerializedName(value = "Android") public List<Gank> androidList;
// @SerializedName(value = "iOS") public List<Gank> iosList;
// @SerializedName(value = "App") public List<Gank> appList;
// @SerializedName(value = "前端") public List<Gank> htmlList;
// @SerializedName(value = "瞎推荐") public List<Gank> recommendList;
// @SerializedName(value = "休息视频") public List<Gank> restVideoList;
// @SerializedName(value = "拓展资源") public List<Gank> extendRespurseList;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
// public interface GankService {
// @GET("day/{date}")
// Observable<GankContent> getGankData(@Path("date") String date);
//
// @GET("history/content/{count}/{page}")
// Observable<GankDailyContent> getDailyData(@Path("count")int count, @Path("page")int page);
//
// @GET("data/福利/{number}/{page}")
// Observable<GankContent> getGirlData(@Path("number") int number, @Path("page") int page);
//
// @GET("category/{}/count/{}/page/{}")
// Observable<GankContent> searchGankData(@Query("category") String category,@Path("count") int count,@Path("page") int page);
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/RetrofitUtil.java
// public class RetrofitUtil {
//
// private static GankService sService;
// private static Gson sGson;
// private static OkHttpClient sOkHttpClient;
//
// static {
// sGson = new GsonBuilder()
// .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
// //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss" + ".SSS'Z'")
// .setDateFormat("yyyy/MM/dd")
// .serializeNulls() //导出null值
// .create();
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// sOkHttpClient = new OkHttpClient.Builder()
// .addInterceptor(loggingInterceptor)
// .retryOnConnectionFailure(true)
// .connectTimeout(15, TimeUnit.SECONDS)
// .build();
// }
//
//
// public static GankService getSingleton() {
//
// if (sService == null) {
// synchronized (RetrofitUtil.class) {
// if (sService == null) {
// String api = GankApi.BASE_URL;
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(api)
// .client(sOkHttpClient)
// .addConverterFactory(GsonConverterFactory.create(sGson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .build();
// sService = retrofit.create(GankService.class);
// }
// }
// }
//
// return sService;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.model.bean.GankContent;
import me.wavever.ganklock.model.http.GankService;
import me.wavever.ganklock.model.http.RetrofitUtil; | package me.wavever.ganklock.model.data;
/**
* Created by wavever on 2016/9/20.
*/
public class ContentGankData {
private GankService service = RetrofitUtil.getSingleton();
private List<Gank> mList = new ArrayList<>();
public void getDailyGankDataFromServer(String date, Observer observer) {
service.getGankData(date) | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankContent.java
// public class GankContent {
//
// @SerializedName(value = "category")
// public List<String> category;
//
// @SerializedName(value = "error")
// public boolean error;
//
// public Result results;
//
// public class Result {
// @SerializedName(value = "Android") public List<Gank> androidList;
// @SerializedName(value = "iOS") public List<Gank> iosList;
// @SerializedName(value = "App") public List<Gank> appList;
// @SerializedName(value = "前端") public List<Gank> htmlList;
// @SerializedName(value = "瞎推荐") public List<Gank> recommendList;
// @SerializedName(value = "休息视频") public List<Gank> restVideoList;
// @SerializedName(value = "拓展资源") public List<Gank> extendRespurseList;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
// public interface GankService {
// @GET("day/{date}")
// Observable<GankContent> getGankData(@Path("date") String date);
//
// @GET("history/content/{count}/{page}")
// Observable<GankDailyContent> getDailyData(@Path("count")int count, @Path("page")int page);
//
// @GET("data/福利/{number}/{page}")
// Observable<GankContent> getGirlData(@Path("number") int number, @Path("page") int page);
//
// @GET("category/{}/count/{}/page/{}")
// Observable<GankContent> searchGankData(@Query("category") String category,@Path("count") int count,@Path("page") int page);
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/RetrofitUtil.java
// public class RetrofitUtil {
//
// private static GankService sService;
// private static Gson sGson;
// private static OkHttpClient sOkHttpClient;
//
// static {
// sGson = new GsonBuilder()
// .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
// //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss" + ".SSS'Z'")
// .setDateFormat("yyyy/MM/dd")
// .serializeNulls() //导出null值
// .create();
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// sOkHttpClient = new OkHttpClient.Builder()
// .addInterceptor(loggingInterceptor)
// .retryOnConnectionFailure(true)
// .connectTimeout(15, TimeUnit.SECONDS)
// .build();
// }
//
//
// public static GankService getSingleton() {
//
// if (sService == null) {
// synchronized (RetrofitUtil.class) {
// if (sService == null) {
// String api = GankApi.BASE_URL;
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(api)
// .client(sOkHttpClient)
// .addConverterFactory(GsonConverterFactory.create(sGson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .build();
// sService = retrofit.create(GankService.class);
// }
// }
// }
//
// return sService;
// }
//
// }
// Path: app/src/main/java/me/wavever/ganklock/model/data/ContentGankData.java
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.model.bean.GankContent;
import me.wavever.ganklock.model.http.GankService;
import me.wavever.ganklock.model.http.RetrofitUtil;
package me.wavever.ganklock.model.data;
/**
* Created by wavever on 2016/9/20.
*/
public class ContentGankData {
private GankService service = RetrofitUtil.getSingleton();
private List<Gank> mList = new ArrayList<>();
public void getDailyGankDataFromServer(String date, Observer observer) {
service.getGankData(date) | .map(new Function<GankContent, GankContent.Result>() { |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/utils/UIUtil.java | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
| import android.content.Context;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import me.wavever.ganklock.MyApplication; | package me.wavever.ganklock.utils;
/**
* Created by wavever on 2016/3/10.
*/
public class UIUtil {
public static int[] getScreenSize() {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/utils/UIUtil.java
import android.content.Context;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import me.wavever.ganklock.MyApplication;
package me.wavever.ganklock.utils;
/**
* Created by wavever on 2016/3/10.
*/
public class UIUtil {
public static int[] getScreenSize() {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager | = (WindowManager) MyApplication.getContext() |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/model/data/DailyGankData.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDailyContent.java
// public class GankDailyContent {
//
// @SerializedName(value = "error")
// public String error;
//
// @SerializedName(value = "results")
// public List<GankDaily> results;
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
// public interface GankService {
// @GET("day/{date}")
// Observable<GankContent> getGankData(@Path("date") String date);
//
// @GET("history/content/{count}/{page}")
// Observable<GankDailyContent> getDailyData(@Path("count")int count, @Path("page")int page);
//
// @GET("data/福利/{number}/{page}")
// Observable<GankContent> getGirlData(@Path("number") int number, @Path("page") int page);
//
// @GET("category/{}/count/{}/page/{}")
// Observable<GankContent> searchGankData(@Query("category") String category,@Path("count") int count,@Path("page") int page);
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/RetrofitUtil.java
// public class RetrofitUtil {
//
// private static GankService sService;
// private static Gson sGson;
// private static OkHttpClient sOkHttpClient;
//
// static {
// sGson = new GsonBuilder()
// .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
// //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss" + ".SSS'Z'")
// .setDateFormat("yyyy/MM/dd")
// .serializeNulls() //导出null值
// .create();
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// sOkHttpClient = new OkHttpClient.Builder()
// .addInterceptor(loggingInterceptor)
// .retryOnConnectionFailure(true)
// .connectTimeout(15, TimeUnit.SECONDS)
// .build();
// }
//
//
// public static GankService getSingleton() {
//
// if (sService == null) {
// synchronized (RetrofitUtil.class) {
// if (sService == null) {
// String api = GankApi.BASE_URL;
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(api)
// .client(sOkHttpClient)
// .addConverterFactory(GsonConverterFactory.create(sGson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .build();
// sService = retrofit.create(GankService.class);
// }
// }
// }
//
// return sService;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/LogUtil.java
// public class LogUtil {
//
// private static final String TAG = "TAG";
//
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WRAN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static final int LEVEL = VERBOSE;
//
// //只需要修改LEVEL的值,就可以自由的控制日志的打印,
// // 当LEVEL为NOTHING时,就可以屏蔽掉所有的日志
//
// public static void v(String message) {
// if (LEVEL <= VERBOSE) {
// Log.v(TAG, message);
// }
// }
//
// public static void d(String message) {
// if (LEVEL <= DEBUG) {
// Log.d(TAG,message);
// }
// }
//
// public static void i(String message) {
// if (LEVEL <= INFO) {
// Log.i(TAG,message);
// }
// }
//
// public static void w(String message) {
// if (LEVEL <= WRAN) {
// Log.w(TAG,message);
// }
// }
//
// public static void e(String message) {
// if (LEVEL <= ERROR) {
// Log.e(TAG,message);
// }
// }
//
// }
| import com.activeandroid.query.Select;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.wavever.ganklock.model.bean.GankDaily;
import me.wavever.ganklock.model.bean.GankDailyContent;
import me.wavever.ganklock.model.http.GankService;
import me.wavever.ganklock.model.http.RetrofitUtil;
import me.wavever.ganklock.utils.LogUtil; | package me.wavever.ganklock.model.data;
/**
* Created by wavever on 2016/9/1.
*/
public class DailyGankData {
private static String TAG = DailyGankData.class.getSimpleName() + "-->";
| // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDailyContent.java
// public class GankDailyContent {
//
// @SerializedName(value = "error")
// public String error;
//
// @SerializedName(value = "results")
// public List<GankDaily> results;
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
// public interface GankService {
// @GET("day/{date}")
// Observable<GankContent> getGankData(@Path("date") String date);
//
// @GET("history/content/{count}/{page}")
// Observable<GankDailyContent> getDailyData(@Path("count")int count, @Path("page")int page);
//
// @GET("data/福利/{number}/{page}")
// Observable<GankContent> getGirlData(@Path("number") int number, @Path("page") int page);
//
// @GET("category/{}/count/{}/page/{}")
// Observable<GankContent> searchGankData(@Query("category") String category,@Path("count") int count,@Path("page") int page);
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/RetrofitUtil.java
// public class RetrofitUtil {
//
// private static GankService sService;
// private static Gson sGson;
// private static OkHttpClient sOkHttpClient;
//
// static {
// sGson = new GsonBuilder()
// .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
// //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss" + ".SSS'Z'")
// .setDateFormat("yyyy/MM/dd")
// .serializeNulls() //导出null值
// .create();
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// sOkHttpClient = new OkHttpClient.Builder()
// .addInterceptor(loggingInterceptor)
// .retryOnConnectionFailure(true)
// .connectTimeout(15, TimeUnit.SECONDS)
// .build();
// }
//
//
// public static GankService getSingleton() {
//
// if (sService == null) {
// synchronized (RetrofitUtil.class) {
// if (sService == null) {
// String api = GankApi.BASE_URL;
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(api)
// .client(sOkHttpClient)
// .addConverterFactory(GsonConverterFactory.create(sGson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .build();
// sService = retrofit.create(GankService.class);
// }
// }
// }
//
// return sService;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/LogUtil.java
// public class LogUtil {
//
// private static final String TAG = "TAG";
//
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WRAN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static final int LEVEL = VERBOSE;
//
// //只需要修改LEVEL的值,就可以自由的控制日志的打印,
// // 当LEVEL为NOTHING时,就可以屏蔽掉所有的日志
//
// public static void v(String message) {
// if (LEVEL <= VERBOSE) {
// Log.v(TAG, message);
// }
// }
//
// public static void d(String message) {
// if (LEVEL <= DEBUG) {
// Log.d(TAG,message);
// }
// }
//
// public static void i(String message) {
// if (LEVEL <= INFO) {
// Log.i(TAG,message);
// }
// }
//
// public static void w(String message) {
// if (LEVEL <= WRAN) {
// Log.w(TAG,message);
// }
// }
//
// public static void e(String message) {
// if (LEVEL <= ERROR) {
// Log.e(TAG,message);
// }
// }
//
// }
// Path: app/src/main/java/me/wavever/ganklock/model/data/DailyGankData.java
import com.activeandroid.query.Select;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.wavever.ganklock.model.bean.GankDaily;
import me.wavever.ganklock.model.bean.GankDailyContent;
import me.wavever.ganklock.model.http.GankService;
import me.wavever.ganklock.model.http.RetrofitUtil;
import me.wavever.ganklock.utils.LogUtil;
package me.wavever.ganklock.model.data;
/**
* Created by wavever on 2016/9/1.
*/
public class DailyGankData {
private static String TAG = DailyGankData.class.getSimpleName() + "-->";
| private GankService service = RetrofitUtil.getSingleton(); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/model/data/DailyGankData.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDailyContent.java
// public class GankDailyContent {
//
// @SerializedName(value = "error")
// public String error;
//
// @SerializedName(value = "results")
// public List<GankDaily> results;
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
// public interface GankService {
// @GET("day/{date}")
// Observable<GankContent> getGankData(@Path("date") String date);
//
// @GET("history/content/{count}/{page}")
// Observable<GankDailyContent> getDailyData(@Path("count")int count, @Path("page")int page);
//
// @GET("data/福利/{number}/{page}")
// Observable<GankContent> getGirlData(@Path("number") int number, @Path("page") int page);
//
// @GET("category/{}/count/{}/page/{}")
// Observable<GankContent> searchGankData(@Query("category") String category,@Path("count") int count,@Path("page") int page);
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/RetrofitUtil.java
// public class RetrofitUtil {
//
// private static GankService sService;
// private static Gson sGson;
// private static OkHttpClient sOkHttpClient;
//
// static {
// sGson = new GsonBuilder()
// .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
// //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss" + ".SSS'Z'")
// .setDateFormat("yyyy/MM/dd")
// .serializeNulls() //导出null值
// .create();
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// sOkHttpClient = new OkHttpClient.Builder()
// .addInterceptor(loggingInterceptor)
// .retryOnConnectionFailure(true)
// .connectTimeout(15, TimeUnit.SECONDS)
// .build();
// }
//
//
// public static GankService getSingleton() {
//
// if (sService == null) {
// synchronized (RetrofitUtil.class) {
// if (sService == null) {
// String api = GankApi.BASE_URL;
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(api)
// .client(sOkHttpClient)
// .addConverterFactory(GsonConverterFactory.create(sGson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .build();
// sService = retrofit.create(GankService.class);
// }
// }
// }
//
// return sService;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/LogUtil.java
// public class LogUtil {
//
// private static final String TAG = "TAG";
//
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WRAN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static final int LEVEL = VERBOSE;
//
// //只需要修改LEVEL的值,就可以自由的控制日志的打印,
// // 当LEVEL为NOTHING时,就可以屏蔽掉所有的日志
//
// public static void v(String message) {
// if (LEVEL <= VERBOSE) {
// Log.v(TAG, message);
// }
// }
//
// public static void d(String message) {
// if (LEVEL <= DEBUG) {
// Log.d(TAG,message);
// }
// }
//
// public static void i(String message) {
// if (LEVEL <= INFO) {
// Log.i(TAG,message);
// }
// }
//
// public static void w(String message) {
// if (LEVEL <= WRAN) {
// Log.w(TAG,message);
// }
// }
//
// public static void e(String message) {
// if (LEVEL <= ERROR) {
// Log.e(TAG,message);
// }
// }
//
// }
| import com.activeandroid.query.Select;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.wavever.ganklock.model.bean.GankDaily;
import me.wavever.ganklock.model.bean.GankDailyContent;
import me.wavever.ganklock.model.http.GankService;
import me.wavever.ganklock.model.http.RetrofitUtil;
import me.wavever.ganklock.utils.LogUtil; | package me.wavever.ganklock.model.data;
/**
* Created by wavever on 2016/9/1.
*/
public class DailyGankData {
private static String TAG = DailyGankData.class.getSimpleName() + "-->";
| // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDailyContent.java
// public class GankDailyContent {
//
// @SerializedName(value = "error")
// public String error;
//
// @SerializedName(value = "results")
// public List<GankDaily> results;
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/GankService.java
// public interface GankService {
// @GET("day/{date}")
// Observable<GankContent> getGankData(@Path("date") String date);
//
// @GET("history/content/{count}/{page}")
// Observable<GankDailyContent> getDailyData(@Path("count")int count, @Path("page")int page);
//
// @GET("data/福利/{number}/{page}")
// Observable<GankContent> getGirlData(@Path("number") int number, @Path("page") int page);
//
// @GET("category/{}/count/{}/page/{}")
// Observable<GankContent> searchGankData(@Query("category") String category,@Path("count") int count,@Path("page") int page);
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/http/RetrofitUtil.java
// public class RetrofitUtil {
//
// private static GankService sService;
// private static Gson sGson;
// private static OkHttpClient sOkHttpClient;
//
// static {
// sGson = new GsonBuilder()
// .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
// //.setDateFormat("yyyy-MM-dd'T'HH:mm:ss" + ".SSS'Z'")
// .setDateFormat("yyyy/MM/dd")
// .serializeNulls() //导出null值
// .create();
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// sOkHttpClient = new OkHttpClient.Builder()
// .addInterceptor(loggingInterceptor)
// .retryOnConnectionFailure(true)
// .connectTimeout(15, TimeUnit.SECONDS)
// .build();
// }
//
//
// public static GankService getSingleton() {
//
// if (sService == null) {
// synchronized (RetrofitUtil.class) {
// if (sService == null) {
// String api = GankApi.BASE_URL;
// Retrofit retrofit = new Retrofit.Builder()
// .baseUrl(api)
// .client(sOkHttpClient)
// .addConverterFactory(GsonConverterFactory.create(sGson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .build();
// sService = retrofit.create(GankService.class);
// }
// }
// }
//
// return sService;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/LogUtil.java
// public class LogUtil {
//
// private static final String TAG = "TAG";
//
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WRAN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static final int LEVEL = VERBOSE;
//
// //只需要修改LEVEL的值,就可以自由的控制日志的打印,
// // 当LEVEL为NOTHING时,就可以屏蔽掉所有的日志
//
// public static void v(String message) {
// if (LEVEL <= VERBOSE) {
// Log.v(TAG, message);
// }
// }
//
// public static void d(String message) {
// if (LEVEL <= DEBUG) {
// Log.d(TAG,message);
// }
// }
//
// public static void i(String message) {
// if (LEVEL <= INFO) {
// Log.i(TAG,message);
// }
// }
//
// public static void w(String message) {
// if (LEVEL <= WRAN) {
// Log.w(TAG,message);
// }
// }
//
// public static void e(String message) {
// if (LEVEL <= ERROR) {
// Log.e(TAG,message);
// }
// }
//
// }
// Path: app/src/main/java/me/wavever/ganklock/model/data/DailyGankData.java
import com.activeandroid.query.Select;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.wavever.ganklock.model.bean.GankDaily;
import me.wavever.ganklock.model.bean.GankDailyContent;
import me.wavever.ganklock.model.http.GankService;
import me.wavever.ganklock.model.http.RetrofitUtil;
import me.wavever.ganklock.utils.LogUtil;
package me.wavever.ganklock.model.data;
/**
* Created by wavever on 2016/9/1.
*/
public class DailyGankData {
private static String TAG = DailyGankData.class.getSimpleName() + "-->";
| private GankService service = RetrofitUtil.getSingleton(); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/view/IGankContentView.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
| import java.util.List;
import me.wavever.ganklock.model.bean.Gank; | package me.wavever.ganklock.view;
/**
* Created by wavever on 2016/2/22.
*/
public interface IGankContentView extends IBaseView {
void loadData(String date); | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/view/IGankContentView.java
import java.util.List;
import me.wavever.ganklock.model.bean.Gank;
package me.wavever.ganklock.view;
/**
* Created by wavever on 2016/2/22.
*/
public interface IGankContentView extends IBaseView {
void loadData(String date); | void showData(List<Gank> list); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/ui/activity/LockActivity.java
// public class LockActivity extends BaseMvpActivity<ILockView,LockPresenter> implements ILockView,SwipeUnLockLayout.OnSwipeListener {
//
// private static final String TAG = "LockActivity-->";
//
// private ViewSwitcher mViewSwitcher;
// private ImageView mImg;
// private TextView mTitle;
// private Bitmap bitmap;
// private String url;
//
// @Override protected int loadView() {
// return R.layout.activity_lock;
// }
//
// @Override protected void initView() {
// getWindow().addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
// getWindow().addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// setUI();
// SwipeUnLockLayout swipeUnLockLayout = (SwipeUnLockLayout) findViewById(
// R.id.slide_layout);
// swipeUnLockLayout.setOnSwipeListener(this);
// mViewSwitcher = (ViewSwitcher) findViewById(R.id.lock_view_switcher);
// mTitle = (TextView) findViewById(R.id.lock_view_gank_title);
// TextView mLockViewDate = (TextView) findViewById(R.id.lock_view_date);
// final String lockDateText = DateUtil.getLockDateText();
// mLockViewDate.setText(lockDateText);
// mImg = (ImageView) findViewById(R.id.lock_view_img);
// url = PreferenceUtil.getString("url");
// if (url.isEmpty()) {
// mImg.setImageResource(R.drawable.test_image);
// } else {
// getBitmap();
// }
// mImg.setOnClickListener(new View.OnClickListener() {
// @Override public void onClick(View v) {
// mViewSwitcher.showNext();
// }
// });
//
// }
//
// private void setUI() {
// Window window = getWindow();
// window.getDecorView().setSystemUiVisibility(
// View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// );
// if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
// window.addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS);
// }
// if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
// window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// //这个属性重复设置会导致NAVIGATION BAR显示
// //window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// window.setStatusBarColor(0);
// }
// }
//
// @Override public void onSwipeFinish() {
// finish();
// }
//
// @Override public LockPresenter createPresenter() {
// return new LockPresenter();
// }
//
// @Override
// public void onWindowFocusChanged(boolean hasFocus) {
// super.onWindowFocusChanged(hasFocus);
// if (hasFocus) {
// setUI();
// }
// }
//
// private void getBitmap(){
//
// Observable.create(new ObservableOnSubscribe<Bitmap>() {
// @Override
// public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
// try {
// bitmap = Picasso.with(LockActivity.this).load(url).get();
// emitter.onNext(bitmap);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }).subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Consumer<Bitmap>() {
// @Override
// public void accept(Bitmap bitmap) throws Exception {
// mImg.setImageBitmap(bitmap);
// }
// });
//
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import me.wavever.ganklock.MyApplication;
import me.wavever.ganklock.ui.activity.LockActivity; | package me.wavever.ganklock.receiver;
/**
* Created by wavever on 2015/12/24.
*/
public class GankLockReceiver extends BroadcastReceiver {
private static final String TAG = GankLockReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/*if (action.equals(Intent.ACTION_SCREEN_ON)) {
LockManager.createLockView();
onPhoneRing();
}*/
if (action.equals(Intent.ACTION_SCREEN_OFF)) { | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/ui/activity/LockActivity.java
// public class LockActivity extends BaseMvpActivity<ILockView,LockPresenter> implements ILockView,SwipeUnLockLayout.OnSwipeListener {
//
// private static final String TAG = "LockActivity-->";
//
// private ViewSwitcher mViewSwitcher;
// private ImageView mImg;
// private TextView mTitle;
// private Bitmap bitmap;
// private String url;
//
// @Override protected int loadView() {
// return R.layout.activity_lock;
// }
//
// @Override protected void initView() {
// getWindow().addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
// getWindow().addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// setUI();
// SwipeUnLockLayout swipeUnLockLayout = (SwipeUnLockLayout) findViewById(
// R.id.slide_layout);
// swipeUnLockLayout.setOnSwipeListener(this);
// mViewSwitcher = (ViewSwitcher) findViewById(R.id.lock_view_switcher);
// mTitle = (TextView) findViewById(R.id.lock_view_gank_title);
// TextView mLockViewDate = (TextView) findViewById(R.id.lock_view_date);
// final String lockDateText = DateUtil.getLockDateText();
// mLockViewDate.setText(lockDateText);
// mImg = (ImageView) findViewById(R.id.lock_view_img);
// url = PreferenceUtil.getString("url");
// if (url.isEmpty()) {
// mImg.setImageResource(R.drawable.test_image);
// } else {
// getBitmap();
// }
// mImg.setOnClickListener(new View.OnClickListener() {
// @Override public void onClick(View v) {
// mViewSwitcher.showNext();
// }
// });
//
// }
//
// private void setUI() {
// Window window = getWindow();
// window.getDecorView().setSystemUiVisibility(
// View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// );
// if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
// window.addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS);
// }
// if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
// window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// //这个属性重复设置会导致NAVIGATION BAR显示
// //window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// window.setStatusBarColor(0);
// }
// }
//
// @Override public void onSwipeFinish() {
// finish();
// }
//
// @Override public LockPresenter createPresenter() {
// return new LockPresenter();
// }
//
// @Override
// public void onWindowFocusChanged(boolean hasFocus) {
// super.onWindowFocusChanged(hasFocus);
// if (hasFocus) {
// setUI();
// }
// }
//
// private void getBitmap(){
//
// Observable.create(new ObservableOnSubscribe<Bitmap>() {
// @Override
// public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
// try {
// bitmap = Picasso.with(LockActivity.this).load(url).get();
// emitter.onNext(bitmap);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }).subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Consumer<Bitmap>() {
// @Override
// public void accept(Bitmap bitmap) throws Exception {
// mImg.setImageBitmap(bitmap);
// }
// });
//
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import me.wavever.ganklock.MyApplication;
import me.wavever.ganklock.ui.activity.LockActivity;
package me.wavever.ganklock.receiver;
/**
* Created by wavever on 2015/12/24.
*/
public class GankLockReceiver extends BroadcastReceiver {
private static final String TAG = GankLockReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/*if (action.equals(Intent.ACTION_SCREEN_ON)) {
LockManager.createLockView();
onPhoneRing();
}*/
if (action.equals(Intent.ACTION_SCREEN_OFF)) { | Intent mLockIntent = new Intent(context, LockActivity.class); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/ui/activity/LockActivity.java
// public class LockActivity extends BaseMvpActivity<ILockView,LockPresenter> implements ILockView,SwipeUnLockLayout.OnSwipeListener {
//
// private static final String TAG = "LockActivity-->";
//
// private ViewSwitcher mViewSwitcher;
// private ImageView mImg;
// private TextView mTitle;
// private Bitmap bitmap;
// private String url;
//
// @Override protected int loadView() {
// return R.layout.activity_lock;
// }
//
// @Override protected void initView() {
// getWindow().addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
// getWindow().addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// setUI();
// SwipeUnLockLayout swipeUnLockLayout = (SwipeUnLockLayout) findViewById(
// R.id.slide_layout);
// swipeUnLockLayout.setOnSwipeListener(this);
// mViewSwitcher = (ViewSwitcher) findViewById(R.id.lock_view_switcher);
// mTitle = (TextView) findViewById(R.id.lock_view_gank_title);
// TextView mLockViewDate = (TextView) findViewById(R.id.lock_view_date);
// final String lockDateText = DateUtil.getLockDateText();
// mLockViewDate.setText(lockDateText);
// mImg = (ImageView) findViewById(R.id.lock_view_img);
// url = PreferenceUtil.getString("url");
// if (url.isEmpty()) {
// mImg.setImageResource(R.drawable.test_image);
// } else {
// getBitmap();
// }
// mImg.setOnClickListener(new View.OnClickListener() {
// @Override public void onClick(View v) {
// mViewSwitcher.showNext();
// }
// });
//
// }
//
// private void setUI() {
// Window window = getWindow();
// window.getDecorView().setSystemUiVisibility(
// View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// );
// if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
// window.addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS);
// }
// if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
// window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// //这个属性重复设置会导致NAVIGATION BAR显示
// //window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// window.setStatusBarColor(0);
// }
// }
//
// @Override public void onSwipeFinish() {
// finish();
// }
//
// @Override public LockPresenter createPresenter() {
// return new LockPresenter();
// }
//
// @Override
// public void onWindowFocusChanged(boolean hasFocus) {
// super.onWindowFocusChanged(hasFocus);
// if (hasFocus) {
// setUI();
// }
// }
//
// private void getBitmap(){
//
// Observable.create(new ObservableOnSubscribe<Bitmap>() {
// @Override
// public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
// try {
// bitmap = Picasso.with(LockActivity.this).load(url).get();
// emitter.onNext(bitmap);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }).subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Consumer<Bitmap>() {
// @Override
// public void accept(Bitmap bitmap) throws Exception {
// mImg.setImageBitmap(bitmap);
// }
// });
//
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import me.wavever.ganklock.MyApplication;
import me.wavever.ganklock.ui.activity.LockActivity; | package me.wavever.ganklock.receiver;
/**
* Created by wavever on 2015/12/24.
*/
public class GankLockReceiver extends BroadcastReceiver {
private static final String TAG = GankLockReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/*if (action.equals(Intent.ACTION_SCREEN_ON)) {
LockManager.createLockView();
onPhoneRing();
}*/
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Intent mLockIntent = new Intent(context, LockActivity.class);
mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(mLockIntent);
}
}
public void onPhoneRing() {
//手机处于响铃状态 | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/ui/activity/LockActivity.java
// public class LockActivity extends BaseMvpActivity<ILockView,LockPresenter> implements ILockView,SwipeUnLockLayout.OnSwipeListener {
//
// private static final String TAG = "LockActivity-->";
//
// private ViewSwitcher mViewSwitcher;
// private ImageView mImg;
// private TextView mTitle;
// private Bitmap bitmap;
// private String url;
//
// @Override protected int loadView() {
// return R.layout.activity_lock;
// }
//
// @Override protected void initView() {
// getWindow().addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
// getWindow().addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// setUI();
// SwipeUnLockLayout swipeUnLockLayout = (SwipeUnLockLayout) findViewById(
// R.id.slide_layout);
// swipeUnLockLayout.setOnSwipeListener(this);
// mViewSwitcher = (ViewSwitcher) findViewById(R.id.lock_view_switcher);
// mTitle = (TextView) findViewById(R.id.lock_view_gank_title);
// TextView mLockViewDate = (TextView) findViewById(R.id.lock_view_date);
// final String lockDateText = DateUtil.getLockDateText();
// mLockViewDate.setText(lockDateText);
// mImg = (ImageView) findViewById(R.id.lock_view_img);
// url = PreferenceUtil.getString("url");
// if (url.isEmpty()) {
// mImg.setImageResource(R.drawable.test_image);
// } else {
// getBitmap();
// }
// mImg.setOnClickListener(new View.OnClickListener() {
// @Override public void onClick(View v) {
// mViewSwitcher.showNext();
// }
// });
//
// }
//
// private void setUI() {
// Window window = getWindow();
// window.getDecorView().setSystemUiVisibility(
// View.SYSTEM_UI_FLAG_LAYOUT_STABLE
// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
// | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
// | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
// | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
// );
// if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
// window.addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS);
// }
// if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
// window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// //这个属性重复设置会导致NAVIGATION BAR显示
// //window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
// window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// window.setStatusBarColor(0);
// }
// }
//
// @Override public void onSwipeFinish() {
// finish();
// }
//
// @Override public LockPresenter createPresenter() {
// return new LockPresenter();
// }
//
// @Override
// public void onWindowFocusChanged(boolean hasFocus) {
// super.onWindowFocusChanged(hasFocus);
// if (hasFocus) {
// setUI();
// }
// }
//
// private void getBitmap(){
//
// Observable.create(new ObservableOnSubscribe<Bitmap>() {
// @Override
// public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
// try {
// bitmap = Picasso.with(LockActivity.this).load(url).get();
// emitter.onNext(bitmap);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }).subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Consumer<Bitmap>() {
// @Override
// public void accept(Bitmap bitmap) throws Exception {
// mImg.setImageBitmap(bitmap);
// }
// });
//
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/receiver/GankLockReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import me.wavever.ganklock.MyApplication;
import me.wavever.ganklock.ui.activity.LockActivity;
package me.wavever.ganklock.receiver;
/**
* Created by wavever on 2015/12/24.
*/
public class GankLockReceiver extends BroadcastReceiver {
private static final String TAG = GankLockReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/*if (action.equals(Intent.ACTION_SCREEN_ON)) {
LockManager.createLockView();
onPhoneRing();
}*/
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Intent mLockIntent = new Intent(context, LockActivity.class);
mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(mLockIntent);
}
}
public void onPhoneRing() {
//手机处于响铃状态 | if (((TelephonyManager) MyApplication.getContext() |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/ui/fragment/SettingFragment.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/ToastUtil.java
// public class ToastUtil {
//
// private static Toast sToast;
//
// public static void showToastShort(Context context, String content) {
// if (sToast == null) {
// sToast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
// } else {
// sToast.setText(content);
// }
// sToast.show();
// }
//
// public static void showToastLong(Context context, String content) {
// if (sToast == null) {
// sToast = Toast.makeText(context, content, Toast.LENGTH_LONG);
// } else {
// sToast.setText(content);
// }
// sToast.show();
// }
//
// public static void showToastShort(Context context, int resId) {
// showToastShort(context, context.getResources().getString(resId));
// }
//
// public static void showToastLong(Context context, int resId) {
// showToastLong(context, context.getResources().getString(resId));
// }
// }
| import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import me.wavever.ganklock.R;
import me.wavever.ganklock.model.bean.GankDaily;
import me.wavever.ganklock.utils.ToastUtil;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action1; | package me.wavever.ganklock.ui.fragment;
/**
* Created by wavever on 2016/2/23.
*/
public class SettingFragment extends PreferenceFragment
implements Preference.OnPreferenceChangeListener,
Preference.OnPreferenceClickListener {
private Subscription subscription;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference(getString(R.string.key_lock_style)).setOnPreferenceClickListener(this);
findPreference(getString(R.string.key_shake_feed_back)).setOnPreferenceChangeListener(this);
findPreference("key_clear_cache").setOnPreferenceClickListener(this);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_shake_feed_back))) {
if ((Boolean) newValue) {
} else {
}
}
return true;
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_clear_cache))) {
Observable.create(new Observable.OnSubscribe<Integer>() {
@Override public void call(Subscriber<? super Integer> subscriber) { | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/ToastUtil.java
// public class ToastUtil {
//
// private static Toast sToast;
//
// public static void showToastShort(Context context, String content) {
// if (sToast == null) {
// sToast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
// } else {
// sToast.setText(content);
// }
// sToast.show();
// }
//
// public static void showToastLong(Context context, String content) {
// if (sToast == null) {
// sToast = Toast.makeText(context, content, Toast.LENGTH_LONG);
// } else {
// sToast.setText(content);
// }
// sToast.show();
// }
//
// public static void showToastShort(Context context, int resId) {
// showToastShort(context, context.getResources().getString(resId));
// }
//
// public static void showToastLong(Context context, int resId) {
// showToastLong(context, context.getResources().getString(resId));
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/ui/fragment/SettingFragment.java
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import me.wavever.ganklock.R;
import me.wavever.ganklock.model.bean.GankDaily;
import me.wavever.ganklock.utils.ToastUtil;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action1;
package me.wavever.ganklock.ui.fragment;
/**
* Created by wavever on 2016/2/23.
*/
public class SettingFragment extends PreferenceFragment
implements Preference.OnPreferenceChangeListener,
Preference.OnPreferenceClickListener {
private Subscription subscription;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference(getString(R.string.key_lock_style)).setOnPreferenceClickListener(this);
findPreference(getString(R.string.key_shake_feed_back)).setOnPreferenceChangeListener(this);
findPreference("key_clear_cache").setOnPreferenceClickListener(this);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_shake_feed_back))) {
if ((Boolean) newValue) {
} else {
}
}
return true;
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_clear_cache))) {
Observable.create(new Observable.OnSubscribe<Integer>() {
@Override public void call(Subscriber<? super Integer> subscriber) { | new Delete().from(GankDaily.class).execute(); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/ui/fragment/SettingFragment.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/ToastUtil.java
// public class ToastUtil {
//
// private static Toast sToast;
//
// public static void showToastShort(Context context, String content) {
// if (sToast == null) {
// sToast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
// } else {
// sToast.setText(content);
// }
// sToast.show();
// }
//
// public static void showToastLong(Context context, String content) {
// if (sToast == null) {
// sToast = Toast.makeText(context, content, Toast.LENGTH_LONG);
// } else {
// sToast.setText(content);
// }
// sToast.show();
// }
//
// public static void showToastShort(Context context, int resId) {
// showToastShort(context, context.getResources().getString(resId));
// }
//
// public static void showToastLong(Context context, int resId) {
// showToastLong(context, context.getResources().getString(resId));
// }
// }
| import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import me.wavever.ganklock.R;
import me.wavever.ganklock.model.bean.GankDaily;
import me.wavever.ganklock.utils.ToastUtil;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action1; | addPreferencesFromResource(R.xml.preferences);
findPreference(getString(R.string.key_lock_style)).setOnPreferenceClickListener(this);
findPreference(getString(R.string.key_shake_feed_back)).setOnPreferenceChangeListener(this);
findPreference("key_clear_cache").setOnPreferenceClickListener(this);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_shake_feed_back))) {
if ((Boolean) newValue) {
} else {
}
}
return true;
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_clear_cache))) {
Observable.create(new Observable.OnSubscribe<Integer>() {
@Override public void call(Subscriber<? super Integer> subscriber) {
new Delete().from(GankDaily.class).execute();
subscriber.onNext(new Select().from(GankDaily.class).count());
}
}).subscribe(new Action1<Integer>() {
@Override public void call(Integer count) {
if (count == 0) { | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/ToastUtil.java
// public class ToastUtil {
//
// private static Toast sToast;
//
// public static void showToastShort(Context context, String content) {
// if (sToast == null) {
// sToast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
// } else {
// sToast.setText(content);
// }
// sToast.show();
// }
//
// public static void showToastLong(Context context, String content) {
// if (sToast == null) {
// sToast = Toast.makeText(context, content, Toast.LENGTH_LONG);
// } else {
// sToast.setText(content);
// }
// sToast.show();
// }
//
// public static void showToastShort(Context context, int resId) {
// showToastShort(context, context.getResources().getString(resId));
// }
//
// public static void showToastLong(Context context, int resId) {
// showToastLong(context, context.getResources().getString(resId));
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/ui/fragment/SettingFragment.java
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import me.wavever.ganklock.R;
import me.wavever.ganklock.model.bean.GankDaily;
import me.wavever.ganklock.utils.ToastUtil;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action1;
addPreferencesFromResource(R.xml.preferences);
findPreference(getString(R.string.key_lock_style)).setOnPreferenceClickListener(this);
findPreference(getString(R.string.key_shake_feed_back)).setOnPreferenceChangeListener(this);
findPreference("key_clear_cache").setOnPreferenceClickListener(this);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_shake_feed_back))) {
if ((Boolean) newValue) {
} else {
}
}
return true;
}
@Override
public boolean onPreferenceClick(Preference preference) {
String key = preference.getKey();
if (key.equals(getString(R.string.key_clear_cache))) {
Observable.create(new Observable.OnSubscribe<Integer>() {
@Override public void call(Subscriber<? super Integer> subscriber) {
new Delete().from(GankDaily.class).execute();
subscriber.onNext(new Select().from(GankDaily.class).count());
}
}).subscribe(new Action1<Integer>() {
@Override public void call(Integer count) {
if (count == 0) { | ToastUtil.showToastShort(getActivity(), "清除缓存成功~"); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/view/ILikeView.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
| import java.util.List;
import me.wavever.ganklock.model.bean.Gank; | package me.wavever.ganklock.view;
/**
* Created by wavever on 2016/9/2.
*/
public interface ILikeView extends IBaseView{
void showEmptyTip(); | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/view/ILikeView.java
import java.util.List;
import me.wavever.ganklock.model.bean.Gank;
package me.wavever.ganklock.view;
/**
* Created by wavever on 2016/9/2.
*/
public interface ILikeView extends IBaseView{
void showEmptyTip(); | void showLikeData(List<Gank> list); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/presenter/GankContentPresenter.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/data/ContentGankData.java
// public class ContentGankData {
//
// private GankService service = RetrofitUtil.getSingleton();
// private List<Gank> mList = new ArrayList<>();
//
// public void getDailyGankDataFromServer(String date, Observer observer) {
//
// service.getGankData(date)
// .map(new Function<GankContent, GankContent.Result>() {
// @Override
// public GankContent.Result apply(GankContent gankContent) throws Exception {
// return gankContent.results;
// }
// }).map(new Function<GankContent.Result, List<Gank>>() {
// @Override
// public List<Gank> apply(GankContent.Result result) throws Exception {
// return addAllResult(result);
// }
// }).subscribeOn(Schedulers.io()) //在io线程进行数据的读取 放在任何地方都可以
// .observeOn(AndroidSchedulers.mainThread()) //在主线程处理数据 指定的是它之后的操作的线程,因此如果需要多次切换线程,可指定多次
// .subscribe(observer);
// /*service.getGankData(date).flatMap(new Func1<GankContent, Observable<Gank>>() {
// @Override public Observable<Gank> call(GankContent gankContent) {
// return Observable.from(gankContent.results);
// }
// })
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);*/
// }
//
//
// private List<Gank> addAllResult(GankContent.Result results) {
// if (!mList.isEmpty()) mList.clear();
// if (results.androidList != null) mList.addAll(0, results.androidList);
// if (results.iosList != null) mList.addAll(results.iosList);
// if (results.htmlList != null) mList.addAll(results.htmlList);
// if (results.appList != null) mList.addAll(results.appList);
// if (results.recommendList != null) mList.addAll(results.recommendList);
// if(results.extendRespurseList != null) mList.addAll(results.extendRespurseList);
// if (results.restVideoList != null) mList.addAll(results.restVideoList);
// return mList;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/view/IGankContentView.java
// public interface IGankContentView extends IBaseView {
//
// void loadData(String date);
// void showData(List<Gank> list);
// void showError();
// }
| import java.util.List;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.model.data.ContentGankData;
import me.wavever.ganklock.view.IGankContentView; | package me.wavever.ganklock.presenter;
/**
* Created by wavever on 2016/3/4.
*/
public class GankContentPresenter extends BasePresenter<IGankContentView> {
private static final String TAG = "GankContentPresenter-->"; | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/data/ContentGankData.java
// public class ContentGankData {
//
// private GankService service = RetrofitUtil.getSingleton();
// private List<Gank> mList = new ArrayList<>();
//
// public void getDailyGankDataFromServer(String date, Observer observer) {
//
// service.getGankData(date)
// .map(new Function<GankContent, GankContent.Result>() {
// @Override
// public GankContent.Result apply(GankContent gankContent) throws Exception {
// return gankContent.results;
// }
// }).map(new Function<GankContent.Result, List<Gank>>() {
// @Override
// public List<Gank> apply(GankContent.Result result) throws Exception {
// return addAllResult(result);
// }
// }).subscribeOn(Schedulers.io()) //在io线程进行数据的读取 放在任何地方都可以
// .observeOn(AndroidSchedulers.mainThread()) //在主线程处理数据 指定的是它之后的操作的线程,因此如果需要多次切换线程,可指定多次
// .subscribe(observer);
// /*service.getGankData(date).flatMap(new Func1<GankContent, Observable<Gank>>() {
// @Override public Observable<Gank> call(GankContent gankContent) {
// return Observable.from(gankContent.results);
// }
// })
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);*/
// }
//
//
// private List<Gank> addAllResult(GankContent.Result results) {
// if (!mList.isEmpty()) mList.clear();
// if (results.androidList != null) mList.addAll(0, results.androidList);
// if (results.iosList != null) mList.addAll(results.iosList);
// if (results.htmlList != null) mList.addAll(results.htmlList);
// if (results.appList != null) mList.addAll(results.appList);
// if (results.recommendList != null) mList.addAll(results.recommendList);
// if(results.extendRespurseList != null) mList.addAll(results.extendRespurseList);
// if (results.restVideoList != null) mList.addAll(results.restVideoList);
// return mList;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/view/IGankContentView.java
// public interface IGankContentView extends IBaseView {
//
// void loadData(String date);
// void showData(List<Gank> list);
// void showError();
// }
// Path: app/src/main/java/me/wavever/ganklock/presenter/GankContentPresenter.java
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.model.data.ContentGankData;
import me.wavever.ganklock.view.IGankContentView;
package me.wavever.ganklock.presenter;
/**
* Created by wavever on 2016/3/4.
*/
public class GankContentPresenter extends BasePresenter<IGankContentView> {
private static final String TAG = "GankContentPresenter-->"; | private final ContentGankData contentGankData = new ContentGankData(); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/presenter/GankContentPresenter.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/data/ContentGankData.java
// public class ContentGankData {
//
// private GankService service = RetrofitUtil.getSingleton();
// private List<Gank> mList = new ArrayList<>();
//
// public void getDailyGankDataFromServer(String date, Observer observer) {
//
// service.getGankData(date)
// .map(new Function<GankContent, GankContent.Result>() {
// @Override
// public GankContent.Result apply(GankContent gankContent) throws Exception {
// return gankContent.results;
// }
// }).map(new Function<GankContent.Result, List<Gank>>() {
// @Override
// public List<Gank> apply(GankContent.Result result) throws Exception {
// return addAllResult(result);
// }
// }).subscribeOn(Schedulers.io()) //在io线程进行数据的读取 放在任何地方都可以
// .observeOn(AndroidSchedulers.mainThread()) //在主线程处理数据 指定的是它之后的操作的线程,因此如果需要多次切换线程,可指定多次
// .subscribe(observer);
// /*service.getGankData(date).flatMap(new Func1<GankContent, Observable<Gank>>() {
// @Override public Observable<Gank> call(GankContent gankContent) {
// return Observable.from(gankContent.results);
// }
// })
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);*/
// }
//
//
// private List<Gank> addAllResult(GankContent.Result results) {
// if (!mList.isEmpty()) mList.clear();
// if (results.androidList != null) mList.addAll(0, results.androidList);
// if (results.iosList != null) mList.addAll(results.iosList);
// if (results.htmlList != null) mList.addAll(results.htmlList);
// if (results.appList != null) mList.addAll(results.appList);
// if (results.recommendList != null) mList.addAll(results.recommendList);
// if(results.extendRespurseList != null) mList.addAll(results.extendRespurseList);
// if (results.restVideoList != null) mList.addAll(results.restVideoList);
// return mList;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/view/IGankContentView.java
// public interface IGankContentView extends IBaseView {
//
// void loadData(String date);
// void showData(List<Gank> list);
// void showError();
// }
| import java.util.List;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.model.data.ContentGankData;
import me.wavever.ganklock.view.IGankContentView; | package me.wavever.ganklock.presenter;
/**
* Created by wavever on 2016/3/4.
*/
public class GankContentPresenter extends BasePresenter<IGankContentView> {
private static final String TAG = "GankContentPresenter-->";
private final ContentGankData contentGankData = new ContentGankData();
public void loadContentData(String date) {
| // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/model/data/ContentGankData.java
// public class ContentGankData {
//
// private GankService service = RetrofitUtil.getSingleton();
// private List<Gank> mList = new ArrayList<>();
//
// public void getDailyGankDataFromServer(String date, Observer observer) {
//
// service.getGankData(date)
// .map(new Function<GankContent, GankContent.Result>() {
// @Override
// public GankContent.Result apply(GankContent gankContent) throws Exception {
// return gankContent.results;
// }
// }).map(new Function<GankContent.Result, List<Gank>>() {
// @Override
// public List<Gank> apply(GankContent.Result result) throws Exception {
// return addAllResult(result);
// }
// }).subscribeOn(Schedulers.io()) //在io线程进行数据的读取 放在任何地方都可以
// .observeOn(AndroidSchedulers.mainThread()) //在主线程处理数据 指定的是它之后的操作的线程,因此如果需要多次切换线程,可指定多次
// .subscribe(observer);
// /*service.getGankData(date).flatMap(new Func1<GankContent, Observable<Gank>>() {
// @Override public Observable<Gank> call(GankContent gankContent) {
// return Observable.from(gankContent.results);
// }
// })
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber);*/
// }
//
//
// private List<Gank> addAllResult(GankContent.Result results) {
// if (!mList.isEmpty()) mList.clear();
// if (results.androidList != null) mList.addAll(0, results.androidList);
// if (results.iosList != null) mList.addAll(results.iosList);
// if (results.htmlList != null) mList.addAll(results.htmlList);
// if (results.appList != null) mList.addAll(results.appList);
// if (results.recommendList != null) mList.addAll(results.recommendList);
// if(results.extendRespurseList != null) mList.addAll(results.extendRespurseList);
// if (results.restVideoList != null) mList.addAll(results.restVideoList);
// return mList;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/view/IGankContentView.java
// public interface IGankContentView extends IBaseView {
//
// void loadData(String date);
// void showData(List<Gank> list);
// void showError();
// }
// Path: app/src/main/java/me/wavever/ganklock/presenter/GankContentPresenter.java
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.model.data.ContentGankData;
import me.wavever.ganklock.view.IGankContentView;
package me.wavever.ganklock.presenter;
/**
* Created by wavever on 2016/3/4.
*/
public class GankContentPresenter extends BasePresenter<IGankContentView> {
private static final String TAG = "GankContentPresenter-->";
private final ContentGankData contentGankData = new ContentGankData();
public void loadContentData(String date) {
| Observer observer = new Observer<List<Gank>>() { |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/MyApplication.java | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/service/LockService.java
// public class LockService extends Service {
//
// private BroadcastReceiver receiver;
//
// @Override
// public void onCreate() {
// super.onCreate();
// IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction(Intent.ACTION_SCREEN_ON);
// intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
// receiver = new GankLockReceiver();
// registerReceiver(receiver, intentFilter);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// return Service.START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// if(PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)){
// //LockManager.startLock(false);
// startService(new Intent(LockService.this,LockService.class));
// return;
// }
// unregisterReceiver(receiver);
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import com.activeandroid.app.Application;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.service.LockService;
import me.wavever.ganklock.utils.PreferenceUtil; | package me.wavever.ganklock;
/**
* Created by wavever on 2016/3/2.
*/
public class MyApplication extends Application{
private static Context context;
| // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/service/LockService.java
// public class LockService extends Service {
//
// private BroadcastReceiver receiver;
//
// @Override
// public void onCreate() {
// super.onCreate();
// IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction(Intent.ACTION_SCREEN_ON);
// intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
// receiver = new GankLockReceiver();
// registerReceiver(receiver, intentFilter);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// return Service.START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// if(PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)){
// //LockManager.startLock(false);
// startService(new Intent(LockService.this,LockService.class));
// return;
// }
// unregisterReceiver(receiver);
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
import android.content.Context;
import android.content.Intent;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import com.activeandroid.app.Application;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.service.LockService;
import me.wavever.ganklock.utils.PreferenceUtil;
package me.wavever.ganklock;
/**
* Created by wavever on 2016/3/2.
*/
public class MyApplication extends Application{
private static Context context;
| private static PreferenceUtil sp; |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/MyApplication.java | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/service/LockService.java
// public class LockService extends Service {
//
// private BroadcastReceiver receiver;
//
// @Override
// public void onCreate() {
// super.onCreate();
// IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction(Intent.ACTION_SCREEN_ON);
// intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
// receiver = new GankLockReceiver();
// registerReceiver(receiver, intentFilter);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// return Service.START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// if(PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)){
// //LockManager.startLock(false);
// startService(new Intent(LockService.this,LockService.class));
// return;
// }
// unregisterReceiver(receiver);
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import com.activeandroid.app.Application;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.service.LockService;
import me.wavever.ganklock.utils.PreferenceUtil; | package me.wavever.ganklock;
/**
* Created by wavever on 2016/3/2.
*/
public class MyApplication extends Application{
private static Context context;
private static PreferenceUtil sp;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext(); | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/service/LockService.java
// public class LockService extends Service {
//
// private BroadcastReceiver receiver;
//
// @Override
// public void onCreate() {
// super.onCreate();
// IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction(Intent.ACTION_SCREEN_ON);
// intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
// receiver = new GankLockReceiver();
// registerReceiver(receiver, intentFilter);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// return Service.START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// if(PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)){
// //LockManager.startLock(false);
// startService(new Intent(LockService.this,LockService.class));
// return;
// }
// unregisterReceiver(receiver);
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
import android.content.Context;
import android.content.Intent;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import com.activeandroid.app.Application;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.service.LockService;
import me.wavever.ganklock.utils.PreferenceUtil;
package me.wavever.ganklock;
/**
* Created by wavever on 2016/3/2.
*/
public class MyApplication extends Application{
private static Context context;
private static PreferenceUtil sp;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext(); | if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) { |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/MyApplication.java | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/service/LockService.java
// public class LockService extends Service {
//
// private BroadcastReceiver receiver;
//
// @Override
// public void onCreate() {
// super.onCreate();
// IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction(Intent.ACTION_SCREEN_ON);
// intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
// receiver = new GankLockReceiver();
// registerReceiver(receiver, intentFilter);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// return Service.START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// if(PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)){
// //LockManager.startLock(false);
// startService(new Intent(LockService.this,LockService.class));
// return;
// }
// unregisterReceiver(receiver);
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import com.activeandroid.app.Application;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.service.LockService;
import me.wavever.ganklock.utils.PreferenceUtil; | package me.wavever.ganklock;
/**
* Created by wavever on 2016/3/2.
*/
public class MyApplication extends Application{
private static Context context;
private static PreferenceUtil sp;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) { | // Path: app/src/main/java/me/wavever/ganklock/config/Config.java
// public class Config {
//
// public static final String IS_FIRST_RUN = "IS_FIRST_RUN";
//
// public static final String GANK_LOCK_IS_OPEN = "LOCK_IS_OPEN";
//
// public static final String LAST_GET_DATE = "LAST_GET_DATE";
//
// public static final String GET_TODAY_DATA = "GET_DATA";
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/service/LockService.java
// public class LockService extends Service {
//
// private BroadcastReceiver receiver;
//
// @Override
// public void onCreate() {
// super.onCreate();
// IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction(Intent.ACTION_SCREEN_ON);
// intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
// receiver = new GankLockReceiver();
// registerReceiver(receiver, intentFilter);
// }
//
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// return Service.START_STICKY;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// if(PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)){
// //LockManager.startLock(false);
// startService(new Intent(LockService.this,LockService.class));
// return;
// }
// unregisterReceiver(receiver);
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// return null;
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
// public class PreferenceUtil {
// private static SharedPreferences prefs;
// private static Editor editor;
//
//
// static {
// prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
// editor = prefs.edit();
// }
//
//
// public static void putString(String key, String value) {
// editor.putString(key, value).apply();
// }
//
//
// public static String getString(String key) {
// return prefs.getString(key, "");
// }
//
//
// public static void putInt(String key, int value) {
// editor.putInt(key, value).apply();
// }
//
//
// public static int getInt(String key,int value) {
// return prefs.getInt(key, value);
// }
//
//
// public static void putBoolean(String key, boolean value) {
// editor.putBoolean(key, value).apply();//apply没有返回值,commit返回值为布尔值
// }
//
// public static boolean getBoolean(String key) {
// return prefs.getBoolean(key, false);
// }
//
//
// public static boolean clear() {
// editor.clear();
// return editor.commit();
// }
//
//
// public static void close() {
// prefs = null;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
import android.content.Context;
import android.content.Intent;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import com.activeandroid.app.Application;
import me.wavever.ganklock.config.Config;
import me.wavever.ganklock.service.LockService;
import me.wavever.ganklock.utils.PreferenceUtil;
package me.wavever.ganklock;
/**
* Created by wavever on 2016/3/2.
*/
public class MyApplication extends Application{
private static Context context;
private static PreferenceUtil sp;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) { | context.startService(new Intent(context, LockService.class)); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/view/IDailyGankView.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
| import java.util.List;
import me.wavever.ganklock.model.bean.GankDaily; | package me.wavever.ganklock.view;
/**
* Created by wavever on 2016/8/14.
*/
public interface IDailyGankView extends IBaseView{
void showLoading();
void loadDailyData(int page);
void loadFailure();
void loadTodayDailyData(); | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
// Path: app/src/main/java/me/wavever/ganklock/view/IDailyGankView.java
import java.util.List;
import me.wavever.ganklock.model.bean.GankDaily;
package me.wavever.ganklock.view;
/**
* Created by wavever on 2016/8/14.
*/
public interface IDailyGankView extends IBaseView{
void showLoading();
void loadDailyData(int page);
void loadFailure();
void loadTodayDailyData(); | void showDailyData(List<GankDaily> ganks); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/event/ClickEvent.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
| import me.wavever.ganklock.model.bean.GankDaily; | package me.wavever.ganklock.event;
/**
* Created by wavever on 2016/9/26.
*/
public class ClickEvent {
public static final int CLICK_TYPE_DAILY_PHOTO = 0;
public static final int CLICK_TYPE_DAILY_TITLE = 1;
public static final int CLICK_TYPE_MEIZHI = 2;
public static final int CLICK_TYPE_LIKE = 3;
public int eventType;
| // Path: app/src/main/java/me/wavever/ganklock/model/bean/GankDaily.java
// @Table(name = "GankDaily")
// public class GankDaily extends Model {
// @SerializedName(value = "_id")
// @Column(name = "_id")
// public String _id;
// @SerializedName(value = "publishedAt")
// @Column(name = "publishedAt")
// public String publishedAt;
// @SerializedName(value = "title")
// @Column(name = "title")
// public String title;
// @SerializedName(value = "content")
// @Column(name = "content")
// public String content;//妹纸图的url
// }
// Path: app/src/main/java/me/wavever/ganklock/event/ClickEvent.java
import me.wavever.ganklock.model.bean.GankDaily;
package me.wavever.ganklock.event;
/**
* Created by wavever on 2016/9/26.
*/
public class ClickEvent {
public static final int CLICK_TYPE_DAILY_PHOTO = 0;
public static final int CLICK_TYPE_DAILY_TITLE = 1;
public static final int CLICK_TYPE_MEIZHI = 2;
public static final int CLICK_TYPE_LIKE = 3;
public int eventType;
| public GankDaily gankDaily; |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/presenter/LikePresenter.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/LogUtil.java
// public class LogUtil {
//
// private static final String TAG = "TAG";
//
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WRAN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static final int LEVEL = VERBOSE;
//
// //只需要修改LEVEL的值,就可以自由的控制日志的打印,
// // 当LEVEL为NOTHING时,就可以屏蔽掉所有的日志
//
// public static void v(String message) {
// if (LEVEL <= VERBOSE) {
// Log.v(TAG, message);
// }
// }
//
// public static void d(String message) {
// if (LEVEL <= DEBUG) {
// Log.d(TAG,message);
// }
// }
//
// public static void i(String message) {
// if (LEVEL <= INFO) {
// Log.i(TAG,message);
// }
// }
//
// public static void w(String message) {
// if (LEVEL <= WRAN) {
// Log.w(TAG,message);
// }
// }
//
// public static void e(String message) {
// if (LEVEL <= ERROR) {
// Log.e(TAG,message);
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/view/ILikeView.java
// public interface ILikeView extends IBaseView{
// void showEmptyTip();
// void showLikeData(List<Gank> list);
// void refreshLikeData(List<Gank> list);
// }
| import com.activeandroid.query.Select;
import java.util.List;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.utils.LogUtil;
import me.wavever.ganklock.view.ILikeView; | package me.wavever.ganklock.presenter;
/**
* Created by wavever on 2016/9/2.
*/
public class LikePresenter extends BasePresenter<ILikeView>{
private static final String TAG = LikePresenter.class.getSimpleName()+"-->";
public void getLikeList(){ | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/LogUtil.java
// public class LogUtil {
//
// private static final String TAG = "TAG";
//
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WRAN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static final int LEVEL = VERBOSE;
//
// //只需要修改LEVEL的值,就可以自由的控制日志的打印,
// // 当LEVEL为NOTHING时,就可以屏蔽掉所有的日志
//
// public static void v(String message) {
// if (LEVEL <= VERBOSE) {
// Log.v(TAG, message);
// }
// }
//
// public static void d(String message) {
// if (LEVEL <= DEBUG) {
// Log.d(TAG,message);
// }
// }
//
// public static void i(String message) {
// if (LEVEL <= INFO) {
// Log.i(TAG,message);
// }
// }
//
// public static void w(String message) {
// if (LEVEL <= WRAN) {
// Log.w(TAG,message);
// }
// }
//
// public static void e(String message) {
// if (LEVEL <= ERROR) {
// Log.e(TAG,message);
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/view/ILikeView.java
// public interface ILikeView extends IBaseView{
// void showEmptyTip();
// void showLikeData(List<Gank> list);
// void refreshLikeData(List<Gank> list);
// }
// Path: app/src/main/java/me/wavever/ganklock/presenter/LikePresenter.java
import com.activeandroid.query.Select;
import java.util.List;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.utils.LogUtil;
import me.wavever.ganklock.view.ILikeView;
package me.wavever.ganklock.presenter;
/**
* Created by wavever on 2016/9/2.
*/
public class LikePresenter extends BasePresenter<ILikeView>{
private static final String TAG = LikePresenter.class.getSimpleName()+"-->";
public void getLikeList(){ | List<Gank> list = new Select().from(Gank.class).execute(); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/presenter/LikePresenter.java | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/LogUtil.java
// public class LogUtil {
//
// private static final String TAG = "TAG";
//
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WRAN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static final int LEVEL = VERBOSE;
//
// //只需要修改LEVEL的值,就可以自由的控制日志的打印,
// // 当LEVEL为NOTHING时,就可以屏蔽掉所有的日志
//
// public static void v(String message) {
// if (LEVEL <= VERBOSE) {
// Log.v(TAG, message);
// }
// }
//
// public static void d(String message) {
// if (LEVEL <= DEBUG) {
// Log.d(TAG,message);
// }
// }
//
// public static void i(String message) {
// if (LEVEL <= INFO) {
// Log.i(TAG,message);
// }
// }
//
// public static void w(String message) {
// if (LEVEL <= WRAN) {
// Log.w(TAG,message);
// }
// }
//
// public static void e(String message) {
// if (LEVEL <= ERROR) {
// Log.e(TAG,message);
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/view/ILikeView.java
// public interface ILikeView extends IBaseView{
// void showEmptyTip();
// void showLikeData(List<Gank> list);
// void refreshLikeData(List<Gank> list);
// }
| import com.activeandroid.query.Select;
import java.util.List;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.utils.LogUtil;
import me.wavever.ganklock.view.ILikeView; | package me.wavever.ganklock.presenter;
/**
* Created by wavever on 2016/9/2.
*/
public class LikePresenter extends BasePresenter<ILikeView>{
private static final String TAG = LikePresenter.class.getSimpleName()+"-->";
public void getLikeList(){
List<Gank> list = new Select().from(Gank.class).execute();
for(Gank gank:list){ | // Path: app/src/main/java/me/wavever/ganklock/model/bean/Gank.java
// @Table(name = "Ganks") public class Gank extends Model implements Serializable {
//
// @Column(name = "_id") private String _id;
// @Column(name = "url") private String url;
// @Column(name = "desc") private String desc;
// @Column(name = "who") private String who;
// @Column(name = "type") private String type;
// @Column(name = "used") private boolean used;
// @Column(name = "createdAt") private Date createdAt;
// //2016-03-10T12:54:31.68Z->2016/03/10
// @Column(name = "publishedAt") private Date publishedAt;
// private boolean isLike;
//
//
// public String get_id() {
// return _id;
// }
//
//
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public String getUrl() {
// return url;
// }
//
//
// public String getDesc() {
// return desc;
// }
//
//
// public String getWho() {
// return who;
// }
//
//
// public String getType() {
// return type;
// }
//
//
// public boolean isUsed() {
// return used;
// }
//
//
// public Date getCreateAt() {
// return createdAt;
// }
//
//
// public Date getPublishedAt() {
// return publishedAt;
// }
//
//
// public void setIsLike(boolean like) {
// isLike = like;
// }
//
// public boolean getIsLike() {
// return isLike;
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/utils/LogUtil.java
// public class LogUtil {
//
// private static final String TAG = "TAG";
//
// public static final int VERBOSE = 1;
//
// public static final int DEBUG = 2;
//
// public static final int INFO = 3;
//
// public static final int WRAN = 4;
//
// public static final int ERROR = 5;
//
// public static final int NOTHING = 6;
//
// public static final int LEVEL = VERBOSE;
//
// //只需要修改LEVEL的值,就可以自由的控制日志的打印,
// // 当LEVEL为NOTHING时,就可以屏蔽掉所有的日志
//
// public static void v(String message) {
// if (LEVEL <= VERBOSE) {
// Log.v(TAG, message);
// }
// }
//
// public static void d(String message) {
// if (LEVEL <= DEBUG) {
// Log.d(TAG,message);
// }
// }
//
// public static void i(String message) {
// if (LEVEL <= INFO) {
// Log.i(TAG,message);
// }
// }
//
// public static void w(String message) {
// if (LEVEL <= WRAN) {
// Log.w(TAG,message);
// }
// }
//
// public static void e(String message) {
// if (LEVEL <= ERROR) {
// Log.e(TAG,message);
// }
// }
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/view/ILikeView.java
// public interface ILikeView extends IBaseView{
// void showEmptyTip();
// void showLikeData(List<Gank> list);
// void refreshLikeData(List<Gank> list);
// }
// Path: app/src/main/java/me/wavever/ganklock/presenter/LikePresenter.java
import com.activeandroid.query.Select;
import java.util.List;
import me.wavever.ganklock.model.bean.Gank;
import me.wavever.ganklock.utils.LogUtil;
import me.wavever.ganklock.view.ILikeView;
package me.wavever.ganklock.presenter;
/**
* Created by wavever on 2016/9/2.
*/
public class LikePresenter extends BasePresenter<ILikeView>{
private static final String TAG = LikePresenter.class.getSimpleName()+"-->";
public void getLikeList(){
List<Gank> list = new Select().from(Gank.class).execute();
for(Gank gank:list){ | LogUtil.d(TAG+"收藏"+gank.getDesc()); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/ui/activity/SettingActivity.java | // Path: app/src/main/java/me/wavever/ganklock/ui/fragment/SettingFragment.java
// public class SettingFragment extends PreferenceFragment
// implements Preference.OnPreferenceChangeListener,
// Preference.OnPreferenceClickListener {
//
// private Subscription subscription;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.xml.preferences);
// findPreference(getString(R.string.key_lock_style)).setOnPreferenceClickListener(this);
// findPreference(getString(R.string.key_shake_feed_back)).setOnPreferenceChangeListener(this);
// findPreference("key_clear_cache").setOnPreferenceClickListener(this);
// }
//
//
// @Override
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// String key = preference.getKey();
// if (key.equals(getString(R.string.key_shake_feed_back))) {
// if ((Boolean) newValue) {
// } else {
// }
// }
// return true;
// }
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
// String key = preference.getKey();
// if (key.equals(getString(R.string.key_clear_cache))) {
// Observable.create(new Observable.OnSubscribe<Integer>() {
// @Override public void call(Subscriber<? super Integer> subscriber) {
// new Delete().from(GankDaily.class).execute();
// subscriber.onNext(new Select().from(GankDaily.class).count());
// }
// }).subscribe(new Action1<Integer>() {
// @Override public void call(Integer count) {
// if (count == 0) {
// ToastUtil.showToastShort(getActivity(), "清除缓存成功~");
// } else {
// ToastUtil.showToastShort(getActivity(), "清除缓存失败~");
// }
// }
// });
// } else if (key.equals(getString(R.string.key_lock_style))) {
// ToastUtil.showToastShort(getActivity(), "正在开发中哦");
// }
// return false;
// }
//
//
// @Override public void onDestroy() {
// super.onDestroy();
// }
// }
| import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import me.wavever.ganklock.R;
import me.wavever.ganklock.ui.fragment.SettingFragment; | package me.wavever.ganklock.ui.activity;
/**
* Created by wavever on 2016/2/23.
*/
public class SettingActivity extends BaseActivity {
private Toolbar mToolbar;
@Override protected int loadView() {
return R.layout.activity_setting;
}
@Override protected void initView() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
setTitle(R.string.action_setting);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: app/src/main/java/me/wavever/ganklock/ui/fragment/SettingFragment.java
// public class SettingFragment extends PreferenceFragment
// implements Preference.OnPreferenceChangeListener,
// Preference.OnPreferenceClickListener {
//
// private Subscription subscription;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// addPreferencesFromResource(R.xml.preferences);
// findPreference(getString(R.string.key_lock_style)).setOnPreferenceClickListener(this);
// findPreference(getString(R.string.key_shake_feed_back)).setOnPreferenceChangeListener(this);
// findPreference("key_clear_cache").setOnPreferenceClickListener(this);
// }
//
//
// @Override
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// String key = preference.getKey();
// if (key.equals(getString(R.string.key_shake_feed_back))) {
// if ((Boolean) newValue) {
// } else {
// }
// }
// return true;
// }
//
// @Override
// public boolean onPreferenceClick(Preference preference) {
// String key = preference.getKey();
// if (key.equals(getString(R.string.key_clear_cache))) {
// Observable.create(new Observable.OnSubscribe<Integer>() {
// @Override public void call(Subscriber<? super Integer> subscriber) {
// new Delete().from(GankDaily.class).execute();
// subscriber.onNext(new Select().from(GankDaily.class).count());
// }
// }).subscribe(new Action1<Integer>() {
// @Override public void call(Integer count) {
// if (count == 0) {
// ToastUtil.showToastShort(getActivity(), "清除缓存成功~");
// } else {
// ToastUtil.showToastShort(getActivity(), "清除缓存失败~");
// }
// }
// });
// } else if (key.equals(getString(R.string.key_lock_style))) {
// ToastUtil.showToastShort(getActivity(), "正在开发中哦");
// }
// return false;
// }
//
//
// @Override public void onDestroy() {
// super.onDestroy();
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/ui/activity/SettingActivity.java
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import me.wavever.ganklock.R;
import me.wavever.ganklock.ui.fragment.SettingFragment;
package me.wavever.ganklock.ui.activity;
/**
* Created by wavever on 2016/2/23.
*/
public class SettingActivity extends BaseActivity {
private Toolbar mToolbar;
@Override protected int loadView() {
return R.layout.activity_setting;
}
@Override protected void initView() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
setTitle(R.string.action_setting);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | replaceFragment(R.id.setting_container, new SettingFragment()); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/ui/adapter/MeizhiRecyclerViewAdapter.java | // Path: app/src/main/java/me/wavever/ganklock/event/ClickEvent.java
// public class ClickEvent {
//
// public static final int CLICK_TYPE_DAILY_PHOTO = 0;
// public static final int CLICK_TYPE_DAILY_TITLE = 1;
//
// public static final int CLICK_TYPE_MEIZHI = 2;
//
// public static final int CLICK_TYPE_LIKE = 3;
//
// public int eventType;
//
// public GankDaily gankDaily;
//
// public int position;
//
// public ClickEvent(int eventType,GankDaily gankDaily) {
// this.eventType = eventType;
// this.gankDaily = gankDaily;
// }
//
// public ClickEvent(int eventType,int position) {
// this.eventType = eventType;
// this.position = position;
// }
//
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/event/RxBus.java
// public class RxBus {
//
// private static volatile RxBus instance;
//
// private final SerializedSubject<Object, Object> subject;
//
// private RxBus() {
// subject = new SerializedSubject<>(PublishSubject.create());
// }
//
// /**
// * 单例模式获取RxBus
// *
// * @return
// */
// public static RxBus getInstance() {
// RxBus rxBus = instance;
// if (instance == null) {
// synchronized (RxBus.class) {
// rxBus = instance;
// if (instance == null) {
// rxBus = new RxBus();
// instance = rxBus;
// }
// }
// }
// return rxBus;
// }
//
// /**
// * 发送一个新的事件
// *
// * @param object
// */
// public void post(Object object) {
// subject.onNext(object);
// }
//
// /**
// * 根据传递的eventType类型返回特定的被观察者
// * @param eventType
// * @param <T>
// * @return
// */
// public <T> Observable<T> tObservable(Class<T> eventType) {
// return subject.ofType(eventType);
// }
//
// public boolean hasObservers() {
// return subject.hasObservers();
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/ui/adapter/MeizhiRecyclerViewAdapter.java
// class MeizhiViewHolder extends ViewHolder {
//
// ImageView img;
// int position;
//
// public MeizhiViewHolder(View itemView) {
// super(itemView);
// img = (ImageView) itemView.findViewById(R.id.item_photo);
// img.setOnClickListener(new View.OnClickListener() {
// @Override public void onClick(View v) {
// RxBus.getInstance()
// .post(new ClickEvent(ClickEvent.CLICK_TYPE_MEIZHI, position));
// }
// });
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.List;
import me.wavever.ganklock.R;
import me.wavever.ganklock.event.ClickEvent;
import me.wavever.ganklock.event.RxBus;
import me.wavever.ganklock.ui.adapter.MeizhiRecyclerViewAdapter.MeizhiViewHolder; |
@Override
public MeizhiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_meizhi_recycler_view, parent, false);
return new MeizhiViewHolder(view);
}
@Override
public void onBindViewHolder(MeizhiViewHolder holder, int position) {
holder.position = position;
Picasso.with(mContext).load(mList.get(position)).resize(300,300).centerCrop().into(holder.img);
}
@Override public int getItemCount() {
return mList == null ? 0 : mList.size();
}
class MeizhiViewHolder extends ViewHolder {
ImageView img;
int position;
public MeizhiViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.item_photo);
img.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { | // Path: app/src/main/java/me/wavever/ganklock/event/ClickEvent.java
// public class ClickEvent {
//
// public static final int CLICK_TYPE_DAILY_PHOTO = 0;
// public static final int CLICK_TYPE_DAILY_TITLE = 1;
//
// public static final int CLICK_TYPE_MEIZHI = 2;
//
// public static final int CLICK_TYPE_LIKE = 3;
//
// public int eventType;
//
// public GankDaily gankDaily;
//
// public int position;
//
// public ClickEvent(int eventType,GankDaily gankDaily) {
// this.eventType = eventType;
// this.gankDaily = gankDaily;
// }
//
// public ClickEvent(int eventType,int position) {
// this.eventType = eventType;
// this.position = position;
// }
//
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/event/RxBus.java
// public class RxBus {
//
// private static volatile RxBus instance;
//
// private final SerializedSubject<Object, Object> subject;
//
// private RxBus() {
// subject = new SerializedSubject<>(PublishSubject.create());
// }
//
// /**
// * 单例模式获取RxBus
// *
// * @return
// */
// public static RxBus getInstance() {
// RxBus rxBus = instance;
// if (instance == null) {
// synchronized (RxBus.class) {
// rxBus = instance;
// if (instance == null) {
// rxBus = new RxBus();
// instance = rxBus;
// }
// }
// }
// return rxBus;
// }
//
// /**
// * 发送一个新的事件
// *
// * @param object
// */
// public void post(Object object) {
// subject.onNext(object);
// }
//
// /**
// * 根据传递的eventType类型返回特定的被观察者
// * @param eventType
// * @param <T>
// * @return
// */
// public <T> Observable<T> tObservable(Class<T> eventType) {
// return subject.ofType(eventType);
// }
//
// public boolean hasObservers() {
// return subject.hasObservers();
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/ui/adapter/MeizhiRecyclerViewAdapter.java
// class MeizhiViewHolder extends ViewHolder {
//
// ImageView img;
// int position;
//
// public MeizhiViewHolder(View itemView) {
// super(itemView);
// img = (ImageView) itemView.findViewById(R.id.item_photo);
// img.setOnClickListener(new View.OnClickListener() {
// @Override public void onClick(View v) {
// RxBus.getInstance()
// .post(new ClickEvent(ClickEvent.CLICK_TYPE_MEIZHI, position));
// }
// });
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/ui/adapter/MeizhiRecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.List;
import me.wavever.ganklock.R;
import me.wavever.ganklock.event.ClickEvent;
import me.wavever.ganklock.event.RxBus;
import me.wavever.ganklock.ui.adapter.MeizhiRecyclerViewAdapter.MeizhiViewHolder;
@Override
public MeizhiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_meizhi_recycler_view, parent, false);
return new MeizhiViewHolder(view);
}
@Override
public void onBindViewHolder(MeizhiViewHolder holder, int position) {
holder.position = position;
Picasso.with(mContext).load(mList.get(position)).resize(300,300).centerCrop().into(holder.img);
}
@Override public int getItemCount() {
return mList == null ? 0 : mList.size();
}
class MeizhiViewHolder extends ViewHolder {
ImageView img;
int position;
public MeizhiViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.item_photo);
img.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) { | RxBus.getInstance() |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/ui/adapter/MeizhiRecyclerViewAdapter.java | // Path: app/src/main/java/me/wavever/ganklock/event/ClickEvent.java
// public class ClickEvent {
//
// public static final int CLICK_TYPE_DAILY_PHOTO = 0;
// public static final int CLICK_TYPE_DAILY_TITLE = 1;
//
// public static final int CLICK_TYPE_MEIZHI = 2;
//
// public static final int CLICK_TYPE_LIKE = 3;
//
// public int eventType;
//
// public GankDaily gankDaily;
//
// public int position;
//
// public ClickEvent(int eventType,GankDaily gankDaily) {
// this.eventType = eventType;
// this.gankDaily = gankDaily;
// }
//
// public ClickEvent(int eventType,int position) {
// this.eventType = eventType;
// this.position = position;
// }
//
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/event/RxBus.java
// public class RxBus {
//
// private static volatile RxBus instance;
//
// private final SerializedSubject<Object, Object> subject;
//
// private RxBus() {
// subject = new SerializedSubject<>(PublishSubject.create());
// }
//
// /**
// * 单例模式获取RxBus
// *
// * @return
// */
// public static RxBus getInstance() {
// RxBus rxBus = instance;
// if (instance == null) {
// synchronized (RxBus.class) {
// rxBus = instance;
// if (instance == null) {
// rxBus = new RxBus();
// instance = rxBus;
// }
// }
// }
// return rxBus;
// }
//
// /**
// * 发送一个新的事件
// *
// * @param object
// */
// public void post(Object object) {
// subject.onNext(object);
// }
//
// /**
// * 根据传递的eventType类型返回特定的被观察者
// * @param eventType
// * @param <T>
// * @return
// */
// public <T> Observable<T> tObservable(Class<T> eventType) {
// return subject.ofType(eventType);
// }
//
// public boolean hasObservers() {
// return subject.hasObservers();
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/ui/adapter/MeizhiRecyclerViewAdapter.java
// class MeizhiViewHolder extends ViewHolder {
//
// ImageView img;
// int position;
//
// public MeizhiViewHolder(View itemView) {
// super(itemView);
// img = (ImageView) itemView.findViewById(R.id.item_photo);
// img.setOnClickListener(new View.OnClickListener() {
// @Override public void onClick(View v) {
// RxBus.getInstance()
// .post(new ClickEvent(ClickEvent.CLICK_TYPE_MEIZHI, position));
// }
// });
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.List;
import me.wavever.ganklock.R;
import me.wavever.ganklock.event.ClickEvent;
import me.wavever.ganklock.event.RxBus;
import me.wavever.ganklock.ui.adapter.MeizhiRecyclerViewAdapter.MeizhiViewHolder; | @Override
public MeizhiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_meizhi_recycler_view, parent, false);
return new MeizhiViewHolder(view);
}
@Override
public void onBindViewHolder(MeizhiViewHolder holder, int position) {
holder.position = position;
Picasso.with(mContext).load(mList.get(position)).resize(300,300).centerCrop().into(holder.img);
}
@Override public int getItemCount() {
return mList == null ? 0 : mList.size();
}
class MeizhiViewHolder extends ViewHolder {
ImageView img;
int position;
public MeizhiViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.item_photo);
img.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
RxBus.getInstance() | // Path: app/src/main/java/me/wavever/ganklock/event/ClickEvent.java
// public class ClickEvent {
//
// public static final int CLICK_TYPE_DAILY_PHOTO = 0;
// public static final int CLICK_TYPE_DAILY_TITLE = 1;
//
// public static final int CLICK_TYPE_MEIZHI = 2;
//
// public static final int CLICK_TYPE_LIKE = 3;
//
// public int eventType;
//
// public GankDaily gankDaily;
//
// public int position;
//
// public ClickEvent(int eventType,GankDaily gankDaily) {
// this.eventType = eventType;
// this.gankDaily = gankDaily;
// }
//
// public ClickEvent(int eventType,int position) {
// this.eventType = eventType;
// this.position = position;
// }
//
//
// }
//
// Path: app/src/main/java/me/wavever/ganklock/event/RxBus.java
// public class RxBus {
//
// private static volatile RxBus instance;
//
// private final SerializedSubject<Object, Object> subject;
//
// private RxBus() {
// subject = new SerializedSubject<>(PublishSubject.create());
// }
//
// /**
// * 单例模式获取RxBus
// *
// * @return
// */
// public static RxBus getInstance() {
// RxBus rxBus = instance;
// if (instance == null) {
// synchronized (RxBus.class) {
// rxBus = instance;
// if (instance == null) {
// rxBus = new RxBus();
// instance = rxBus;
// }
// }
// }
// return rxBus;
// }
//
// /**
// * 发送一个新的事件
// *
// * @param object
// */
// public void post(Object object) {
// subject.onNext(object);
// }
//
// /**
// * 根据传递的eventType类型返回特定的被观察者
// * @param eventType
// * @param <T>
// * @return
// */
// public <T> Observable<T> tObservable(Class<T> eventType) {
// return subject.ofType(eventType);
// }
//
// public boolean hasObservers() {
// return subject.hasObservers();
// }
// }
//
// Path: app/src/main/java/me/wavever/ganklock/ui/adapter/MeizhiRecyclerViewAdapter.java
// class MeizhiViewHolder extends ViewHolder {
//
// ImageView img;
// int position;
//
// public MeizhiViewHolder(View itemView) {
// super(itemView);
// img = (ImageView) itemView.findViewById(R.id.item_photo);
// img.setOnClickListener(new View.OnClickListener() {
// @Override public void onClick(View v) {
// RxBus.getInstance()
// .post(new ClickEvent(ClickEvent.CLICK_TYPE_MEIZHI, position));
// }
// });
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/ui/adapter/MeizhiRecyclerViewAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.List;
import me.wavever.ganklock.R;
import me.wavever.ganklock.event.ClickEvent;
import me.wavever.ganklock.event.RxBus;
import me.wavever.ganklock.ui.adapter.MeizhiRecyclerViewAdapter.MeizhiViewHolder;
@Override
public MeizhiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_meizhi_recycler_view, parent, false);
return new MeizhiViewHolder(view);
}
@Override
public void onBindViewHolder(MeizhiViewHolder holder, int position) {
holder.position = position;
Picasso.with(mContext).load(mList.get(position)).resize(300,300).centerCrop().into(holder.img);
}
@Override public int getItemCount() {
return mList == null ? 0 : mList.size();
}
class MeizhiViewHolder extends ViewHolder {
ImageView img;
int position;
public MeizhiViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.item_photo);
img.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
RxBus.getInstance() | .post(new ClickEvent(ClickEvent.CLICK_TYPE_MEIZHI, position)); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
| import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import me.wavever.ganklock.MyApplication; | package me.wavever.ganklock.utils;
public class PreferenceUtil {
private static SharedPreferences prefs;
private static Editor editor;
static { | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/utils/PreferenceUtil.java
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import me.wavever.ganklock.MyApplication;
package me.wavever.ganklock.utils;
public class PreferenceUtil {
private static SharedPreferences prefs;
private static Editor editor;
static { | prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext()); |
wavever/GankLock | app/src/main/java/me/wavever/ganklock/utils/SystemUtil.java | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
| import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import me.wavever.ganklock.MyApplication; | package me.wavever.ganklock.utils;
/**
* Created by wavever on 2016/9/20.
*/
public class SystemUtil {
/**
* 网络是否可用
*/
public static boolean isNetworkAvailable() { | // Path: app/src/main/java/me/wavever/ganklock/MyApplication.java
// public class MyApplication extends Application{
//
// private static Context context;
//
// private static PreferenceUtil sp;
//
// @Override
// public void onCreate() {
// super.onCreate();
// context = getApplicationContext();
// if (PreferenceUtil.getBoolean(Config.GANK_LOCK_IS_OPEN)) {
// context.startService(new Intent(context, LockService.class));
// }
// }
//
// /**
// * 获得一个全局的Context对象
// */
// public static Context getContext() {
// return context;
// }
// }
// Path: app/src/main/java/me/wavever/ganklock/utils/SystemUtil.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import me.wavever.ganklock.MyApplication;
package me.wavever.ganklock.utils;
/**
* Created by wavever on 2016/9/20.
*/
public class SystemUtil {
/**
* 网络是否可用
*/
public static boolean isNetworkAvailable() { | ConnectivityManager manager = (ConnectivityManager) MyApplication.getContext() |
budhash/cliche | src/main/java/com/budhash/cliche/ShellFactory.java | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/EmptyMultiMap.java
// public class EmptyMultiMap<K, V> implements MultiMap<K, V> {
//
// public void put(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public Collection<V> get(K key) {
// return new ArrayList<V>();
// }
//
// public Set<K> keySet() {
// return new HashSet<K>();
// }
//
// public void remove(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public void removeAll(K key) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public int size() {
// return 0;
// }
//
// public void putAll(MultiMap<K, V> map) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// @Override
// public String toString() {
// return "{}";
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
| import java.util.ArrayList;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.EmptyMultiMap;
import com.budhash.cliche.util.MultiMap; | /*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche;
/**
*
* @author ASG
*/
public class ShellFactory {
private ShellFactory() { } // this class has only static methods.
/**
* One of facade methods for operating the Shell.
*
* Run the obtained Shell with commandLoop().
*
* @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
*
* @param prompt Prompt to be displayed
* @param appName The app name string
* @param handlers Command handlers
* @return Shell that can be either further customized or run directly by calling commandLoop().
*/
public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {
ConsoleIO io = new ConsoleIO();
List<String> path = new ArrayList<String>(1);
path.add(prompt);
| // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/EmptyMultiMap.java
// public class EmptyMultiMap<K, V> implements MultiMap<K, V> {
//
// public void put(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public Collection<V> get(K key) {
// return new ArrayList<V>();
// }
//
// public Set<K> keySet() {
// return new HashSet<K>();
// }
//
// public void remove(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public void removeAll(K key) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public int size() {
// return 0;
// }
//
// public void putAll(MultiMap<K, V> map) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// @Override
// public String toString() {
// return "{}";
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
// Path: src/main/java/com/budhash/cliche/ShellFactory.java
import java.util.ArrayList;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.EmptyMultiMap;
import com.budhash.cliche.util.MultiMap;
/*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche;
/**
*
* @author ASG
*/
public class ShellFactory {
private ShellFactory() { } // this class has only static methods.
/**
* One of facade methods for operating the Shell.
*
* Run the obtained Shell with commandLoop().
*
* @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
*
* @param prompt Prompt to be displayed
* @param appName The app name string
* @param handlers Command handlers
* @return Shell that can be either further customized or run directly by calling commandLoop().
*/
public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {
ConsoleIO io = new ConsoleIO();
List<String> path = new ArrayList<String>(1);
path.add(prompt);
| MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>(); |
budhash/cliche | src/main/java/com/budhash/cliche/ShellFactory.java | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/EmptyMultiMap.java
// public class EmptyMultiMap<K, V> implements MultiMap<K, V> {
//
// public void put(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public Collection<V> get(K key) {
// return new ArrayList<V>();
// }
//
// public Set<K> keySet() {
// return new HashSet<K>();
// }
//
// public void remove(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public void removeAll(K key) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public int size() {
// return 0;
// }
//
// public void putAll(MultiMap<K, V> map) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// @Override
// public String toString() {
// return "{}";
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
| import java.util.ArrayList;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.EmptyMultiMap;
import com.budhash.cliche.util.MultiMap; | /*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche;
/**
*
* @author ASG
*/
public class ShellFactory {
private ShellFactory() { } // this class has only static methods.
/**
* One of facade methods for operating the Shell.
*
* Run the obtained Shell with commandLoop().
*
* @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
*
* @param prompt Prompt to be displayed
* @param appName The app name string
* @param handlers Command handlers
* @return Shell that can be either further customized or run directly by calling commandLoop().
*/
public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {
ConsoleIO io = new ConsoleIO();
List<String> path = new ArrayList<String>(1);
path.add(prompt);
| // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/EmptyMultiMap.java
// public class EmptyMultiMap<K, V> implements MultiMap<K, V> {
//
// public void put(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public Collection<V> get(K key) {
// return new ArrayList<V>();
// }
//
// public Set<K> keySet() {
// return new HashSet<K>();
// }
//
// public void remove(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public void removeAll(K key) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public int size() {
// return 0;
// }
//
// public void putAll(MultiMap<K, V> map) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// @Override
// public String toString() {
// return "{}";
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
// Path: src/main/java/com/budhash/cliche/ShellFactory.java
import java.util.ArrayList;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.EmptyMultiMap;
import com.budhash.cliche.util.MultiMap;
/*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche;
/**
*
* @author ASG
*/
public class ShellFactory {
private ShellFactory() { } // this class has only static methods.
/**
* One of facade methods for operating the Shell.
*
* Run the obtained Shell with commandLoop().
*
* @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
*
* @param prompt Prompt to be displayed
* @param appName The app name string
* @param handlers Command handlers
* @return Shell that can be either further customized or run directly by calling commandLoop().
*/
public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {
ConsoleIO io = new ConsoleIO();
List<String> path = new ArrayList<String>(1);
path.add(prompt);
| MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>(); |
budhash/cliche | src/main/java/com/budhash/cliche/ShellFactory.java | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/EmptyMultiMap.java
// public class EmptyMultiMap<K, V> implements MultiMap<K, V> {
//
// public void put(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public Collection<V> get(K key) {
// return new ArrayList<V>();
// }
//
// public Set<K> keySet() {
// return new HashSet<K>();
// }
//
// public void remove(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public void removeAll(K key) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public int size() {
// return 0;
// }
//
// public void putAll(MultiMap<K, V> map) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// @Override
// public String toString() {
// return "{}";
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
| import java.util.ArrayList;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.EmptyMultiMap;
import com.budhash.cliche.util.MultiMap; | List<String> path = new ArrayList<String>(1);
path.add(prompt);
MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>(auxHandlers);
modifAuxHandlers.put("!", io);
Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),
new CommandTable(new DashJoinedNamer(true)), path);
theShell.setAppName(appName);
theShell.addMainHandler(theShell, "!");
theShell.addMainHandler(new HelpCommandHandler(), "?");
theShell.addMainHandler(mainHandler, "");
return theShell;
}
/**
* Facade method for operating the Shell.
*
* Run the obtained Shell with commandLoop().
*
* @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
*
* @param prompt Prompt to be displayed
* @param appName The app name string
* @param mainHandler Command handler
* @return Shell that can be either further customized or run directly by calling commandLoop().
*/
public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) { | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/EmptyMultiMap.java
// public class EmptyMultiMap<K, V> implements MultiMap<K, V> {
//
// public void put(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public Collection<V> get(K key) {
// return new ArrayList<V>();
// }
//
// public Set<K> keySet() {
// return new HashSet<K>();
// }
//
// public void remove(K key, V value) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public void removeAll(K key) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// public int size() {
// return 0;
// }
//
// public void putAll(MultiMap<K, V> map) {
// throw new UnsupportedOperationException(
// "You can't modify EmptyMultyMap: it's always empty!");
// }
//
// @Override
// public String toString() {
// return "{}";
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
// Path: src/main/java/com/budhash/cliche/ShellFactory.java
import java.util.ArrayList;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.EmptyMultiMap;
import com.budhash.cliche.util.MultiMap;
List<String> path = new ArrayList<String>(1);
path.add(prompt);
MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>(auxHandlers);
modifAuxHandlers.put("!", io);
Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),
new CommandTable(new DashJoinedNamer(true)), path);
theShell.setAppName(appName);
theShell.addMainHandler(theShell, "!");
theShell.addMainHandler(new HelpCommandHandler(), "?");
theShell.addMainHandler(mainHandler, "");
return theShell;
}
/**
* Facade method for operating the Shell.
*
* Run the obtained Shell with commandLoop().
*
* @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
*
* @param prompt Prompt to be displayed
* @param appName The app name string
* @param mainHandler Command handler
* @return Shell that can be either further customized or run directly by calling commandLoop().
*/
public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) { | return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>()); |
budhash/cliche | src/main/java/com/budhash/cliche/DashJoinedNamer.java | // Path: src/main/java/com/budhash/cliche/util/Strings.java
// public class Strings {
//
// /**
// * Fixes case of a word: Str -> str, but URL -> URL.
// * @param s Word to be fixed
// * @return all-lowercase or all-uppercase word.
// */
// public static String fixCase(String s) {
// if (s == null || s.length() == 0) {
// return s;
// }
// if ( Character.isUpperCase(s.charAt(0))
// && (s.length() == 1 || Character.isLowerCase(s.charAt(1)))) {
// s = s.toLowerCase();
// }
// return s;
// }
//
// /**
// * Generic string joining function.
// * @param strings Strings to be joined
// * @param fixCase does it need to fix word case
// * @param withChar char to join strings with.
// * @return joined-string
// */
// public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {
// if (strings == null || strings.size() == 0) {
// return "";
// }
// StringBuilder result = null;
// for (String s : strings) {
// if (fixCase) {
// s = fixCase(s);
// }
// if (result == null) {
// result = new StringBuilder(s);
// } else {
// result.append(withChar);
// result.append(s);
// }
// }
// return result.toString();
// }
//
// /**
// * Rather clever function. Splits javaCaseIdentifier into parts
// * (java, Case, Identifier).
// * @param string String to be splitted
// * @return List of components
// */
// public static List<String> splitJavaIdentifier(String string) {
// assert string != null;
// List<String> result = new ArrayList<String>();
//
// int startIndex = 0;
// while (startIndex < string.length()) {
// if (Character.isLowerCase(string.charAt(startIndex))) {
// int i = startIndex;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else if (Character.isUpperCase(string.charAt(startIndex))) {
// if (string.length() - startIndex == 1) {
// result.add(Character.toString(string.charAt(startIndex++)));
// } else if (Character.isLowerCase(string.charAt(startIndex + 1))) {
// int i = startIndex + 1;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else { // if there's several uppercase letters in row
// int i = startIndex + 1;
// while (i < string.length() && Character.isUpperCase(string.charAt(i))
// && (string.length()-i == 1 || Character.isUpperCase(string.charAt(i+1)))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// }
// }else {
// result.add(Character.toString(string.charAt(startIndex++)));
// }
// }
// return result;
// }
//
// }
| import java.util.List;
import com.budhash.cliche.util.Strings;
import java.lang.reflect.Method; | /*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche;
/**
* Default "dash-joined" implementation of the CommandNamer.
*
* @author ASG
*/
public class DashJoinedNamer implements CommandNamer {
private final boolean doRemoveCommonPrefix;
public DashJoinedNamer(boolean doRemoveCommonPrefix) {
this.doRemoveCommonPrefix = doRemoveCommonPrefix;
}
public NamingInfo nameCommand(Method method) { | // Path: src/main/java/com/budhash/cliche/util/Strings.java
// public class Strings {
//
// /**
// * Fixes case of a word: Str -> str, but URL -> URL.
// * @param s Word to be fixed
// * @return all-lowercase or all-uppercase word.
// */
// public static String fixCase(String s) {
// if (s == null || s.length() == 0) {
// return s;
// }
// if ( Character.isUpperCase(s.charAt(0))
// && (s.length() == 1 || Character.isLowerCase(s.charAt(1)))) {
// s = s.toLowerCase();
// }
// return s;
// }
//
// /**
// * Generic string joining function.
// * @param strings Strings to be joined
// * @param fixCase does it need to fix word case
// * @param withChar char to join strings with.
// * @return joined-string
// */
// public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {
// if (strings == null || strings.size() == 0) {
// return "";
// }
// StringBuilder result = null;
// for (String s : strings) {
// if (fixCase) {
// s = fixCase(s);
// }
// if (result == null) {
// result = new StringBuilder(s);
// } else {
// result.append(withChar);
// result.append(s);
// }
// }
// return result.toString();
// }
//
// /**
// * Rather clever function. Splits javaCaseIdentifier into parts
// * (java, Case, Identifier).
// * @param string String to be splitted
// * @return List of components
// */
// public static List<String> splitJavaIdentifier(String string) {
// assert string != null;
// List<String> result = new ArrayList<String>();
//
// int startIndex = 0;
// while (startIndex < string.length()) {
// if (Character.isLowerCase(string.charAt(startIndex))) {
// int i = startIndex;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else if (Character.isUpperCase(string.charAt(startIndex))) {
// if (string.length() - startIndex == 1) {
// result.add(Character.toString(string.charAt(startIndex++)));
// } else if (Character.isLowerCase(string.charAt(startIndex + 1))) {
// int i = startIndex + 1;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else { // if there's several uppercase letters in row
// int i = startIndex + 1;
// while (i < string.length() && Character.isUpperCase(string.charAt(i))
// && (string.length()-i == 1 || Character.isUpperCase(string.charAt(i+1)))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// }
// }else {
// result.add(Character.toString(string.charAt(startIndex++)));
// }
// }
// return result;
// }
//
// }
// Path: src/main/java/com/budhash/cliche/DashJoinedNamer.java
import java.util.List;
import com.budhash.cliche.util.Strings;
import java.lang.reflect.Method;
/*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche;
/**
* Default "dash-joined" implementation of the CommandNamer.
*
* @author ASG
*/
public class DashJoinedNamer implements CommandNamer {
private final boolean doRemoveCommonPrefix;
public DashJoinedNamer(boolean doRemoveCommonPrefix) {
this.doRemoveCommonPrefix = doRemoveCommonPrefix;
}
public NamingInfo nameCommand(Method method) { | List<String> words = Strings.splitJavaIdentifier(method.getName()); |
budhash/cliche | src/test/java/com/budhash/cliche/OutputConversionEngineTest.java | // Path: src/main/java/com/budhash/cliche/OutputConversionEngine.java
// public class OutputConversionEngine {
//
// private List<OutputConverter> outputConverters = new ArrayList<OutputConverter>();
//
// public void addConverter(OutputConverter converter) {
// if (converter == null ) {
// throw new IllegalArgumentException("Converter == null");
// }
// outputConverters.add(converter);
// }
//
// public boolean removeConverter(OutputConverter converter) {
// return outputConverters.remove(converter);
// }
//
// public Object convertOutput(Object anObject) {
// Object convertedOutput = anObject;
// for (ListIterator<OutputConverter> it = outputConverters.listIterator(outputConverters.size()); it.hasPrevious();) {
// OutputConverter outputConverter = it.previous(); // last in --- first called.
// Object conversionResult = outputConverter.convertOutput(convertedOutput);
// if (conversionResult != null) {
// convertedOutput = conversionResult;
// }
// }
// return convertedOutput;
// }
//
// public void addDeclaredConverters(Object handler) {
// Field[] fields = handler.getClass().getFields();
// final String PREFIX = "CLI_OUTPUT_CONVERTERS";
// for (Field field : fields) {
// if (field.getName().startsWith(PREFIX)
// && field.getType().isArray()
// && OutputConverter.class.isAssignableFrom(field.getType().getComponentType())) {
// try {
// Object convertersArray = field.get(handler);
// for (int i = 0; i < Array.getLength(convertersArray); i++) {
// addConverter((OutputConverter)Array.get(convertersArray, i));
// }
// } catch (Exception ex) {
// throw new RuntimeException("Error getting converter from field " + field.getName(), ex);
// }
// }
// }
// }
//
//
// }
//
// Path: src/main/java/com/budhash/cliche/OutputConverter.java
// public interface OutputConverter {
// /**
// * Object-to--user-friendly-object (usually string) conversion method.
// * The method must check argument's class, since it will be fed virtually all
// * returned objects. Simply return null when not sure.
// * @param toBeFormatted Object to be displayed to the user
// * @return Object representing the object or Null if don't know how to make it.
// * Do not return default toString() !!
// */
// Object convertOutput(Object toBeFormatted);
// }
| import org.junit.Before;
import org.junit.Test;
import com.budhash.cliche.OutputConversionEngine;
import com.budhash.cliche.OutputConverter;
import static org.junit.Assert.*; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.budhash.cliche;
/**
*
* @author ASG
*/
public class OutputConversionEngineTest {
@Before
public void setUp() { | // Path: src/main/java/com/budhash/cliche/OutputConversionEngine.java
// public class OutputConversionEngine {
//
// private List<OutputConverter> outputConverters = new ArrayList<OutputConverter>();
//
// public void addConverter(OutputConverter converter) {
// if (converter == null ) {
// throw new IllegalArgumentException("Converter == null");
// }
// outputConverters.add(converter);
// }
//
// public boolean removeConverter(OutputConverter converter) {
// return outputConverters.remove(converter);
// }
//
// public Object convertOutput(Object anObject) {
// Object convertedOutput = anObject;
// for (ListIterator<OutputConverter> it = outputConverters.listIterator(outputConverters.size()); it.hasPrevious();) {
// OutputConverter outputConverter = it.previous(); // last in --- first called.
// Object conversionResult = outputConverter.convertOutput(convertedOutput);
// if (conversionResult != null) {
// convertedOutput = conversionResult;
// }
// }
// return convertedOutput;
// }
//
// public void addDeclaredConverters(Object handler) {
// Field[] fields = handler.getClass().getFields();
// final String PREFIX = "CLI_OUTPUT_CONVERTERS";
// for (Field field : fields) {
// if (field.getName().startsWith(PREFIX)
// && field.getType().isArray()
// && OutputConverter.class.isAssignableFrom(field.getType().getComponentType())) {
// try {
// Object convertersArray = field.get(handler);
// for (int i = 0; i < Array.getLength(convertersArray); i++) {
// addConverter((OutputConverter)Array.get(convertersArray, i));
// }
// } catch (Exception ex) {
// throw new RuntimeException("Error getting converter from field " + field.getName(), ex);
// }
// }
// }
// }
//
//
// }
//
// Path: src/main/java/com/budhash/cliche/OutputConverter.java
// public interface OutputConverter {
// /**
// * Object-to--user-friendly-object (usually string) conversion method.
// * The method must check argument's class, since it will be fed virtually all
// * returned objects. Simply return null when not sure.
// * @param toBeFormatted Object to be displayed to the user
// * @return Object representing the object or Null if don't know how to make it.
// * Do not return default toString() !!
// */
// Object convertOutput(Object toBeFormatted);
// }
// Path: src/test/java/com/budhash/cliche/OutputConversionEngineTest.java
import org.junit.Before;
import org.junit.Test;
import com.budhash.cliche.OutputConversionEngine;
import com.budhash.cliche.OutputConverter;
import static org.junit.Assert.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.budhash.cliche;
/**
*
* @author ASG
*/
public class OutputConversionEngineTest {
@Before
public void setUp() { | converter = new OutputConversionEngine(); |
budhash/cliche | src/test/java/com/budhash/cliche/OutputConversionEngineTest.java | // Path: src/main/java/com/budhash/cliche/OutputConversionEngine.java
// public class OutputConversionEngine {
//
// private List<OutputConverter> outputConverters = new ArrayList<OutputConverter>();
//
// public void addConverter(OutputConverter converter) {
// if (converter == null ) {
// throw new IllegalArgumentException("Converter == null");
// }
// outputConverters.add(converter);
// }
//
// public boolean removeConverter(OutputConverter converter) {
// return outputConverters.remove(converter);
// }
//
// public Object convertOutput(Object anObject) {
// Object convertedOutput = anObject;
// for (ListIterator<OutputConverter> it = outputConverters.listIterator(outputConverters.size()); it.hasPrevious();) {
// OutputConverter outputConverter = it.previous(); // last in --- first called.
// Object conversionResult = outputConverter.convertOutput(convertedOutput);
// if (conversionResult != null) {
// convertedOutput = conversionResult;
// }
// }
// return convertedOutput;
// }
//
// public void addDeclaredConverters(Object handler) {
// Field[] fields = handler.getClass().getFields();
// final String PREFIX = "CLI_OUTPUT_CONVERTERS";
// for (Field field : fields) {
// if (field.getName().startsWith(PREFIX)
// && field.getType().isArray()
// && OutputConverter.class.isAssignableFrom(field.getType().getComponentType())) {
// try {
// Object convertersArray = field.get(handler);
// for (int i = 0; i < Array.getLength(convertersArray); i++) {
// addConverter((OutputConverter)Array.get(convertersArray, i));
// }
// } catch (Exception ex) {
// throw new RuntimeException("Error getting converter from field " + field.getName(), ex);
// }
// }
// }
// }
//
//
// }
//
// Path: src/main/java/com/budhash/cliche/OutputConverter.java
// public interface OutputConverter {
// /**
// * Object-to--user-friendly-object (usually string) conversion method.
// * The method must check argument's class, since it will be fed virtually all
// * returned objects. Simply return null when not sure.
// * @param toBeFormatted Object to be displayed to the user
// * @return Object representing the object or Null if don't know how to make it.
// * Do not return default toString() !!
// */
// Object convertOutput(Object toBeFormatted);
// }
| import org.junit.Before;
import org.junit.Test;
import com.budhash.cliche.OutputConversionEngine;
import com.budhash.cliche.OutputConverter;
import static org.junit.Assert.*; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.budhash.cliche;
/**
*
* @author ASG
*/
public class OutputConversionEngineTest {
@Before
public void setUp() {
converter = new OutputConversionEngine();
converter.addDeclaredConverters(this);
}
OutputConversionEngine converter;
| // Path: src/main/java/com/budhash/cliche/OutputConversionEngine.java
// public class OutputConversionEngine {
//
// private List<OutputConverter> outputConverters = new ArrayList<OutputConverter>();
//
// public void addConverter(OutputConverter converter) {
// if (converter == null ) {
// throw new IllegalArgumentException("Converter == null");
// }
// outputConverters.add(converter);
// }
//
// public boolean removeConverter(OutputConverter converter) {
// return outputConverters.remove(converter);
// }
//
// public Object convertOutput(Object anObject) {
// Object convertedOutput = anObject;
// for (ListIterator<OutputConverter> it = outputConverters.listIterator(outputConverters.size()); it.hasPrevious();) {
// OutputConverter outputConverter = it.previous(); // last in --- first called.
// Object conversionResult = outputConverter.convertOutput(convertedOutput);
// if (conversionResult != null) {
// convertedOutput = conversionResult;
// }
// }
// return convertedOutput;
// }
//
// public void addDeclaredConverters(Object handler) {
// Field[] fields = handler.getClass().getFields();
// final String PREFIX = "CLI_OUTPUT_CONVERTERS";
// for (Field field : fields) {
// if (field.getName().startsWith(PREFIX)
// && field.getType().isArray()
// && OutputConverter.class.isAssignableFrom(field.getType().getComponentType())) {
// try {
// Object convertersArray = field.get(handler);
// for (int i = 0; i < Array.getLength(convertersArray); i++) {
// addConverter((OutputConverter)Array.get(convertersArray, i));
// }
// } catch (Exception ex) {
// throw new RuntimeException("Error getting converter from field " + field.getName(), ex);
// }
// }
// }
// }
//
//
// }
//
// Path: src/main/java/com/budhash/cliche/OutputConverter.java
// public interface OutputConverter {
// /**
// * Object-to--user-friendly-object (usually string) conversion method.
// * The method must check argument's class, since it will be fed virtually all
// * returned objects. Simply return null when not sure.
// * @param toBeFormatted Object to be displayed to the user
// * @return Object representing the object or Null if don't know how to make it.
// * Do not return default toString() !!
// */
// Object convertOutput(Object toBeFormatted);
// }
// Path: src/test/java/com/budhash/cliche/OutputConversionEngineTest.java
import org.junit.Before;
import org.junit.Test;
import com.budhash.cliche.OutputConversionEngine;
import com.budhash.cliche.OutputConverter;
import static org.junit.Assert.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.budhash.cliche;
/**
*
* @author ASG
*/
public class OutputConversionEngineTest {
@Before
public void setUp() {
converter = new OutputConversionEngine();
converter.addDeclaredConverters(this);
}
OutputConversionEngine converter;
| public static final OutputConverter[] CLI_OUTPUT_CONVERTERS = { |
budhash/cliche | src/test/java/com/budhash/cliche/util/MultiMapTest.java | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
| import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.MultiMap;
import static org.junit.Assert.*; | /*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche.util;
/**
*
* @author ASG
*/
public class MultiMapTest {
public MultiMapTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Test
public void test() {
System.out.println("test"); | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
// Path: src/test/java/com/budhash/cliche/util/MultiMapTest.java
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.MultiMap;
import static org.junit.Assert.*;
/*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche.util;
/**
*
* @author ASG
*/
public class MultiMapTest {
public MultiMapTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Test
public void test() {
System.out.println("test"); | MultiMap<String, String> map = new ArrayHashMultiMap<String, String>(); |
budhash/cliche | src/test/java/com/budhash/cliche/util/MultiMapTest.java | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
| import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.MultiMap;
import static org.junit.Assert.*; | /*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche.util;
/**
*
* @author ASG
*/
public class MultiMapTest {
public MultiMapTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Test
public void test() {
System.out.println("test"); | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
// Path: src/test/java/com/budhash/cliche/util/MultiMapTest.java
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.MultiMap;
import static org.junit.Assert.*;
/*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche.util;
/**
*
* @author ASG
*/
public class MultiMapTest {
public MultiMapTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Test
public void test() {
System.out.println("test"); | MultiMap<String, String> map = new ArrayHashMultiMap<String, String>(); |
budhash/cliche | src/main/java/com/budhash/cliche/example/HelloWorld.java | // Path: src/main/java/com/budhash/cliche/ShellFactory.java
// public class ShellFactory {
//
// private ShellFactory() { } // this class has only static methods.
//
// /**
// * One of facade methods for operating the Shell.
// *
// * Run the obtained Shell with commandLoop().
// *
// * @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
// *
// * @param prompt Prompt to be displayed
// * @param appName The app name string
// * @param handlers Command handlers
// * @return Shell that can be either further customized or run directly by calling commandLoop().
// */
// public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {
// ConsoleIO io = new ConsoleIO();
//
// List<String> path = new ArrayList<String>(1);
// path.add(prompt);
//
// MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>();
// modifAuxHandlers.put("!", io);
//
// Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),
// new CommandTable(new DashJoinedNamer(true)), path);
// theShell.setAppName(appName);
//
// theShell.addMainHandler(theShell, "!");
// theShell.addMainHandler(new HelpCommandHandler(), "?");
// for (Object h : handlers) {
// theShell.addMainHandler(h, "");
// }
//
// return theShell;
// }
//
// /**
// * Facade method for operating the Shell allowing specification of auxiliary
// * handlers (i.e. handlers that are to be passed to all subshells).
// *
// * Run the obtained Shell with commandLoop().
// *
// * @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
// *
// * @param prompt Prompt to be displayed
// * @param appName The app name string
// * @param mainHandler Main command handler
// * @param auxHandlers Aux handlers to be passed to all subshells.
// * @return Shell that can be either further customized or run directly by calling commandLoop().
// */
// public static Shell createConsoleShell(String prompt, String appName, Object mainHandler,
// MultiMap<String, Object> auxHandlers) {
// ConsoleIO io = new ConsoleIO();
//
// List<String> path = new ArrayList<String>(1);
// path.add(prompt);
//
// MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>(auxHandlers);
// modifAuxHandlers.put("!", io);
//
// Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),
// new CommandTable(new DashJoinedNamer(true)), path);
// theShell.setAppName(appName);
//
// theShell.addMainHandler(theShell, "!");
// theShell.addMainHandler(new HelpCommandHandler(), "?");
// theShell.addMainHandler(mainHandler, "");
//
// return theShell;
// }
//
// /**
// * Facade method for operating the Shell.
// *
// * Run the obtained Shell with commandLoop().
// *
// * @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
// *
// * @param prompt Prompt to be displayed
// * @param appName The app name string
// * @param mainHandler Command handler
// * @return Shell that can be either further customized or run directly by calling commandLoop().
// */
// public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) {
// return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());
// }
//
// /**
// * Facade method facilitating the creation of subshell.
// * Subshell is created and run inside Command method and shares the same IO and naming strategy.
// *
// * Run the obtained Shell with commandLoop().
// *
// * @param pathElement sub-prompt
// * @param parent Shell to be subshell'd
// * @param appName The app name string
// * @param mainHandler Command handler
// * @param auxHandlers Aux handlers to be passed to all subshells.
// * @return subshell
// */
// public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler,
// MultiMap<String, Object> auxHandlers) {
//
// List<String> newPath = new ArrayList<String>(parent.getPath());
// newPath.add(pathElement);
//
// Shell subshell = new Shell(parent.getSettings().createWithAddedAuxHandlers(auxHandlers),
// new CommandTable(parent.getCommandTable().getNamer()), newPath);
//
// subshell.setAppName(appName);
// subshell.addMainHandler(subshell, "!");
// subshell.addMainHandler(new HelpCommandHandler(), "?");
//
// subshell.addMainHandler(mainHandler, "");
// return subshell;
// }
//
// /**
// * Facade method facilitating the creation of subshell.
// * Subshell is created and run inside Command method and shares the same IO and naming strtategy.
// *
// * Run the obtained Shell with commandLoop().
// *
// * @param pathElement sub-prompt
// * @param parent Shell to be subshell'd
// * @param appName The app name string
// * @param mainHandler Command handler
// * @return subshell
// */
// public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler) {
// return createSubshell(pathElement, parent, appName, mainHandler, new EmptyMultiMap<String, Object>());
// }
//
//
// }
| import com.budhash.cliche.Command;
import com.budhash.cliche.ShellFactory;
import java.io.IOException; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.budhash.cliche.example;
/**
* 'Hello World!' example.
*
* @author ASG
*/
public class HelloWorld {
@Command
public int add(int a, int b) {
return a + b;
}
@Command
public String echo(String s) {
return s;
}
public static void main(String[] params) throws IOException { | // Path: src/main/java/com/budhash/cliche/ShellFactory.java
// public class ShellFactory {
//
// private ShellFactory() { } // this class has only static methods.
//
// /**
// * One of facade methods for operating the Shell.
// *
// * Run the obtained Shell with commandLoop().
// *
// * @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
// *
// * @param prompt Prompt to be displayed
// * @param appName The app name string
// * @param handlers Command handlers
// * @return Shell that can be either further customized or run directly by calling commandLoop().
// */
// public static Shell createConsoleShell(String prompt, String appName, Object... handlers) {
// ConsoleIO io = new ConsoleIO();
//
// List<String> path = new ArrayList<String>(1);
// path.add(prompt);
//
// MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>();
// modifAuxHandlers.put("!", io);
//
// Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),
// new CommandTable(new DashJoinedNamer(true)), path);
// theShell.setAppName(appName);
//
// theShell.addMainHandler(theShell, "!");
// theShell.addMainHandler(new HelpCommandHandler(), "?");
// for (Object h : handlers) {
// theShell.addMainHandler(h, "");
// }
//
// return theShell;
// }
//
// /**
// * Facade method for operating the Shell allowing specification of auxiliary
// * handlers (i.e. handlers that are to be passed to all subshells).
// *
// * Run the obtained Shell with commandLoop().
// *
// * @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
// *
// * @param prompt Prompt to be displayed
// * @param appName The app name string
// * @param mainHandler Main command handler
// * @param auxHandlers Aux handlers to be passed to all subshells.
// * @return Shell that can be either further customized or run directly by calling commandLoop().
// */
// public static Shell createConsoleShell(String prompt, String appName, Object mainHandler,
// MultiMap<String, Object> auxHandlers) {
// ConsoleIO io = new ConsoleIO();
//
// List<String> path = new ArrayList<String>(1);
// path.add(prompt);
//
// MultiMap<String, Object> modifAuxHandlers = new ArrayHashMultiMap<String, Object>(auxHandlers);
// modifAuxHandlers.put("!", io);
//
// Shell theShell = new Shell(new Shell.Settings(io, io, modifAuxHandlers, false),
// new CommandTable(new DashJoinedNamer(true)), path);
// theShell.setAppName(appName);
//
// theShell.addMainHandler(theShell, "!");
// theShell.addMainHandler(new HelpCommandHandler(), "?");
// theShell.addMainHandler(mainHandler, "");
//
// return theShell;
// }
//
// /**
// * Facade method for operating the Shell.
// *
// * Run the obtained Shell with commandLoop().
// *
// * @see com.budhash.cliche.Shell#Shell(com.budhash.cliche.Shell.Settings, com.budhash.cliche.CommandTable, java.util.List)
// *
// * @param prompt Prompt to be displayed
// * @param appName The app name string
// * @param mainHandler Command handler
// * @return Shell that can be either further customized or run directly by calling commandLoop().
// */
// public static Shell createConsoleShell(String prompt, String appName, Object mainHandler) {
// return createConsoleShell(prompt, appName, mainHandler, new EmptyMultiMap<String, Object>());
// }
//
// /**
// * Facade method facilitating the creation of subshell.
// * Subshell is created and run inside Command method and shares the same IO and naming strategy.
// *
// * Run the obtained Shell with commandLoop().
// *
// * @param pathElement sub-prompt
// * @param parent Shell to be subshell'd
// * @param appName The app name string
// * @param mainHandler Command handler
// * @param auxHandlers Aux handlers to be passed to all subshells.
// * @return subshell
// */
// public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler,
// MultiMap<String, Object> auxHandlers) {
//
// List<String> newPath = new ArrayList<String>(parent.getPath());
// newPath.add(pathElement);
//
// Shell subshell = new Shell(parent.getSettings().createWithAddedAuxHandlers(auxHandlers),
// new CommandTable(parent.getCommandTable().getNamer()), newPath);
//
// subshell.setAppName(appName);
// subshell.addMainHandler(subshell, "!");
// subshell.addMainHandler(new HelpCommandHandler(), "?");
//
// subshell.addMainHandler(mainHandler, "");
// return subshell;
// }
//
// /**
// * Facade method facilitating the creation of subshell.
// * Subshell is created and run inside Command method and shares the same IO and naming strtategy.
// *
// * Run the obtained Shell with commandLoop().
// *
// * @param pathElement sub-prompt
// * @param parent Shell to be subshell'd
// * @param appName The app name string
// * @param mainHandler Command handler
// * @return subshell
// */
// public static Shell createSubshell(String pathElement, Shell parent, String appName, Object mainHandler) {
// return createSubshell(pathElement, parent, appName, mainHandler, new EmptyMultiMap<String, Object>());
// }
//
//
// }
// Path: src/main/java/com/budhash/cliche/example/HelloWorld.java
import com.budhash.cliche.Command;
import com.budhash.cliche.ShellFactory;
import java.io.IOException;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.budhash.cliche.example;
/**
* 'Hello World!' example.
*
* @author ASG
*/
public class HelloWorld {
@Command
public int add(int a, int b) {
return a + b;
}
@Command
public String echo(String s) {
return s;
}
public static void main(String[] params) throws IOException { | ShellFactory.createConsoleShell("hello", null, new HelloWorld()) |
budhash/cliche | src/main/java/com/budhash/cliche/ConsoleIO.java | // Path: src/main/java/com/budhash/cliche/util/Strings.java
// public class Strings {
//
// /**
// * Fixes case of a word: Str -> str, but URL -> URL.
// * @param s Word to be fixed
// * @return all-lowercase or all-uppercase word.
// */
// public static String fixCase(String s) {
// if (s == null || s.length() == 0) {
// return s;
// }
// if ( Character.isUpperCase(s.charAt(0))
// && (s.length() == 1 || Character.isLowerCase(s.charAt(1)))) {
// s = s.toLowerCase();
// }
// return s;
// }
//
// /**
// * Generic string joining function.
// * @param strings Strings to be joined
// * @param fixCase does it need to fix word case
// * @param withChar char to join strings with.
// * @return joined-string
// */
// public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {
// if (strings == null || strings.size() == 0) {
// return "";
// }
// StringBuilder result = null;
// for (String s : strings) {
// if (fixCase) {
// s = fixCase(s);
// }
// if (result == null) {
// result = new StringBuilder(s);
// } else {
// result.append(withChar);
// result.append(s);
// }
// }
// return result.toString();
// }
//
// /**
// * Rather clever function. Splits javaCaseIdentifier into parts
// * (java, Case, Identifier).
// * @param string String to be splitted
// * @return List of components
// */
// public static List<String> splitJavaIdentifier(String string) {
// assert string != null;
// List<String> result = new ArrayList<String>();
//
// int startIndex = 0;
// while (startIndex < string.length()) {
// if (Character.isLowerCase(string.charAt(startIndex))) {
// int i = startIndex;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else if (Character.isUpperCase(string.charAt(startIndex))) {
// if (string.length() - startIndex == 1) {
// result.add(Character.toString(string.charAt(startIndex++)));
// } else if (Character.isLowerCase(string.charAt(startIndex + 1))) {
// int i = startIndex + 1;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else { // if there's several uppercase letters in row
// int i = startIndex + 1;
// while (i < string.length() && Character.isUpperCase(string.charAt(i))
// && (string.length()-i == 1 || Character.isUpperCase(string.charAt(i+1)))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// }
// }else {
// result.add(Character.toString(string.charAt(startIndex++)));
// }
// }
// return result;
// }
//
// }
| import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.List;
import com.budhash.cliche.util.Strings; | /*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche;
/**
* Console IO subsystem.
* This is also one of special command handlers and is responsible
* for logging (duplicating output) and execution of scripts.
*
* @author ASG
*/
public class ConsoleIO implements Input, Output, ShellManageable {
public ConsoleIO(BufferedReader in, PrintStream out, PrintStream err) {
this.in = in;
this.out = out;
this.err = err;
}
public ConsoleIO() {
this(new BufferedReader(new InputStreamReader(System.in)),
System.out, System.err);
}
private BufferedReader in;
private PrintStream out;
private PrintStream err;
private int lastCommandOffset = 0;
public String readCommand(List<String> path) {
try { | // Path: src/main/java/com/budhash/cliche/util/Strings.java
// public class Strings {
//
// /**
// * Fixes case of a word: Str -> str, but URL -> URL.
// * @param s Word to be fixed
// * @return all-lowercase or all-uppercase word.
// */
// public static String fixCase(String s) {
// if (s == null || s.length() == 0) {
// return s;
// }
// if ( Character.isUpperCase(s.charAt(0))
// && (s.length() == 1 || Character.isLowerCase(s.charAt(1)))) {
// s = s.toLowerCase();
// }
// return s;
// }
//
// /**
// * Generic string joining function.
// * @param strings Strings to be joined
// * @param fixCase does it need to fix word case
// * @param withChar char to join strings with.
// * @return joined-string
// */
// public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {
// if (strings == null || strings.size() == 0) {
// return "";
// }
// StringBuilder result = null;
// for (String s : strings) {
// if (fixCase) {
// s = fixCase(s);
// }
// if (result == null) {
// result = new StringBuilder(s);
// } else {
// result.append(withChar);
// result.append(s);
// }
// }
// return result.toString();
// }
//
// /**
// * Rather clever function. Splits javaCaseIdentifier into parts
// * (java, Case, Identifier).
// * @param string String to be splitted
// * @return List of components
// */
// public static List<String> splitJavaIdentifier(String string) {
// assert string != null;
// List<String> result = new ArrayList<String>();
//
// int startIndex = 0;
// while (startIndex < string.length()) {
// if (Character.isLowerCase(string.charAt(startIndex))) {
// int i = startIndex;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else if (Character.isUpperCase(string.charAt(startIndex))) {
// if (string.length() - startIndex == 1) {
// result.add(Character.toString(string.charAt(startIndex++)));
// } else if (Character.isLowerCase(string.charAt(startIndex + 1))) {
// int i = startIndex + 1;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else { // if there's several uppercase letters in row
// int i = startIndex + 1;
// while (i < string.length() && Character.isUpperCase(string.charAt(i))
// && (string.length()-i == 1 || Character.isUpperCase(string.charAt(i+1)))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// }
// }else {
// result.add(Character.toString(string.charAt(startIndex++)));
// }
// }
// return result;
// }
//
// }
// Path: src/main/java/com/budhash/cliche/ConsoleIO.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.List;
import com.budhash.cliche.util.Strings;
/*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche;
/**
* Console IO subsystem.
* This is also one of special command handlers and is responsible
* for logging (duplicating output) and execution of scripts.
*
* @author ASG
*/
public class ConsoleIO implements Input, Output, ShellManageable {
public ConsoleIO(BufferedReader in, PrintStream out, PrintStream err) {
this.in = in;
this.out = out;
this.err = err;
}
public ConsoleIO() {
this(new BufferedReader(new InputStreamReader(System.in)),
System.out, System.err);
}
private BufferedReader in;
private PrintStream out;
private PrintStream err;
private int lastCommandOffset = 0;
public String readCommand(List<String> path) {
try { | String prompt = Strings.joinStrings(path, false, '/'); |
budhash/cliche | src/test/java/com/budhash/cliche/util/StringsTest.java | // Path: src/main/java/com/budhash/cliche/util/Strings.java
// public class Strings {
//
// /**
// * Fixes case of a word: Str -> str, but URL -> URL.
// * @param s Word to be fixed
// * @return all-lowercase or all-uppercase word.
// */
// public static String fixCase(String s) {
// if (s == null || s.length() == 0) {
// return s;
// }
// if ( Character.isUpperCase(s.charAt(0))
// && (s.length() == 1 || Character.isLowerCase(s.charAt(1)))) {
// s = s.toLowerCase();
// }
// return s;
// }
//
// /**
// * Generic string joining function.
// * @param strings Strings to be joined
// * @param fixCase does it need to fix word case
// * @param withChar char to join strings with.
// * @return joined-string
// */
// public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {
// if (strings == null || strings.size() == 0) {
// return "";
// }
// StringBuilder result = null;
// for (String s : strings) {
// if (fixCase) {
// s = fixCase(s);
// }
// if (result == null) {
// result = new StringBuilder(s);
// } else {
// result.append(withChar);
// result.append(s);
// }
// }
// return result.toString();
// }
//
// /**
// * Rather clever function. Splits javaCaseIdentifier into parts
// * (java, Case, Identifier).
// * @param string String to be splitted
// * @return List of components
// */
// public static List<String> splitJavaIdentifier(String string) {
// assert string != null;
// List<String> result = new ArrayList<String>();
//
// int startIndex = 0;
// while (startIndex < string.length()) {
// if (Character.isLowerCase(string.charAt(startIndex))) {
// int i = startIndex;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else if (Character.isUpperCase(string.charAt(startIndex))) {
// if (string.length() - startIndex == 1) {
// result.add(Character.toString(string.charAt(startIndex++)));
// } else if (Character.isLowerCase(string.charAt(startIndex + 1))) {
// int i = startIndex + 1;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else { // if there's several uppercase letters in row
// int i = startIndex + 1;
// while (i < string.length() && Character.isUpperCase(string.charAt(i))
// && (string.length()-i == 1 || Character.isUpperCase(string.charAt(i+1)))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// }
// }else {
// result.add(Character.toString(string.charAt(startIndex++)));
// }
// }
// return result;
// }
//
// }
| import org.junit.Test;
import com.budhash.cliche.util.Strings;
import static org.junit.Assert.*;
import java.util.Arrays; | /*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche.util;
/**
*
* @author ASG
*/
public class StringsTest {
/**
* Test of fixCase method, of class Strings.
*/
@Test
public void testFixCase() {
System.out.println("fixCase");
String[] cases = {
"",
"a",
"A",
"Abc",
"ABC",
"ABc"
};
String[] results = {
"",
"a",
"a",
"abc",
"ABC",
"ABc"
};
for (int i = 0; i < cases.length; i++) { | // Path: src/main/java/com/budhash/cliche/util/Strings.java
// public class Strings {
//
// /**
// * Fixes case of a word: Str -> str, but URL -> URL.
// * @param s Word to be fixed
// * @return all-lowercase or all-uppercase word.
// */
// public static String fixCase(String s) {
// if (s == null || s.length() == 0) {
// return s;
// }
// if ( Character.isUpperCase(s.charAt(0))
// && (s.length() == 1 || Character.isLowerCase(s.charAt(1)))) {
// s = s.toLowerCase();
// }
// return s;
// }
//
// /**
// * Generic string joining function.
// * @param strings Strings to be joined
// * @param fixCase does it need to fix word case
// * @param withChar char to join strings with.
// * @return joined-string
// */
// public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {
// if (strings == null || strings.size() == 0) {
// return "";
// }
// StringBuilder result = null;
// for (String s : strings) {
// if (fixCase) {
// s = fixCase(s);
// }
// if (result == null) {
// result = new StringBuilder(s);
// } else {
// result.append(withChar);
// result.append(s);
// }
// }
// return result.toString();
// }
//
// /**
// * Rather clever function. Splits javaCaseIdentifier into parts
// * (java, Case, Identifier).
// * @param string String to be splitted
// * @return List of components
// */
// public static List<String> splitJavaIdentifier(String string) {
// assert string != null;
// List<String> result = new ArrayList<String>();
//
// int startIndex = 0;
// while (startIndex < string.length()) {
// if (Character.isLowerCase(string.charAt(startIndex))) {
// int i = startIndex;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else if (Character.isUpperCase(string.charAt(startIndex))) {
// if (string.length() - startIndex == 1) {
// result.add(Character.toString(string.charAt(startIndex++)));
// } else if (Character.isLowerCase(string.charAt(startIndex + 1))) {
// int i = startIndex + 1;
// while (i < string.length() && Character.isLowerCase(string.charAt(i))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// } else { // if there's several uppercase letters in row
// int i = startIndex + 1;
// while (i < string.length() && Character.isUpperCase(string.charAt(i))
// && (string.length()-i == 1 || Character.isUpperCase(string.charAt(i+1)))) {
// i++;
// }
// result.add(string.substring(startIndex, i));
// startIndex = i;
// }
// }else {
// result.add(Character.toString(string.charAt(startIndex++)));
// }
// }
// return result;
// }
//
// }
// Path: src/test/java/com/budhash/cliche/util/StringsTest.java
import org.junit.Test;
import com.budhash.cliche.util.Strings;
import static org.junit.Assert.*;
import java.util.Arrays;
/*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
package com.budhash.cliche.util;
/**
*
* @author ASG
*/
public class StringsTest {
/**
* Test of fixCase method, of class Strings.
*/
@Test
public void testFixCase() {
System.out.println("fixCase");
String[] cases = {
"",
"a",
"A",
"Abc",
"ABC",
"ABc"
};
String[] results = {
"",
"a",
"a",
"abc",
"ABC",
"ABc"
};
for (int i = 0; i < cases.length; i++) { | assertEquals(results[i], Strings.fixCase(cases[i])); |
budhash/cliche | src/main/java/com/budhash/cliche/Shell.java | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
| import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.MultiMap; | /*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
/*
* Cliche is to be a VERY simple reflection-based command line shell
* to provide simple CLI for simple applications.
* The name formed as follows: "CLI Shell" --> "CLIShe" --> "Cliche".
*/
package com.budhash.cliche;
/**
* Shell is the class interacting with user. Provides the command loop. All
* logic lies here.
*
* @author ASG
*/
public class Shell {
// TODO : fix this to point to github
public static String PROJECT_HOMEPAGE_URL = "http://cliche.sourceforge.net";
private Output output;
private Input input;
private String appName;
public static class Settings {
private final Input input;
private final Output output; | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
// Path: src/main/java/com/budhash/cliche/Shell.java
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.MultiMap;
/*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
/*
* Cliche is to be a VERY simple reflection-based command line shell
* to provide simple CLI for simple applications.
* The name formed as follows: "CLI Shell" --> "CLIShe" --> "Cliche".
*/
package com.budhash.cliche;
/**
* Shell is the class interacting with user. Provides the command loop. All
* logic lies here.
*
* @author ASG
*/
public class Shell {
// TODO : fix this to point to github
public static String PROJECT_HOMEPAGE_URL = "http://cliche.sourceforge.net";
private Output output;
private Input input;
private String appName;
public static class Settings {
private final Input input;
private final Output output; | private final MultiMap<String, Object> auxHandlers; |
budhash/cliche | src/main/java/com/budhash/cliche/Shell.java | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
| import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.MultiMap; | /*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
/*
* Cliche is to be a VERY simple reflection-based command line shell
* to provide simple CLI for simple applications.
* The name formed as follows: "CLI Shell" --> "CLIShe" --> "Cliche".
*/
package com.budhash.cliche;
/**
* Shell is the class interacting with user. Provides the command loop. All
* logic lies here.
*
* @author ASG
*/
public class Shell {
// TODO : fix this to point to github
public static String PROJECT_HOMEPAGE_URL = "http://cliche.sourceforge.net";
private Output output;
private Input input;
private String appName;
public static class Settings {
private final Input input;
private final Output output;
private final MultiMap<String, Object> auxHandlers;
private final boolean displayTime;
public Settings(Input input, Output output,
MultiMap<String, Object> auxHandlers, boolean displayTime) {
this.input = input;
this.output = output;
this.auxHandlers = auxHandlers;
this.displayTime = displayTime;
}
public Settings createWithAddedAuxHandlers(
MultiMap<String, Object> addAuxHandlers) { | // Path: src/main/java/com/budhash/cliche/util/ArrayHashMultiMap.java
// public final class ArrayHashMultiMap<K, V> implements MultiMap<K, V> {
//
// private Map<K, List<V>> listMap;
//
// public ArrayHashMultiMap() {
// listMap = new HashMap<K, List<V>>();
// }
//
// public ArrayHashMultiMap(MultiMap<K, V> map) {
// this();
// putAll(map);
// }
//
// public void put(K key, V value) {
// List<V> values = listMap.get(key);
// if (values == null) {
// values = new ArrayList<V>();
// listMap.put(key, values);
// }
// values.add(value);
// }
//
// public Collection<V> get(K key) {
// List<V> result = listMap.get(key);
// if (result == null) {
// result = new ArrayList<V>();
// }
// return result;
// }
//
// public Set<K> keySet() {
// return listMap.keySet();
// }
//
// public void remove(K key, V value) {
// List<V> values = listMap.get(key);
// if (values != null) {
// values.remove(value);
// if (values.isEmpty()) {
// listMap.remove(key);
// }
// }
// }
//
// public void removeAll(K key) {
// listMap.remove(key);
// }
//
// public int size() {
// int sum = 0;
// for (K key : listMap.keySet()) {
// sum += listMap.get(key).size();
// }
// return sum;
// }
//
// public void putAll(MultiMap<K, V> map) {
// for (K key : map.keySet()) {
// for (V val : map.get(key)) {
// put(key, val);
// }
// }
// }
//
// @Override
// public String toString() {
// return listMap.toString();
// }
//
// }
//
// Path: src/main/java/com/budhash/cliche/util/MultiMap.java
// public interface MultiMap<K, V> {
//
// void put(K key, V value);
//
// void putAll(MultiMap<K, V> map);
//
// Collection<V> get(K key);
//
// Set<K> keySet();
//
// void remove(K key, V value);
//
// void removeAll(K key);
//
// /**
// * @return total size of all value collections in the MultiMap.
// */
// int size();
//
// }
// Path: src/main/java/com/budhash/cliche/Shell.java
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.budhash.cliche.util.ArrayHashMultiMap;
import com.budhash.cliche.util.MultiMap;
/*
* This file is part of the Cliche project, licensed under MIT License.
* See LICENSE.txt file in root folder of Cliche sources.
*/
/*
* Cliche is to be a VERY simple reflection-based command line shell
* to provide simple CLI for simple applications.
* The name formed as follows: "CLI Shell" --> "CLIShe" --> "Cliche".
*/
package com.budhash.cliche;
/**
* Shell is the class interacting with user. Provides the command loop. All
* logic lies here.
*
* @author ASG
*/
public class Shell {
// TODO : fix this to point to github
public static String PROJECT_HOMEPAGE_URL = "http://cliche.sourceforge.net";
private Output output;
private Input input;
private String appName;
public static class Settings {
private final Input input;
private final Output output;
private final MultiMap<String, Object> auxHandlers;
private final boolean displayTime;
public Settings(Input input, Output output,
MultiMap<String, Object> auxHandlers, boolean displayTime) {
this.input = input;
this.output = output;
this.auxHandlers = auxHandlers;
this.displayTime = displayTime;
}
public Settings createWithAddedAuxHandlers(
MultiMap<String, Object> addAuxHandlers) { | MultiMap<String, Object> allAuxHandlers = new ArrayHashMultiMap<String, Object>( |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/core/classsearch/ClassSearchResult.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/BundleClass.java
// public class BundleClass {
//
// private Bundle bundle;
//
// private String className;
//
// public BundleClass(Bundle bundle, String className) {
// this.bundle = bundle;
// this.className = className;
// }
//
// public Bundle getBundle() {
// return bundle;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getClassPath() {
// return StringUtils.replace(className, ".", "/");
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BundleClass that = (BundleClass) o;
//
// return new EqualsBuilder()
// .append(bundle, that.bundle)
// .append(className, that.className)
// .isEquals();
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder()
// .append(bundle)
// .append(className)
// .toHashCode();
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/ClassDecompileServlet.java
// public class ClassDecompileServlet extends RestServlet {
//
// public static final String ALIAS_NAME = "class-decompile";
//
// public static final String BUNDLE_ID = "bundleId";
//
// public static final String CLASS_NAME = "className";
//
// private final OsgiExplorer osgiExplorer;
//
// public ClassDecompileServlet(BundleContext bundleContext) {
// super(bundleContext);
// this.osgiExplorer = new OsgiExplorer(bundleContext);
// }
//
// public static String url(BundleContext context, Bundle bundle, String className) {
// return url(context, bundle.getBundleId(), className);
// }
//
// public static String url(BundleContext context, long bundleId, String className) {
// return String.format("%s?%s=%d&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), BUNDLE_ID, bundleId, CLASS_NAME, className);
// }
//
// @Override
// protected String getAliasName() {
// return ALIAS_NAME;
// }
//
// @Override
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String bundleId = StringUtils.trimToEmpty(request.getParameter(BUNDLE_ID));
// final String className = StringUtils.trimToEmpty(request.getParameter(CLASS_NAME));
//
// final Bundle bundle = bundleContext.getBundle(Long.valueOf(bundleId));
// if (bundle == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' not be found.", bundleId));
// return;
// }
//
// final File bundleJar = osgiExplorer.findJar(Long.valueOf(bundleId));
// if (bundleJar == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' JAR cannot be found.", bundleId));
// return;
// }
//
// final String classSource = osgiExplorer.decompileClass(bundleJar, className);
//
// JsonUtils.writeMessage(response, MessageType.SUCCESS, "Class details",
// ImmutableMap.of(
// "className", className,
// "classSource", classSource,
// "bundleId", bundleId,
// "bundleSymbolicName", bundle.getSymbolicName(),
// "bundleJarPath", bundleJar.getAbsolutePath()
// ));
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.core.BundleClass;
import com.neva.felix.webconsole.plugins.search.rest.ClassDecompileServlet;
import org.osgi.framework.BundleContext;
import java.io.Serializable;
import java.util.List; | package com.neva.felix.webconsole.plugins.search.core.classsearch;
public class ClassSearchResult implements Serializable {
private final long bundleId;
private final String className;
private final List<String> contexts;
private final String decompileUrl;
| // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/BundleClass.java
// public class BundleClass {
//
// private Bundle bundle;
//
// private String className;
//
// public BundleClass(Bundle bundle, String className) {
// this.bundle = bundle;
// this.className = className;
// }
//
// public Bundle getBundle() {
// return bundle;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getClassPath() {
// return StringUtils.replace(className, ".", "/");
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BundleClass that = (BundleClass) o;
//
// return new EqualsBuilder()
// .append(bundle, that.bundle)
// .append(className, that.className)
// .isEquals();
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder()
// .append(bundle)
// .append(className)
// .toHashCode();
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/ClassDecompileServlet.java
// public class ClassDecompileServlet extends RestServlet {
//
// public static final String ALIAS_NAME = "class-decompile";
//
// public static final String BUNDLE_ID = "bundleId";
//
// public static final String CLASS_NAME = "className";
//
// private final OsgiExplorer osgiExplorer;
//
// public ClassDecompileServlet(BundleContext bundleContext) {
// super(bundleContext);
// this.osgiExplorer = new OsgiExplorer(bundleContext);
// }
//
// public static String url(BundleContext context, Bundle bundle, String className) {
// return url(context, bundle.getBundleId(), className);
// }
//
// public static String url(BundleContext context, long bundleId, String className) {
// return String.format("%s?%s=%d&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), BUNDLE_ID, bundleId, CLASS_NAME, className);
// }
//
// @Override
// protected String getAliasName() {
// return ALIAS_NAME;
// }
//
// @Override
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String bundleId = StringUtils.trimToEmpty(request.getParameter(BUNDLE_ID));
// final String className = StringUtils.trimToEmpty(request.getParameter(CLASS_NAME));
//
// final Bundle bundle = bundleContext.getBundle(Long.valueOf(bundleId));
// if (bundle == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' not be found.", bundleId));
// return;
// }
//
// final File bundleJar = osgiExplorer.findJar(Long.valueOf(bundleId));
// if (bundleJar == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' JAR cannot be found.", bundleId));
// return;
// }
//
// final String classSource = osgiExplorer.decompileClass(bundleJar, className);
//
// JsonUtils.writeMessage(response, MessageType.SUCCESS, "Class details",
// ImmutableMap.of(
// "className", className,
// "classSource", classSource,
// "bundleId", bundleId,
// "bundleSymbolicName", bundle.getSymbolicName(),
// "bundleJarPath", bundleJar.getAbsolutePath()
// ));
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/classsearch/ClassSearchResult.java
import com.neva.felix.webconsole.plugins.search.core.BundleClass;
import com.neva.felix.webconsole.plugins.search.rest.ClassDecompileServlet;
import org.osgi.framework.BundleContext;
import java.io.Serializable;
import java.util.List;
package com.neva.felix.webconsole.plugins.search.core.classsearch;
public class ClassSearchResult implements Serializable {
private final long bundleId;
private final String className;
private final List<String> contexts;
private final String decompileUrl;
| public ClassSearchResult(BundleContext context, BundleClass clazz, List<String> contexts) { |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/core/classsearch/ClassSearchResult.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/BundleClass.java
// public class BundleClass {
//
// private Bundle bundle;
//
// private String className;
//
// public BundleClass(Bundle bundle, String className) {
// this.bundle = bundle;
// this.className = className;
// }
//
// public Bundle getBundle() {
// return bundle;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getClassPath() {
// return StringUtils.replace(className, ".", "/");
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BundleClass that = (BundleClass) o;
//
// return new EqualsBuilder()
// .append(bundle, that.bundle)
// .append(className, that.className)
// .isEquals();
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder()
// .append(bundle)
// .append(className)
// .toHashCode();
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/ClassDecompileServlet.java
// public class ClassDecompileServlet extends RestServlet {
//
// public static final String ALIAS_NAME = "class-decompile";
//
// public static final String BUNDLE_ID = "bundleId";
//
// public static final String CLASS_NAME = "className";
//
// private final OsgiExplorer osgiExplorer;
//
// public ClassDecompileServlet(BundleContext bundleContext) {
// super(bundleContext);
// this.osgiExplorer = new OsgiExplorer(bundleContext);
// }
//
// public static String url(BundleContext context, Bundle bundle, String className) {
// return url(context, bundle.getBundleId(), className);
// }
//
// public static String url(BundleContext context, long bundleId, String className) {
// return String.format("%s?%s=%d&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), BUNDLE_ID, bundleId, CLASS_NAME, className);
// }
//
// @Override
// protected String getAliasName() {
// return ALIAS_NAME;
// }
//
// @Override
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String bundleId = StringUtils.trimToEmpty(request.getParameter(BUNDLE_ID));
// final String className = StringUtils.trimToEmpty(request.getParameter(CLASS_NAME));
//
// final Bundle bundle = bundleContext.getBundle(Long.valueOf(bundleId));
// if (bundle == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' not be found.", bundleId));
// return;
// }
//
// final File bundleJar = osgiExplorer.findJar(Long.valueOf(bundleId));
// if (bundleJar == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' JAR cannot be found.", bundleId));
// return;
// }
//
// final String classSource = osgiExplorer.decompileClass(bundleJar, className);
//
// JsonUtils.writeMessage(response, MessageType.SUCCESS, "Class details",
// ImmutableMap.of(
// "className", className,
// "classSource", classSource,
// "bundleId", bundleId,
// "bundleSymbolicName", bundle.getSymbolicName(),
// "bundleJarPath", bundleJar.getAbsolutePath()
// ));
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.core.BundleClass;
import com.neva.felix.webconsole.plugins.search.rest.ClassDecompileServlet;
import org.osgi.framework.BundleContext;
import java.io.Serializable;
import java.util.List; | package com.neva.felix.webconsole.plugins.search.core.classsearch;
public class ClassSearchResult implements Serializable {
private final long bundleId;
private final String className;
private final List<String> contexts;
private final String decompileUrl;
public ClassSearchResult(BundleContext context, BundleClass clazz, List<String> contexts) {
this.bundleId = clazz.getBundle().getBundleId();
this.className = clazz.getClassName();
this.contexts = contexts; | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/BundleClass.java
// public class BundleClass {
//
// private Bundle bundle;
//
// private String className;
//
// public BundleClass(Bundle bundle, String className) {
// this.bundle = bundle;
// this.className = className;
// }
//
// public Bundle getBundle() {
// return bundle;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getClassPath() {
// return StringUtils.replace(className, ".", "/");
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BundleClass that = (BundleClass) o;
//
// return new EqualsBuilder()
// .append(bundle, that.bundle)
// .append(className, that.className)
// .isEquals();
// }
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder()
// .append(bundle)
// .append(className)
// .toHashCode();
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/ClassDecompileServlet.java
// public class ClassDecompileServlet extends RestServlet {
//
// public static final String ALIAS_NAME = "class-decompile";
//
// public static final String BUNDLE_ID = "bundleId";
//
// public static final String CLASS_NAME = "className";
//
// private final OsgiExplorer osgiExplorer;
//
// public ClassDecompileServlet(BundleContext bundleContext) {
// super(bundleContext);
// this.osgiExplorer = new OsgiExplorer(bundleContext);
// }
//
// public static String url(BundleContext context, Bundle bundle, String className) {
// return url(context, bundle.getBundleId(), className);
// }
//
// public static String url(BundleContext context, long bundleId, String className) {
// return String.format("%s?%s=%d&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), BUNDLE_ID, bundleId, CLASS_NAME, className);
// }
//
// @Override
// protected String getAliasName() {
// return ALIAS_NAME;
// }
//
// @Override
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String bundleId = StringUtils.trimToEmpty(request.getParameter(BUNDLE_ID));
// final String className = StringUtils.trimToEmpty(request.getParameter(CLASS_NAME));
//
// final Bundle bundle = bundleContext.getBundle(Long.valueOf(bundleId));
// if (bundle == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' not be found.", bundleId));
// return;
// }
//
// final File bundleJar = osgiExplorer.findJar(Long.valueOf(bundleId));
// if (bundleJar == null) {
// JsonUtils.writeMessage(response, MessageType.ERROR, String.format("Bundle '%s' JAR cannot be found.", bundleId));
// return;
// }
//
// final String classSource = osgiExplorer.decompileClass(bundleJar, className);
//
// JsonUtils.writeMessage(response, MessageType.SUCCESS, "Class details",
// ImmutableMap.of(
// "className", className,
// "classSource", classSource,
// "bundleId", bundleId,
// "bundleSymbolicName", bundle.getSymbolicName(),
// "bundleJarPath", bundleJar.getAbsolutePath()
// ));
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/classsearch/ClassSearchResult.java
import com.neva.felix.webconsole.plugins.search.core.BundleClass;
import com.neva.felix.webconsole.plugins.search.rest.ClassDecompileServlet;
import org.osgi.framework.BundleContext;
import java.io.Serializable;
import java.util.List;
package com.neva.felix.webconsole.plugins.search.core.classsearch;
public class ClassSearchResult implements Serializable {
private final long bundleId;
private final String className;
private final List<String> contexts;
private final String decompileUrl;
public ClassSearchResult(BundleContext context, BundleClass clazz, List<String> contexts) {
this.bundleId = clazz.getBundle().getBundleId();
this.className = clazz.getClassName();
this.contexts = contexts; | this.decompileUrl = ClassDecompileServlet.url(context, clazz.getBundle(), clazz.getClassName()); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchUtils.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/PrettifierUtils.java
// public final class PrettifierUtils {
//
// private PrettifierUtils() {
// // hidden constructor
// }
//
// public static String escape(String source) {
// String[] search = { "<", ">", };
// String[] replace = { "<", ">" };
//
// return StringUtils.replaceEach(source, search, replace);
// }
//
// public static String highlight(String line) {
// return String.format("<span class=\"highlighted\">%s</span>", line);
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.utils.PrettifierUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
import java.util.List;
import java.util.Map; | }
/**
* Compose human readable parameter list as description
*/
public static String composeDescription(Map<String, Object> params) {
List<String> lines = Lists.newArrayList();
for (Map.Entry<String, Object> entry : params.entrySet()) {
Object value = entry.getValue();
if (value instanceof String[]) {
value = "[" + StringUtils.join((String[] )value, ", ") + "]";
}
lines.add(String.format("%s: %s", entry.getKey(), value));
}
return StringUtils.join(lines, "\n");
}
public static List<String> findContexts(String phrase, String source, int contextLineCount) {
List<String> contexts = Lists.newLinkedList();
List<String> lines = Splitter.on(LINE_DELIMITER).splitToList(source);
int i = 0;
for (String line : lines) {
if (StringUtils.containsIgnoreCase(line, phrase)) {
String before = Joiner.on("\n")
.join(lines.subList(Math.max(0, i - contextLineCount - 1), Math.max(0, i - 1)));
String after = Joiner.on("\n").join(lines.subList(Math.min(i + 1, lines.size()),
Math.min(lines.size(), i + 1 + contextLineCount))); | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/PrettifierUtils.java
// public final class PrettifierUtils {
//
// private PrettifierUtils() {
// // hidden constructor
// }
//
// public static String escape(String source) {
// String[] search = { "<", ">", };
// String[] replace = { "<", ">" };
//
// return StringUtils.replaceEach(source, search, replace);
// }
//
// public static String highlight(String line) {
// return String.format("<span class=\"highlighted\">%s</span>", line);
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchUtils.java
import com.neva.felix.webconsole.plugins.search.utils.PrettifierUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
import java.util.List;
import java.util.Map;
}
/**
* Compose human readable parameter list as description
*/
public static String composeDescription(Map<String, Object> params) {
List<String> lines = Lists.newArrayList();
for (Map.Entry<String, Object> entry : params.entrySet()) {
Object value = entry.getValue();
if (value instanceof String[]) {
value = "[" + StringUtils.join((String[] )value, ", ") + "]";
}
lines.add(String.format("%s: %s", entry.getKey(), value));
}
return StringUtils.join(lines, "\n");
}
public static List<String> findContexts(String phrase, String source, int contextLineCount) {
List<String> contexts = Lists.newLinkedList();
List<String> lines = Splitter.on(LINE_DELIMITER).splitToList(source);
int i = 0;
for (String line : lines) {
if (StringUtils.containsIgnoreCase(line, phrase)) {
String before = Joiner.on("\n")
.join(lines.subList(Math.max(0, i - contextLineCount - 1), Math.max(0, i - 1)));
String after = Joiner.on("\n").join(lines.subList(Math.min(i + 1, lines.size()),
Math.min(lines.size(), i + 1 + contextLineCount))); | String context = PrettifierUtils.escape(before) + "\n" + PrettifierUtils |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/RestServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/TemplateRenderer.java
// public class TemplateRenderer {
//
// private static final Logger LOG = LoggerFactory.getLogger(TemplateRenderer.class);
//
// protected final Map<String, String> globalVars;
//
// public TemplateRenderer() {
// this(Collections.<String, String>emptyMap());
// }
//
// public TemplateRenderer(Map<String, String> globalVars) {
// this.globalVars = globalVars;
// }
//
// public static String render(String templateFile) {
// return render(templateFile, Collections.<String, String>emptyMap());
// }
//
// public static String render(String templateFile, Map<String, String> vars) {
// return new TemplateRenderer().renderTemplate(templateFile, vars);
// }
//
// public final String renderTemplate(String templateFile) {
// return renderTemplate(templateFile, Collections.<String, String>emptyMap());
// }
//
// public final String renderTemplate(String templateFile, Map<String, String> vars) {
// String result = null;
//
// InputStream templateStream = getClass().getResourceAsStream("/" + templateFile);
// if (templateStream == null) {
// LOG.error(String.format("Template '%s' cannot be found.", templateFile));
// } else {
// try {
// result = IOUtils.toString(templateStream, "UTF-8");
// } catch (IOException e) {
// LOG.error(String.format("Cannot load template '%s'", templateFile), e);
// } finally {
// IOUtils.closeQuietly(templateStream);
// }
// }
//
// final Map<String, String> allVars = ImmutableMap.<String, String>builder()
// .putAll(globalVars)
// .putAll(vars)
// .build();
//
// return StrSubstitutor.replace(result, allVars);
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.TemplateRenderer;
import org.osgi.framework.BundleContext;
import javax.servlet.http.HttpServlet;
import java.util.Dictionary;
import java.util.Hashtable; | package com.neva.felix.webconsole.plugins.search.rest;
public abstract class RestServlet extends HttpServlet {
protected final BundleContext bundleContext;
| // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/TemplateRenderer.java
// public class TemplateRenderer {
//
// private static final Logger LOG = LoggerFactory.getLogger(TemplateRenderer.class);
//
// protected final Map<String, String> globalVars;
//
// public TemplateRenderer() {
// this(Collections.<String, String>emptyMap());
// }
//
// public TemplateRenderer(Map<String, String> globalVars) {
// this.globalVars = globalVars;
// }
//
// public static String render(String templateFile) {
// return render(templateFile, Collections.<String, String>emptyMap());
// }
//
// public static String render(String templateFile, Map<String, String> vars) {
// return new TemplateRenderer().renderTemplate(templateFile, vars);
// }
//
// public final String renderTemplate(String templateFile) {
// return renderTemplate(templateFile, Collections.<String, String>emptyMap());
// }
//
// public final String renderTemplate(String templateFile, Map<String, String> vars) {
// String result = null;
//
// InputStream templateStream = getClass().getResourceAsStream("/" + templateFile);
// if (templateStream == null) {
// LOG.error(String.format("Template '%s' cannot be found.", templateFile));
// } else {
// try {
// result = IOUtils.toString(templateStream, "UTF-8");
// } catch (IOException e) {
// LOG.error(String.format("Cannot load template '%s'", templateFile), e);
// } finally {
// IOUtils.closeQuietly(templateStream);
// }
// }
//
// final Map<String, String> allVars = ImmutableMap.<String, String>builder()
// .putAll(globalVars)
// .putAll(vars)
// .build();
//
// return StrSubstitutor.replace(result, allVars);
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/RestServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.TemplateRenderer;
import org.osgi.framework.BundleContext;
import javax.servlet.http.HttpServlet;
import java.util.Dictionary;
import java.util.Hashtable;
package com.neva.felix.webconsole.plugins.search.rest;
public abstract class RestServlet extends HttpServlet {
protected final BundleContext bundleContext;
| protected final TemplateRenderer templateRenderer; |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/RestServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/TemplateRenderer.java
// public class TemplateRenderer {
//
// private static final Logger LOG = LoggerFactory.getLogger(TemplateRenderer.class);
//
// protected final Map<String, String> globalVars;
//
// public TemplateRenderer() {
// this(Collections.<String, String>emptyMap());
// }
//
// public TemplateRenderer(Map<String, String> globalVars) {
// this.globalVars = globalVars;
// }
//
// public static String render(String templateFile) {
// return render(templateFile, Collections.<String, String>emptyMap());
// }
//
// public static String render(String templateFile, Map<String, String> vars) {
// return new TemplateRenderer().renderTemplate(templateFile, vars);
// }
//
// public final String renderTemplate(String templateFile) {
// return renderTemplate(templateFile, Collections.<String, String>emptyMap());
// }
//
// public final String renderTemplate(String templateFile, Map<String, String> vars) {
// String result = null;
//
// InputStream templateStream = getClass().getResourceAsStream("/" + templateFile);
// if (templateStream == null) {
// LOG.error(String.format("Template '%s' cannot be found.", templateFile));
// } else {
// try {
// result = IOUtils.toString(templateStream, "UTF-8");
// } catch (IOException e) {
// LOG.error(String.format("Cannot load template '%s'", templateFile), e);
// } finally {
// IOUtils.closeQuietly(templateStream);
// }
// }
//
// final Map<String, String> allVars = ImmutableMap.<String, String>builder()
// .putAll(globalVars)
// .putAll(vars)
// .build();
//
// return StrSubstitutor.replace(result, allVars);
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.TemplateRenderer;
import org.osgi.framework.BundleContext;
import javax.servlet.http.HttpServlet;
import java.util.Dictionary;
import java.util.Hashtable; | package com.neva.felix.webconsole.plugins.search.rest;
public abstract class RestServlet extends HttpServlet {
protected final BundleContext bundleContext;
protected final TemplateRenderer templateRenderer;
public RestServlet(BundleContext bundleContext) {
this.bundleContext = bundleContext;
this.templateRenderer = new TemplateRenderer();
}
protected abstract String getAliasName();
public Dictionary<String, Object> createProps() {
Dictionary<String, Object> props = new Hashtable<>();
props.put("alias", getAlias());
return props;
}
public String getAlias() { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/TemplateRenderer.java
// public class TemplateRenderer {
//
// private static final Logger LOG = LoggerFactory.getLogger(TemplateRenderer.class);
//
// protected final Map<String, String> globalVars;
//
// public TemplateRenderer() {
// this(Collections.<String, String>emptyMap());
// }
//
// public TemplateRenderer(Map<String, String> globalVars) {
// this.globalVars = globalVars;
// }
//
// public static String render(String templateFile) {
// return render(templateFile, Collections.<String, String>emptyMap());
// }
//
// public static String render(String templateFile, Map<String, String> vars) {
// return new TemplateRenderer().renderTemplate(templateFile, vars);
// }
//
// public final String renderTemplate(String templateFile) {
// return renderTemplate(templateFile, Collections.<String, String>emptyMap());
// }
//
// public final String renderTemplate(String templateFile, Map<String, String> vars) {
// String result = null;
//
// InputStream templateStream = getClass().getResourceAsStream("/" + templateFile);
// if (templateStream == null) {
// LOG.error(String.format("Template '%s' cannot be found.", templateFile));
// } else {
// try {
// result = IOUtils.toString(templateStream, "UTF-8");
// } catch (IOException e) {
// LOG.error(String.format("Cannot load template '%s'", templateFile), e);
// } finally {
// IOUtils.closeQuietly(templateStream);
// }
// }
//
// final Map<String, String> allVars = ImmutableMap.<String, String>builder()
// .putAll(globalVars)
// .putAll(vars)
// .build();
//
// return StrSubstitutor.replace(result, allVars);
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/RestServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.TemplateRenderer;
import org.osgi.framework.BundleContext;
import javax.servlet.http.HttpServlet;
import java.util.Dictionary;
import java.util.Hashtable;
package com.neva.felix.webconsole.plugins.search.rest;
public abstract class RestServlet extends HttpServlet {
protected final BundleContext bundleContext;
protected final TemplateRenderer templateRenderer;
public RestServlet(BundleContext bundleContext) {
this.bundleContext = bundleContext;
this.templateRenderer = new TemplateRenderer();
}
protected abstract String getAliasName();
public Dictionary<String, Object> createProps() {
Dictionary<String, Object> props = new Hashtable<>();
props.put("alias", getAlias());
return props;
}
public String getAlias() { | return SearchPaths.from(bundleContext).pluginAlias(getAliasName()); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/SearchActivator.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/AbstractPlugin.java
// public abstract class AbstractPlugin extends AbstractWebConsolePlugin {
//
// public static final String CATEGORY = "OSGi";
//
// protected final BundleContext bundleContext;
//
// public AbstractPlugin(BundleContext bundleContext) {
// this.bundleContext = bundleContext;
// }
//
// @Override
// protected void renderContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String common = readTemplateFile("/search/common.html");
// final String specific = readTemplateFile("/" + getLabel() + "/plugin.html");
// final String content = StrSubstitutor.replace(specific, ImmutableMap.of("common", common));
//
// response.getWriter().write(content);
// }
//
// protected Dictionary<String, Object> createProps() {
// final Dictionary<String, Object> props = new Hashtable<>();
//
// props.put("felix.webconsole.label", getLabel());
// props.put("felix.webconsole.category", CATEGORY);
//
// return props;
// }
//
// public void register() {
// bundleContext.registerService(Servlet.class.getName(), this, createProps());
// }
//
// public URL getResource(final String path) {
// String prefix = "/" + getLabel() + "/";
// if (path.startsWith(prefix)) {
// return this.getClass().getResource(path);
// }
//
// return null;
// }
//
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/SearchPlugin.java
// public class SearchPlugin extends AbstractPlugin {
//
// public static final String LABEL = "search";
//
// public static final String TITLE = "Search";
//
// public SearchPlugin(BundleContext bundleContext) {
// super(bundleContext);
// }
//
// @Override
// public String getLabel() {
// return LABEL;
// }
//
// @Override
// public String getTitle() {
// return TITLE;
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.plugin.AbstractPlugin;
import com.neva.felix.webconsole.plugins.search.plugin.SearchPlugin;
import com.google.common.collect.ImmutableSet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.Set; | package com.neva.felix.webconsole.plugins.search;
public class SearchActivator implements BundleActivator {
private SearchHttpTracker httpTracker;
@Override
public void start(BundleContext bundleContext) throws Exception { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/AbstractPlugin.java
// public abstract class AbstractPlugin extends AbstractWebConsolePlugin {
//
// public static final String CATEGORY = "OSGi";
//
// protected final BundleContext bundleContext;
//
// public AbstractPlugin(BundleContext bundleContext) {
// this.bundleContext = bundleContext;
// }
//
// @Override
// protected void renderContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String common = readTemplateFile("/search/common.html");
// final String specific = readTemplateFile("/" + getLabel() + "/plugin.html");
// final String content = StrSubstitutor.replace(specific, ImmutableMap.of("common", common));
//
// response.getWriter().write(content);
// }
//
// protected Dictionary<String, Object> createProps() {
// final Dictionary<String, Object> props = new Hashtable<>();
//
// props.put("felix.webconsole.label", getLabel());
// props.put("felix.webconsole.category", CATEGORY);
//
// return props;
// }
//
// public void register() {
// bundleContext.registerService(Servlet.class.getName(), this, createProps());
// }
//
// public URL getResource(final String path) {
// String prefix = "/" + getLabel() + "/";
// if (path.startsWith(prefix)) {
// return this.getClass().getResource(path);
// }
//
// return null;
// }
//
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/SearchPlugin.java
// public class SearchPlugin extends AbstractPlugin {
//
// public static final String LABEL = "search";
//
// public static final String TITLE = "Search";
//
// public SearchPlugin(BundleContext bundleContext) {
// super(bundleContext);
// }
//
// @Override
// public String getLabel() {
// return LABEL;
// }
//
// @Override
// public String getTitle() {
// return TITLE;
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/SearchActivator.java
import com.neva.felix.webconsole.plugins.search.plugin.AbstractPlugin;
import com.neva.felix.webconsole.plugins.search.plugin.SearchPlugin;
import com.google.common.collect.ImmutableSet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.Set;
package com.neva.felix.webconsole.plugins.search;
public class SearchActivator implements BundleActivator {
private SearchHttpTracker httpTracker;
@Override
public void start(BundleContext bundleContext) throws Exception { | for (AbstractPlugin plugin : getPlugins(bundleContext)) { |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/SearchActivator.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/AbstractPlugin.java
// public abstract class AbstractPlugin extends AbstractWebConsolePlugin {
//
// public static final String CATEGORY = "OSGi";
//
// protected final BundleContext bundleContext;
//
// public AbstractPlugin(BundleContext bundleContext) {
// this.bundleContext = bundleContext;
// }
//
// @Override
// protected void renderContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String common = readTemplateFile("/search/common.html");
// final String specific = readTemplateFile("/" + getLabel() + "/plugin.html");
// final String content = StrSubstitutor.replace(specific, ImmutableMap.of("common", common));
//
// response.getWriter().write(content);
// }
//
// protected Dictionary<String, Object> createProps() {
// final Dictionary<String, Object> props = new Hashtable<>();
//
// props.put("felix.webconsole.label", getLabel());
// props.put("felix.webconsole.category", CATEGORY);
//
// return props;
// }
//
// public void register() {
// bundleContext.registerService(Servlet.class.getName(), this, createProps());
// }
//
// public URL getResource(final String path) {
// String prefix = "/" + getLabel() + "/";
// if (path.startsWith(prefix)) {
// return this.getClass().getResource(path);
// }
//
// return null;
// }
//
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/SearchPlugin.java
// public class SearchPlugin extends AbstractPlugin {
//
// public static final String LABEL = "search";
//
// public static final String TITLE = "Search";
//
// public SearchPlugin(BundleContext bundleContext) {
// super(bundleContext);
// }
//
// @Override
// public String getLabel() {
// return LABEL;
// }
//
// @Override
// public String getTitle() {
// return TITLE;
// }
//
// }
| import com.neva.felix.webconsole.plugins.search.plugin.AbstractPlugin;
import com.neva.felix.webconsole.plugins.search.plugin.SearchPlugin;
import com.google.common.collect.ImmutableSet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.Set; | package com.neva.felix.webconsole.plugins.search;
public class SearchActivator implements BundleActivator {
private SearchHttpTracker httpTracker;
@Override
public void start(BundleContext bundleContext) throws Exception {
for (AbstractPlugin plugin : getPlugins(bundleContext)) {
plugin.register();
}
httpTracker = new SearchHttpTracker(bundleContext);
httpTracker.open();
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
httpTracker.close();
httpTracker = null;
}
private Set<AbstractPlugin> getPlugins(BundleContext bundleContext) {
return ImmutableSet.<AbstractPlugin>of( | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/AbstractPlugin.java
// public abstract class AbstractPlugin extends AbstractWebConsolePlugin {
//
// public static final String CATEGORY = "OSGi";
//
// protected final BundleContext bundleContext;
//
// public AbstractPlugin(BundleContext bundleContext) {
// this.bundleContext = bundleContext;
// }
//
// @Override
// protected void renderContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// final String common = readTemplateFile("/search/common.html");
// final String specific = readTemplateFile("/" + getLabel() + "/plugin.html");
// final String content = StrSubstitutor.replace(specific, ImmutableMap.of("common", common));
//
// response.getWriter().write(content);
// }
//
// protected Dictionary<String, Object> createProps() {
// final Dictionary<String, Object> props = new Hashtable<>();
//
// props.put("felix.webconsole.label", getLabel());
// props.put("felix.webconsole.category", CATEGORY);
//
// return props;
// }
//
// public void register() {
// bundleContext.registerService(Servlet.class.getName(), this, createProps());
// }
//
// public URL getResource(final String path) {
// String prefix = "/" + getLabel() + "/";
// if (path.startsWith(prefix)) {
// return this.getClass().getResource(path);
// }
//
// return null;
// }
//
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/plugin/SearchPlugin.java
// public class SearchPlugin extends AbstractPlugin {
//
// public static final String LABEL = "search";
//
// public static final String TITLE = "Search";
//
// public SearchPlugin(BundleContext bundleContext) {
// super(bundleContext);
// }
//
// @Override
// public String getLabel() {
// return LABEL;
// }
//
// @Override
// public String getTitle() {
// return TITLE;
// }
//
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/SearchActivator.java
import com.neva.felix.webconsole.plugins.search.plugin.AbstractPlugin;
import com.neva.felix.webconsole.plugins.search.plugin.SearchPlugin;
import com.google.common.collect.ImmutableSet;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import java.util.Set;
package com.neva.felix.webconsole.plugins.search;
public class SearchActivator implements BundleActivator {
private SearchHttpTracker httpTracker;
@Override
public void start(BundleContext bundleContext) throws Exception {
for (AbstractPlugin plugin : getPlugins(bundleContext)) {
plugin.register();
}
httpTracker = new SearchHttpTracker(bundleContext);
httpTracker.open();
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
httpTracker.close();
httpTracker = null;
}
private Set<AbstractPlugin> getPlugins(BundleContext bundleContext) {
return ImmutableSet.<AbstractPlugin>of( | new SearchPlugin(bundleContext) |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/utils/BundleUtils.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import java.util.Map; | package com.neva.felix.webconsole.plugins.search.utils;
public class BundleUtils {
public static String consolePath(BundleContext context, Bundle bundle) {
return consolePath(context, bundle.getBundleId());
}
public static String consolePath(BundleContext context, long bundleId) { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/BundleUtils.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import java.util.Map;
package com.neva.felix.webconsole.plugins.search.utils;
public class BundleUtils {
public static String consolePath(BundleContext context, Bundle bundle) {
return consolePath(context, bundle.getBundleId());
}
public static String consolePath(BundleContext context, long bundleId) { | return SearchPaths.from(context).appAlias("bundles") + "/" + String.valueOf(bundleId); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage; | package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage;
package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) { | return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME), |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage; | package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage;
package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) { | writeMessage(response, MessageType.ERROR, String.format("File at path '%s' cannot be found.", path)); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage; | package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage;
package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) { | writeMessage(response, MessageType.ERROR, String.format("File at path '%s' cannot be found.", path)); |
neva-dev/felix-search-webconsole-plugin | src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
| import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage; | package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) {
writeMessage(response, MessageType.ERROR, String.format("File at path '%s' cannot be found.", path));
} else { | // Path: src/main/java/com/neva/felix/webconsole/plugins/search/core/SearchPaths.java
// public class SearchPaths {
//
// public static final String APP_NAME = "search";
//
// private static final String APP_ROOT_PROP = "felix.webconsole.manager.root";
//
// private static final String APP_ROOT_DEFAULT = "/system/console";
//
// private final BundleContext context;
//
// public SearchPaths(BundleContext context) {
// this.context = context;
// }
//
// public static SearchPaths from(BundleContext context) {
// return new SearchPaths(context);
// }
//
// public String appRoot() {
// return StringUtils.defaultIfEmpty(context.getProperty(APP_ROOT_PROP), APP_ROOT_DEFAULT);
// }
//
// public String appAlias(String alias) {
// return appRoot() + "/" + alias;
// }
//
// public String pluginRoot() {
// return appRoot() + "/" + APP_NAME;
// }
//
// public String pluginAlias(String alias) {
// return pluginRoot() + "/" + alias;
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/io/FileDownloader.java
// public final class FileDownloader {
//
// private final HttpServletResponse response;
//
// private final MemoryStream fileContent;
//
// private final String fileName;
//
// public FileDownloader(HttpServletResponse response, InputStream input, String fileName) {
// this.response = response;
// this.fileContent = new MemoryStream(input);
// this.fileName = fileName;
// }
//
// public void download() throws IOException {
// setResponseHeaders();
// writeResponseOutput();
// }
//
// private void setResponseHeaders() throws IOException {
// response.setContentLength(fileContent.getLength());
// response.setContentType("application/force-download");
// response.setHeader("Content-Transfer-Encoding", "binary");
// response.setHeader("Content-Disposition",
// String.format("attachment; filename=\"%s\"", fileName.trim()));
// response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// response.setHeader("Pragma", "no-cache");
// }
//
// private void writeResponseOutput() throws IOException {
// fileContent.writeOutput(response.getOutputStream());
// }
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public enum MessageType {
// SUCCESS,
// ERROR
// }
//
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/utils/JsonUtils.java
// public static void writeMessage(HttpServletResponse response, MessageType type, String text)
// throws IOException {
// writeMessage(response, type, text, Collections.<String, Object>emptyMap());
// }
// Path: src/main/java/com/neva/felix/webconsole/plugins/search/rest/FileDownloadServlet.java
import com.neva.felix.webconsole.plugins.search.core.SearchPaths;
import com.neva.felix.webconsole.plugins.search.utils.io.FileDownloader;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.MessageType;
import static com.neva.felix.webconsole.plugins.search.utils.JsonUtils.writeMessage;
package com.neva.felix.webconsole.plugins.search.rest;
public class FileDownloadServlet extends RestServlet {
public static final String ALIAS_NAME = "file-download";
private static final Logger LOG = LoggerFactory.getLogger(FileDownloadServlet.class);
public FileDownloadServlet(BundleContext bundleContext) {
super(bundleContext);
}
public static String url(BundleContext context, String path, String fileName) {
return String.format("%s?%s=%s&%s=%s", SearchPaths.from(context).pluginAlias(ALIAS_NAME),
RestParams.PATH_PARAM, path, RestParams.NAME_PARAM, fileName);
}
@Override
protected String getAliasName() {
return ALIAS_NAME;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
final RestParams params = RestParams.from(request);
final String path = params.getString(RestParams.PATH_PARAM);
final String name = StringUtils.defaultIfBlank(params.getString(RestParams.NAME_PARAM), UUID.randomUUID().toString());
final File file = new File(path);
if (!file.exists()) {
writeMessage(response, MessageType.ERROR, String.format("File at path '%s' cannot be found.", path));
} else { | new FileDownloader(response, new FileInputStream(file), name).download(); |
captain-miao/bleYan | blelibrary/src/main/java/com/github/captain_miao/android/ble/BaseBleScanner.java | // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java
// public enum BleScanState {
//
// SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"),
// BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"),
// SCAN_SUCCESS(0, "SCAN_SUCCESS"),
// SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"),
// SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"),
// SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"),
// SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"),
// SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES");
//
//
// BleScanState(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
//
// public String getMessage() {
// return message;
// }
//
// public static BleScanState newInstance(int code) {
// switch (code) {
// case -2:
// return BleScanState.SCAN_TIMEOUT;
// case -1:
// return BleScanState.BLUETOOTH_OFF;
//
// case 1:
// return BleScanState.SCAN_FAILED_ALREADY_STARTED;
// case 2:
// return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED;
// case 3:
// return BleScanState.SCAN_FAILED_INTERNAL_ERROR;
// case 4:
// return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED;
// case 5:
// return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES;
// default:
// return BleScanState.SCAN_SUCCESS;
// }
// }
// }
| import android.os.Handler;
import com.github.captain_miao.android.ble.constant.BleScanState; | package com.github.captain_miao.android.ble;
/**
* @author YanLu
* @since 15/9/14
*/
public abstract class BaseBleScanner {
public final static long defaultTimeout = 10 *1000;
protected boolean isScanning;
public abstract void onStartBleScan();
public abstract void onStartBleScan(long timeoutMillis);
public abstract void onStopBleScan();
| // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java
// public enum BleScanState {
//
// SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"),
// BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"),
// SCAN_SUCCESS(0, "SCAN_SUCCESS"),
// SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"),
// SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"),
// SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"),
// SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"),
// SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES");
//
//
// BleScanState(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
//
// public String getMessage() {
// return message;
// }
//
// public static BleScanState newInstance(int code) {
// switch (code) {
// case -2:
// return BleScanState.SCAN_TIMEOUT;
// case -1:
// return BleScanState.BLUETOOTH_OFF;
//
// case 1:
// return BleScanState.SCAN_FAILED_ALREADY_STARTED;
// case 2:
// return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED;
// case 3:
// return BleScanState.SCAN_FAILED_INTERNAL_ERROR;
// case 4:
// return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED;
// case 5:
// return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES;
// default:
// return BleScanState.SCAN_SUCCESS;
// }
// }
// }
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/BaseBleScanner.java
import android.os.Handler;
import com.github.captain_miao.android.ble.constant.BleScanState;
package com.github.captain_miao.android.ble;
/**
* @author YanLu
* @since 15/9/14
*/
public abstract class BaseBleScanner {
public final static long defaultTimeout = 10 *1000;
protected boolean isScanning;
public abstract void onStartBleScan();
public abstract void onStartBleScan(long timeoutMillis);
public abstract void onStopBleScan();
| public abstract void onBleScanFailed(BleScanState scanState); |
captain-miao/bleYan | blelibrary/src/main/java/com/github/captain_miao/android/ble/LollipopBleScanner.java | // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java
// public enum BleScanState {
//
// SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"),
// BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"),
// SCAN_SUCCESS(0, "SCAN_SUCCESS"),
// SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"),
// SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"),
// SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"),
// SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"),
// SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES");
//
//
// BleScanState(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
//
// public String getMessage() {
// return message;
// }
//
// public static BleScanState newInstance(int code) {
// switch (code) {
// case -2:
// return BleScanState.SCAN_TIMEOUT;
// case -1:
// return BleScanState.BLUETOOTH_OFF;
//
// case 1:
// return BleScanState.SCAN_FAILED_ALREADY_STARTED;
// case 2:
// return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED;
// case 3:
// return BleScanState.SCAN_FAILED_INTERNAL_ERROR;
// case 4:
// return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED;
// case 5:
// return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES;
// default:
// return BleScanState.SCAN_SUCCESS;
// }
// }
// }
//
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java
// public class BleLog {
// private static boolean isPrintLog = true;
//
// private BleLog() {}
//
// public static boolean isPrintLog() {
// return isPrintLog;
// }
//
// public static void setPrintLog(boolean isPrintLog) {
// BleLog.isPrintLog = isPrintLog;
// }
//
// public static void v(String tag, String msg) {
// if (isPrintLog) {
// Log.v(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (isPrintLog) {
// Log.d(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (isPrintLog) {
// Log.i(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (isPrintLog) {
// Log.w(tag, msg);
// }
// }
//
// public static void e(String tag, String msg) {
// if (isPrintLog) {
// Log.e(tag, msg);
// }
// }
// }
| import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Build;
import com.github.captain_miao.android.ble.constant.BleScanState;
import com.github.captain_miao.android.ble.utils.BleLog;
import java.util.List; | package com.github.captain_miao.android.ble;
/**
* @author YanLu
* @since 15/9/14
*
* Android5.0 above scan bluetooth
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class LollipopBleScanner extends BaseBleScanner {
private final static String TAG = LollipopBleScanner.class.getName();
private BluetoothLeScanner mBluetoothScanner = null;
private BluetoothAdapter mBluetoothAdapter = null;
private SimpleScanCallback mScanCallback = null;
public LollipopBleScanner(SimpleScanCallback callback) {
mScanCallback = callback;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
mBluetoothScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
}
@SuppressWarnings(value = {"deprecation"})
@Override
public void onStartBleScan(long timeoutMillis) {
long delay = timeoutMillis == 0 ? defaultTimeout : timeoutMillis;
if (mBluetoothScanner != null && mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
try {
mBluetoothScanner.startScan(scanCallback);
isScanning = true;
} catch (Exception e){
isScanning = false; | // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java
// public enum BleScanState {
//
// SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"),
// BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"),
// SCAN_SUCCESS(0, "SCAN_SUCCESS"),
// SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"),
// SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"),
// SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"),
// SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"),
// SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES");
//
//
// BleScanState(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
//
// public String getMessage() {
// return message;
// }
//
// public static BleScanState newInstance(int code) {
// switch (code) {
// case -2:
// return BleScanState.SCAN_TIMEOUT;
// case -1:
// return BleScanState.BLUETOOTH_OFF;
//
// case 1:
// return BleScanState.SCAN_FAILED_ALREADY_STARTED;
// case 2:
// return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED;
// case 3:
// return BleScanState.SCAN_FAILED_INTERNAL_ERROR;
// case 4:
// return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED;
// case 5:
// return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES;
// default:
// return BleScanState.SCAN_SUCCESS;
// }
// }
// }
//
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java
// public class BleLog {
// private static boolean isPrintLog = true;
//
// private BleLog() {}
//
// public static boolean isPrintLog() {
// return isPrintLog;
// }
//
// public static void setPrintLog(boolean isPrintLog) {
// BleLog.isPrintLog = isPrintLog;
// }
//
// public static void v(String tag, String msg) {
// if (isPrintLog) {
// Log.v(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (isPrintLog) {
// Log.d(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (isPrintLog) {
// Log.i(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (isPrintLog) {
// Log.w(tag, msg);
// }
// }
//
// public static void e(String tag, String msg) {
// if (isPrintLog) {
// Log.e(tag, msg);
// }
// }
// }
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/LollipopBleScanner.java
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Build;
import com.github.captain_miao.android.ble.constant.BleScanState;
import com.github.captain_miao.android.ble.utils.BleLog;
import java.util.List;
package com.github.captain_miao.android.ble;
/**
* @author YanLu
* @since 15/9/14
*
* Android5.0 above scan bluetooth
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class LollipopBleScanner extends BaseBleScanner {
private final static String TAG = LollipopBleScanner.class.getName();
private BluetoothLeScanner mBluetoothScanner = null;
private BluetoothAdapter mBluetoothAdapter = null;
private SimpleScanCallback mScanCallback = null;
public LollipopBleScanner(SimpleScanCallback callback) {
mScanCallback = callback;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
mBluetoothScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
}
@SuppressWarnings(value = {"deprecation"})
@Override
public void onStartBleScan(long timeoutMillis) {
long delay = timeoutMillis == 0 ? defaultTimeout : timeoutMillis;
if (mBluetoothScanner != null && mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
try {
mBluetoothScanner.startScan(scanCallback);
isScanning = true;
} catch (Exception e){
isScanning = false; | BleLog.e(TAG, e.toString()); |
captain-miao/bleYan | blelibrary/src/main/java/com/github/captain_miao/android/ble/LollipopBleScanner.java | // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java
// public enum BleScanState {
//
// SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"),
// BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"),
// SCAN_SUCCESS(0, "SCAN_SUCCESS"),
// SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"),
// SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"),
// SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"),
// SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"),
// SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES");
//
//
// BleScanState(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
//
// public String getMessage() {
// return message;
// }
//
// public static BleScanState newInstance(int code) {
// switch (code) {
// case -2:
// return BleScanState.SCAN_TIMEOUT;
// case -1:
// return BleScanState.BLUETOOTH_OFF;
//
// case 1:
// return BleScanState.SCAN_FAILED_ALREADY_STARTED;
// case 2:
// return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED;
// case 3:
// return BleScanState.SCAN_FAILED_INTERNAL_ERROR;
// case 4:
// return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED;
// case 5:
// return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES;
// default:
// return BleScanState.SCAN_SUCCESS;
// }
// }
// }
//
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java
// public class BleLog {
// private static boolean isPrintLog = true;
//
// private BleLog() {}
//
// public static boolean isPrintLog() {
// return isPrintLog;
// }
//
// public static void setPrintLog(boolean isPrintLog) {
// BleLog.isPrintLog = isPrintLog;
// }
//
// public static void v(String tag, String msg) {
// if (isPrintLog) {
// Log.v(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (isPrintLog) {
// Log.d(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (isPrintLog) {
// Log.i(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (isPrintLog) {
// Log.w(tag, msg);
// }
// }
//
// public static void e(String tag, String msg) {
// if (isPrintLog) {
// Log.e(tag, msg);
// }
// }
// }
| import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Build;
import com.github.captain_miao.android.ble.constant.BleScanState;
import com.github.captain_miao.android.ble.utils.BleLog;
import java.util.List; | package com.github.captain_miao.android.ble;
/**
* @author YanLu
* @since 15/9/14
*
* Android5.0 above scan bluetooth
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class LollipopBleScanner extends BaseBleScanner {
private final static String TAG = LollipopBleScanner.class.getName();
private BluetoothLeScanner mBluetoothScanner = null;
private BluetoothAdapter mBluetoothAdapter = null;
private SimpleScanCallback mScanCallback = null;
public LollipopBleScanner(SimpleScanCallback callback) {
mScanCallback = callback;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
mBluetoothScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
}
@SuppressWarnings(value = {"deprecation"})
@Override
public void onStartBleScan(long timeoutMillis) {
long delay = timeoutMillis == 0 ? defaultTimeout : timeoutMillis;
if (mBluetoothScanner != null && mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
try {
mBluetoothScanner.startScan(scanCallback);
isScanning = true;
} catch (Exception e){
isScanning = false;
BleLog.e(TAG, e.toString());
}
timeoutHandler.postDelayed(timeoutRunnable, delay);
} else { | // Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/constant/BleScanState.java
// public enum BleScanState {
//
// SCAN_TIMEOUT(-2, "SCAN_SUCCESS_TIME_OUT"),
// BLUETOOTH_OFF(-1, "BLUETOOTH_OFF"),
// SCAN_SUCCESS(0, "SCAN_SUCCESS"),
// SCAN_FAILED_ALREADY_STARTED(1, "SCAN_FAILED_ALREADY_STARTED"),
// SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(2, "SCAN_FAILED_APPLICATION_REGISTRATION_FAILED"),
// SCAN_FAILED_INTERNAL_ERROR(3, "SCAN_FAILED_INTERNAL_ERROR"),
// SCAN_FAILED_FEATURE_UNSUPPORTED(4, "SCAN_FAILED_FEATURE_UNSUPPORTED"),
// SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(5, "SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES");
//
//
// BleScanState(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// private int code;
// private String message;
//
// public int getCode() {
// return code;
// }
//
//
// public String getMessage() {
// return message;
// }
//
// public static BleScanState newInstance(int code) {
// switch (code) {
// case -2:
// return BleScanState.SCAN_TIMEOUT;
// case -1:
// return BleScanState.BLUETOOTH_OFF;
//
// case 1:
// return BleScanState.SCAN_FAILED_ALREADY_STARTED;
// case 2:
// return BleScanState.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED;
// case 3:
// return BleScanState.SCAN_FAILED_INTERNAL_ERROR;
// case 4:
// return BleScanState.SCAN_FAILED_FEATURE_UNSUPPORTED;
// case 5:
// return BleScanState.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES;
// default:
// return BleScanState.SCAN_SUCCESS;
// }
// }
// }
//
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/utils/BleLog.java
// public class BleLog {
// private static boolean isPrintLog = true;
//
// private BleLog() {}
//
// public static boolean isPrintLog() {
// return isPrintLog;
// }
//
// public static void setPrintLog(boolean isPrintLog) {
// BleLog.isPrintLog = isPrintLog;
// }
//
// public static void v(String tag, String msg) {
// if (isPrintLog) {
// Log.v(tag, msg);
// }
// }
//
// public static void d(String tag, String msg) {
// if (isPrintLog) {
// Log.d(tag, msg);
// }
// }
//
// public static void i(String tag, String msg) {
// if (isPrintLog) {
// Log.i(tag, msg);
// }
// }
//
// public static void w(String tag, String msg) {
// if (isPrintLog) {
// Log.w(tag, msg);
// }
// }
//
// public static void e(String tag, String msg) {
// if (isPrintLog) {
// Log.e(tag, msg);
// }
// }
// }
// Path: blelibrary/src/main/java/com/github/captain_miao/android/ble/LollipopBleScanner.java
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Build;
import com.github.captain_miao.android.ble.constant.BleScanState;
import com.github.captain_miao.android.ble.utils.BleLog;
import java.util.List;
package com.github.captain_miao.android.ble;
/**
* @author YanLu
* @since 15/9/14
*
* Android5.0 above scan bluetooth
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class LollipopBleScanner extends BaseBleScanner {
private final static String TAG = LollipopBleScanner.class.getName();
private BluetoothLeScanner mBluetoothScanner = null;
private BluetoothAdapter mBluetoothAdapter = null;
private SimpleScanCallback mScanCallback = null;
public LollipopBleScanner(SimpleScanCallback callback) {
mScanCallback = callback;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
mBluetoothScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
}
@SuppressWarnings(value = {"deprecation"})
@Override
public void onStartBleScan(long timeoutMillis) {
long delay = timeoutMillis == 0 ? defaultTimeout : timeoutMillis;
if (mBluetoothScanner != null && mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
try {
mBluetoothScanner.startScan(scanCallback);
isScanning = true;
} catch (Exception e){
isScanning = false;
BleLog.e(TAG, e.toString());
}
timeoutHandler.postDelayed(timeoutRunnable, delay);
} else { | mScanCallback.onBleScanFailed(BleScanState.BLUETOOTH_OFF); |
captain-miao/bleYan | example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/OpenSourceFragment.java | // Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java
// public class AppConstants {
//
// public static final String KEY_MODEL = "key_model";
// public static final String KEY_STATUS = "key_status";
// public static final String KEY_TITLE = "key_title";
// public static final String KEY_ID = "key_id";
// public static final String KEY_IS_BOOLEAN = "key_boolean";
//
// public static final String KEY_BLE_DEVICE = "key_ble_device";
// public static final String KEY_BLE_SERVICE = "key_ble_service";
// public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic";
//
// public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69;
// }
//
// Path: supportsdk/src/main/java/com/github/captain_miao/android/supportsdk/utils/DeviceUtilsLite.java
// public class DeviceUtilsLite {
//
// public static String getDeviceUniqueId(Context context) {
// String uid = "";
// if (context != null) {
// try {
// TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// String did = tm.getDeviceId();
// String sid = tm.getSubscriberId();
//
// if (did != null && !did.equals("")) {
// uid += did;
// }
// if (sid != null && !sid.equals("")) {
// uid += "_" + sid;
// }
// if (uid.equals("")) {
// uid = "unknown";
// }
// } catch (Exception e) {
//
// }
// }
// return uid;
// }
//
// public static int getAppVersionCode(Context context, String filePath) {
// int versionCode = 0;
// if (context != null) {
// try {
// PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(filePath, 0);
// versionCode = pi.versionCode;
// } catch (Exception e) {
//
// }
// }
// return versionCode;
// }
//
// public static int getAppVersionCode(Context context) {
// return getAppVersionCode(context, (ApplicationInfo) null);
// }
//
// public static int getAppVersionCode(Context context, ApplicationInfo info) {
// int versionCode = 0;
// if (context != null) {
// String packageName = "";
// if (info != null) {
// packageName = info.packageName;
// } else {
// packageName = context.getPackageName();
// }
// try {
// PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0);
// versionCode = pi.versionCode;
// } catch (Exception e) {
//
// }
// }
// return versionCode;
// }
//
// public static String getAppVersionName(Context context) {
// return getAppVersionName(context, null);
// }
//
// public static String getAppVersionName(Context context, ApplicationInfo info) {
// String versionName = "";
// if (context != null) {
// String packageName = "";
// if (info != null) {
// packageName = info.packageName;
// } else {
// packageName = context.getPackageName();
// }
// try {
// PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0);
// versionName = pi.versionName;
//
// } catch (Exception e) {
//
// }
// }
// return versionName;
// }
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.github.captain_miao.android.bluetoothletutorial.R;
import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants;
import com.github.captain_miao.android.supportsdk.utils.DeviceUtilsLite; | package com.github.captain_miao.android.bluetoothletutorial.fragment;
/**
* @author Yan Lu
* @since 2015-07-23
*/
public class OpenSourceFragment extends BaseFragment {
private static final String TAG = OpenSourceFragment.class.getSimpleName();
private String mTitle;
private TextView mTvTitle;
public OpenSourceFragment() {
}
public static OpenSourceFragment newInstance(String title) {
OpenSourceFragment f = new OpenSourceFragment();
Bundle args = new Bundle();
| // Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/constant/AppConstants.java
// public class AppConstants {
//
// public static final String KEY_MODEL = "key_model";
// public static final String KEY_STATUS = "key_status";
// public static final String KEY_TITLE = "key_title";
// public static final String KEY_ID = "key_id";
// public static final String KEY_IS_BOOLEAN = "key_boolean";
//
// public static final String KEY_BLE_DEVICE = "key_ble_device";
// public static final String KEY_BLE_SERVICE = "key_ble_service";
// public static final String KEY_BLE_CHARACTERISTIC = "key_ble_characteristic";
//
// public static final int PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 69;
// }
//
// Path: supportsdk/src/main/java/com/github/captain_miao/android/supportsdk/utils/DeviceUtilsLite.java
// public class DeviceUtilsLite {
//
// public static String getDeviceUniqueId(Context context) {
// String uid = "";
// if (context != null) {
// try {
// TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// String did = tm.getDeviceId();
// String sid = tm.getSubscriberId();
//
// if (did != null && !did.equals("")) {
// uid += did;
// }
// if (sid != null && !sid.equals("")) {
// uid += "_" + sid;
// }
// if (uid.equals("")) {
// uid = "unknown";
// }
// } catch (Exception e) {
//
// }
// }
// return uid;
// }
//
// public static int getAppVersionCode(Context context, String filePath) {
// int versionCode = 0;
// if (context != null) {
// try {
// PackageInfo pi = context.getPackageManager().getPackageArchiveInfo(filePath, 0);
// versionCode = pi.versionCode;
// } catch (Exception e) {
//
// }
// }
// return versionCode;
// }
//
// public static int getAppVersionCode(Context context) {
// return getAppVersionCode(context, (ApplicationInfo) null);
// }
//
// public static int getAppVersionCode(Context context, ApplicationInfo info) {
// int versionCode = 0;
// if (context != null) {
// String packageName = "";
// if (info != null) {
// packageName = info.packageName;
// } else {
// packageName = context.getPackageName();
// }
// try {
// PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0);
// versionCode = pi.versionCode;
// } catch (Exception e) {
//
// }
// }
// return versionCode;
// }
//
// public static String getAppVersionName(Context context) {
// return getAppVersionName(context, null);
// }
//
// public static String getAppVersionName(Context context, ApplicationInfo info) {
// String versionName = "";
// if (context != null) {
// String packageName = "";
// if (info != null) {
// packageName = info.packageName;
// } else {
// packageName = context.getPackageName();
// }
// try {
// PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0);
// versionName = pi.versionName;
//
// } catch (Exception e) {
//
// }
// }
// return versionName;
// }
// }
// Path: example/src/main/java/com/github/captain_miao/android/bluetoothletutorial/fragment/OpenSourceFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.github.captain_miao.android.bluetoothletutorial.R;
import com.github.captain_miao.android.bluetoothletutorial.constant.AppConstants;
import com.github.captain_miao.android.supportsdk.utils.DeviceUtilsLite;
package com.github.captain_miao.android.bluetoothletutorial.fragment;
/**
* @author Yan Lu
* @since 2015-07-23
*/
public class OpenSourceFragment extends BaseFragment {
private static final String TAG = OpenSourceFragment.class.getSimpleName();
private String mTitle;
private TextView mTvTitle;
public OpenSourceFragment() {
}
public static OpenSourceFragment newInstance(String title) {
OpenSourceFragment f = new OpenSourceFragment();
Bundle args = new Bundle();
| args.putString(AppConstants.KEY_TITLE, title); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.