I am learning Reactjs and created a project using React and Spring (Data, Jpa, Rest). Here is the link of the project in Github. The project can be used to learn how to integrate React js with Spring.
Java Fast Scanner Template
This is a fast scanner for Java using Petr’s java template. I have changed a bit to read (remaining) line.
import java.io.*;
import java.util.StringTokenizer;
/**
* Created by sabbir on 01/14/16.
*/
public class Main {
public static void main(String[] args) throws Exception {
FastScanner scanner = new FastScanner(System.in);
long val = scanner.nextLong();
String str = scanner.nextLine();
PrintWriter printWriter = new PrintWriter(System.out);
printWriter.printf("%d\n", val);
printWriter.printf("%d\n", str);
printWriter.close();
}
static class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public long nextInt() {
return Integer.parseInt(next());
}
}
}
Java Enum and Android IntDef/StringDef annotation
When we want a variable x to have values from some predefined constants then what can we do. We can declare the constant variables and set x from these constants. Lets assume x is currentDay and it can have any value from sunday to friday. We can code like this in java using integer constants.
public class Main {
public static final int SUNDAY = 0;
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;
private int currentDay = SUNDAY;
public static void main(String[] args) {
// TODO Auto-generated method stub
Main obj = new Main();
obj.setCurrentDay(WEDNESDAY);
int today = obj.getCurrentDay();
switch (today) {
case SUNDAY:
System.out.println("Today is SUNDAY");
break;
case MONDAY:
System.out.println("Today is MONDAY");
break;
case TUESDAY:
System.out.println("Today is TUESDAY");
break;
case WEDNESDAY:
System.out.println("Today is WEDNESDAY");
break;
case THURSDAY:
System.out.println("Today is THURSDAY");
break;
case FRIDAY:
System.out.println("Today is FRIDAY");
break;
case SATURDAY:
System.out.println("Today is SATURDAY");
break;
default:
break;
}
}
public void setCurrentDay(int currentDay) {
this.currentDay = currentDay;
}
public int getCurrentDay() {
return currentDay;
}
}
Problem with this code is I can set any integer value to currentDay.
obj.setCurrentDay(100);
and compiler will not give me any error. Then in switch/case we will miss that value. So Java gives us a solution that is Enumeration or Enum. If We rewrite the code with Enum in Java.
public class Main {
public enum WeekDays {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
private WeekDays currentDay = WeekDays.SUNDAY;
public static void main(String[] args) {
// TODO Auto-generated method stub
Main obj = new Main();
obj.setCurrentDay(WeekDays.WEDNESDAY);
WeekDays today = obj.getCurrentDay();
switch (today) {
case SUNDAY:
System.out.println("Today is SUNDAY");
break;
case MONDAY:
System.out.println("Today is MONDAY");
break;
case TUESDAY:
System.out.println("Today is TUESDAY");
break;
case WEDNESDAY:
System.out.println("Today is WEDNESDAY");
break;
case THURSDAY:
System.out.println("Today is THURSDAY");
break;
case FRIDAY:
System.out.println("Today is FRIDAY");
break;
case SATURDAY:
System.out.println("Today is SATURDAY");
break;
default:
break;
}
}
public void setCurrentDay(WeekDays currentDay) {
this.currentDay = currentDay;
}
public WeekDays getCurrentDay() {
return currentDay;
}
}
Now we have type safety. I can not have any value other then WeekDays in currentDay variable. That is a great improvement, and we should use it. But in Android there is a problem.
Enum in Android: Enum is a full fledged class in Java. Every value of Enum is an object of that Enum class. So Enum values will take more memory then int constant we used earlier. Even in old android devices (<=2.2), there were some performance issue related to Enum which were solved in JIT compiler. Now we can use Enum in Android Application, but if our application is a memory hungry application or a game application then we better use integer constants instead of Enum. But then problem remains.
There is a solution. Android support annotation library has some good annotation helper which can be used to find bug earlier (in compile time). IntDef and StringDef are two Magic Constant Annotation which can be used instead of Enum. These will help us to check variable assignment like Enum in compile time. Following code showed how to use IntDef instead of Enum.
public class MainActivity extends Activity {
public static final int SUNDAY = 0;
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;
@IntDef({SUNDAY, MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY})
@Retention(RetentionPolicy.SOURCE)
public @interface WeekDays {}
@WeekDays int currentDay = SUNDAY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentDay(WEDNESDAY);
@WeekDays int today = getCurrentDay();
switch (today){
case SUNDAY:
break;
case MONDAY:
break;
case TUESDAY:
break;
case WEDNESDAY:
break;
case THURSDAY:
break;
case FRIDAY:
break;
case SATURDAY:
break;
default:
break;
}
}
public void setCurrentDay(@WeekDays int currentDay) {
this.currentDay = currentDay;
}
@WeekDays
public int getCurrentDay() {
return currentDay;
}
}
Now we can not set any value other than WeekDays in currentDay or today variable. Compiler will check it and will give error. And if we use Android Studio, IDE will give suggestion about the value. So how to use it. At first declare the constants.
public static final int SUNDAY = 0;
public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
public static final int SATURDAY = 6;
Then declare the @IntDef for these constants,
@IntDef({SUNDAY, MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY})
@Retention(RetentionPolicy.SOURCE)
public @interface WeekDays {}
To set a variable of WeekDays type, so that no value other than weekdays can be set to that variable, we declare it like following,
@WeekDays int currentDay ;
Now if there is any assignment which set currentDay to any other value than WeekDays, compiler will give a error. To set function parameter and function return type with WeekDays type,
public void setCurrentDay(@WeekDays int currentDay) {
this.currentDay = currentDay;
}
@WeekDays
public int getCurrentDay() {
return currentDay;
}
@StringDef can be used in same manner.
public class MainActivity extends Activity {
public static final String SUNDAY = "sunday";
public static final String MONDAY = "monday";
public static final String TUESDAY = "tuesday";
public static final String WEDNESDAY = "wednesday";
public static final String THURSDAY = "thursday";
public static final String FRIDAY = "friday";
public static final String SATURDAY = "saturday";
@StringDef({SUNDAY, MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY})
@Retention(RetentionPolicy.SOURCE)
public @interface WeekDays {}
@WeekDays String currentDay = SUNDAY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentDay(WEDNESDAY);
@WeekDays String today = getCurrentDay();
switch (today){
case SUNDAY:
break;
case MONDAY:
break;
case TUESDAY:
break;
case WEDNESDAY:
break;
case THURSDAY:
break;
case FRIDAY:
break;
case SATURDAY:
break;
default:
break;
}
}
public void setCurrentDay(@WeekDays String currentDay) {
this.currentDay = currentDay;
}
@WeekDays
public String getCurrentDay() {
return currentDay;
}
}
To use this feature, you have to add support-annotations library to your project. If you use Android Studio, then add following in your Gradle dependency.
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
...
compile 'com.android.support:support-annotations:22.0.0'
}
You can learn more about support annotation library here. And below is android performance patterns video about price of Enum.
Android adb over Wifi
You can connect to Android device adb through TCP/IP (Wi-Fi) connection. This is very useful if you want to check usb connection or charging discharging feature while debugging. Your PC and device has to be in same network and you need to know the IP address of your device. To do this connect your device over usb. Check it is in debug mode by
$ adb devices List of devices attached TA93404MC8 device
Start the adb in TCP/IP mode in port 5555 (default port). You can use other port (8888, etc).
$ adb tcpip 5555
Then connect to your device over Wi-Fi
$ adb connect xxx.yyy.zzz.ppp connected to xxx.yyy.zzz.ppp:5555
where xxx.yyy.zzz.ppp is the IP address of your device.
Then run
$ adb devices List of devices attached TA93404MC8 device xxx.yyy.zzz.ppp:5555 device
Then unplug the device over usb, and run
$ adb logcat
It should show the logs of your device.
To return back to usb mode, run
$ adb usb
You may have to connect your device over usb to do this.
Android Forground Service for device Orientation and surfaceview
This service start in foreground with a view in windowmanager which change the orientation of the device and a surfaceview which can be used by camera for recording even when phone locked and screen off. Thanks to pallab.
public class SurfaceViewService extends Service {
private WindowManager windowManager;
final WindowManager.LayoutParams myParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
private static SurfaceView mSurfaceView = null;
@Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE);
myParams.gravity = Gravity.TOP | Gravity.CENTER;
myParams.height=1;
myParams.width=1;
myParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
mSurfaceView = new SurfaceView(this);
windowManager.addView(mSurfaceView, myParams);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("gg")
.setTicker("gg")
.setContentText("gg is running")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.logo);
Notification cur_notification = builder.build();
startForeground(1, cur_notification);
}
public static SurfaceView getSurfaceView(){
if(mSurfaceView==null) {
mLogger.error("surfaceview service not started");
}
return mSurfaceView;
}
@Override
public void onDestroy() {
super.onDestroy();
windowManager.removeView(mSurfaceView);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
How to check the size of a growing folder (Linux)
This command will run “du -s .” every 1 second and print the output in full screen (terminal). The result is size of folder in every 1 second.
$ watch -n 1 "du -s ."
watch runs a command repeatedly.
Openssl and nodejs
This an awesome post for openssl public key private key
http://www.devco.net/archives/2006/02/13/public_-_private_key_encryption_using_openssl.php
Here is the post for openssl certificate
http://www.thegeekstuff.com/2009/07/linux-apache-mod-ssl-generate-key-csr-crt-file/
At first generate ssl using openssl
1. Create a private key
$openssl genrsa 1024 > server.key
2. Create a Certificate Signing Request
$openssl req -new -key server.key -out server.csr
3. Create a ssl certificate
$openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Now use this code to run in node.js
var https = require('https');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
save file as server.js.
Now run
$node server.js
open browser, hit:
https://localhost:8000
ffmpeg screen capture linux
You can record desktop screen using ffmpeg from a linux machine.
Compile ffmpeg with following options
./configure --enable-libx264 --enable-x11grab --enable-gpl --enable-version3 --enable-nonfree --enable-shared make -j9 make install
Then grab screen using following command
ffmpeg -video_size 1366x768 -framerate 30 -f x11grab -i :0.0 -c:v libx264 output.flv
checked with ffmpeg version 2.1 in ubuntu 12.04
JNI call and callback in Android
This is a cpp file which I used to jni call and callback in one of my project. I post it here so that i do not have to re r&d. It uses android 4.0.3 source to compile.
#include "JNIMain.h"
#include "GlobalResource.h"
#include "Recorder.h"
JavaVM *javaVM;
jobject recorderJava;
Recorder recorder;
jmethodID audioCallBackID;
jmethodID videoCallBackID;
extern sp<Camera> get_native_camera(JNIEnv *env, jobject thiz, struct JNICameraContext** context);
extern "C" {
Recorder* recorder;
jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)
{
GlobalResource* gr = GlobalResource::getInstance();
javaVM = jvm;
return JNI_VERSION_1_6;
}
jint Java_stopNativeRecording(JNIEnv *env, jobject obj)
{
if(recorder!=0)
{
LOGD("stopping native recorder");
recorder->stop();
if(recorderJava!=0)
env->DeleteGlobalRef(recorderJava);
}
else
{
LOGD("recording was not started");
}
return 0;
}
jint Java_startNativeRecording(JNIEnv *env, jobject obj, jobject jCamera, jobject jSurface)
{
LOGD("starting native recorder");
GlobalResource* gr = GlobalResource::getInstance();
recorderJava = env->NewGlobalRef(obj);
jclass cls = env->GetObjectClass(obj);
audioCallBackID = env->GetMethodID(cls,"onAudioData", "([B)V");
videoCallBackID = env->GetMethodID(cls,"onVideoData", "([B)V");
sp<Camera> cmr=get_native_camera(env,jCamera, NULL);
jclass surfaceClass = env->FindClass("android/view/Surface");
jfieldID surfaceField = env->GetFieldID(surfaceClass, "mNativeSurface", "I");
Surface* const p = (Surface*)(env->GetIntField(jSurface, surfaceField));
sp<Surface> surface=sp<Surface>(p);
recorder = new Recorder();
recorder->start(cmr,surface);
return 0;
}
jobject Java_getCodecInfo(JNIEnv *env, jobject obj, jobject jCamera, jobject jSurface)
{
LOGD("starting native recorder");
GlobalResource* gr = GlobalResource::getInstance();
recorderJava = env->NewGlobalRef(obj);
jclass cls = env->GetObjectClass(obj);
audioCallBackID = env->GetMethodID(cls,"onAudioData", "([B)V");
videoCallBackID = env->GetMethodID(cls,"onVideoData", "([B)V");
sp<Camera> cmr=get_native_camera(env,jCamera, NULL);
jclass surfaceClass = env->FindClass("android/view/Surface");
jfieldID surfaceField = env->GetFieldID(surfaceClass, "mNativeSurface", "I");
Surface* const p = (Surface*)(env->GetIntField(jSurface, surfaceField));
sp<Surface> surface=sp<Surface>(p);
recorder = new Recorder();
recorder->storeCodecInfo(cmr,surface);
/*******************************************returning**************************************/
jclass CodecInfoClass = env->FindClass("CodecInfo");
jmethodID constructor = env->GetMethodID(CodecInfoClass, "<init>", "()V"); // no parameters
jobject codecInfo = env->NewObject(CodecInfoClass, constructor);
//get field ids
LOGD("here");
jfieldID spsFieldID = env->GetFieldID(CodecInfoClass, "VIDEO_SPS", "[B");
jfieldID ppsFieldID = env->GetFieldID(CodecInfoClass, "VIDEO_PPS", "[B");
jfieldID audioProfileFieldID = env->GetFieldID(CodecInfoClass, "AUDIO_PROFILE", "I");
jfieldID audioSamplingRateFieldID = env->GetFieldID(CodecInfoClass, "AUDIO_ACTUAL_SAMPLING_RATE", "I");
jfieldID audioChannelID = env->GetFieldID(CodecInfoClass, "AUDIO_CHANNEL", "I");
LOGD("here");
//sps
android::List<AVCParamSet>::iterator itS = gr->mSeqParamSets.begin();
if(itS != gr->mSeqParamSets.end())
{
int seqParamSetLength = itS->mLength;
jbyteArray vsps = env->NewByteArray(seqParamSetLength);;
env->SetByteArrayRegion(vsps, 0, seqParamSetLength, (jbyte*)itS->mData);
env->SetObjectField (codecInfo, spsFieldID, vsps);
}
LOGD("sps done");
//pps
android::List<AVCParamSet>::iterator itP = gr->mPicParamSets.begin();
if(itP != gr->mPicParamSets.end())
{
int picParamSetLength = itP->mLength;
jbyteArray vpps = env->NewByteArray(picParamSetLength);
env->SetByteArrayRegion(vpps, 0, picParamSetLength, (jbyte*)itP->mData);
env->SetObjectField (codecInfo, ppsFieldID, vpps);
}
LOGD("pps done");
//audioProfile
env->SetIntField(codecInfo, audioProfileFieldID, gr->mProfile);
//audioSamplingRate
env->SetIntField(codecInfo, audioSamplingRateFieldID, gr->mActualSampleingRate);
//audioChannel
env->SetIntField(codecInfo, audioChannelID, gr->mChannel);
return codecInfo;
}
jint Java_cameraPreviewTest(JNIEnv *env,
jobject obj, jobject jSurface)
{
return 0;
}
} //extern c
// these functions are called from c++
JNIEnv* attachCurrentThreadtoJVM()
{
JavaVM *jvm = javaVM;
JNIEnv *env=NULL;
jvm->GetEnv((void **)&env, JNI_VERSION_1_6);
jvm->AttachCurrentThread(&env, NULL);
return env;
}
void detachCurrentThreadtoJVM()
{
JavaVM *jvm = javaVM;
jvm->DetachCurrentThread();
}
void sendDataToJava(JNIEnv* env,Packet* pk, MEDIATYPE dataType)
{
jbyteArray jbArray = env->NewByteArray(pk->length);
env->SetByteArrayRegion(jbArray, 0, pk->length, (jbyte*)pk->data);
if(dataType == AUDIO)
env->CallVoidMethod(recorderJava, audioCallBackID, jbArray);
else
env->CallVoidMethod(recorderJava, videoCallBackID, jbArray);
delete pk->data;
delete pk;
env->DeleteLocalRef(jbArray);
}
Android NDK create executable
It is possible to create executable using android ndk. You need adb to push the executable to the device. Modify/create the Android.mk file in jni folder so that ndk-build create executable rather then shared library.
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := hello_world LOCAL_SRC_FILES := test.cpp include $(BUILD_EXECUTABLE)
My cpp file contains following code
#include <stdio.h>
int main()
{
printf("hello world\n");
}
Run ndk-build in jni folder. Then a executable will create in libs/armeabi folder in hello_world name. Attach your device to the pc. Open your console and go the libs/armeabi folder. Run adb push hello_world /data/local/tmp. Now run adb shell. This will open the shell of your device. cd to the /data/local/tmp. Run ./hello_world. The console will show the output. /data is the only executable section in android.