Friday, February 14, 2014

java


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class MainClass {

public static void main(String args[]) {
try {
System.out.println("enter your name");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();

System.out.println("You entered "+str);
return;

} catch (Exception e) {
e.printStackTrace();
}
}
}

Tuesday, January 21, 2014


Custom Radio Button GKIndia



                 

 <RadioButton
                        android:id="@+id/rb1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:button="@drawable/button_radio"
                        android:gravity="center_vertical"
                        android:text="" />

Tuesday, November 12, 2013

Encrypt and Decrypt any File IN Android or Java

Encrypt and Decrypt any File IN Android or Java



package com.example.encryption;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String key = "squirrel123"; // needs to be at least 8 characters for DES
try{ Log.e("started", "");
FileInputStream fis = new FileInputStream("sdcard/raj.jpg");

FileOutputStream fos = new FileOutputStream("sdcard/c.txt");
encrypt(key, fis, fos);

FileInputStream fis2 = new FileInputStream("sdcard/c.txt");
FileOutputStream fos2 = new FileOutputStream("sdcard/c.jpg");
decrypt(key, fis2, fos2);
}catch(Exception e){e.printStackTrace();} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}

public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
}

public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {

DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE

if (mode == Cipher.ENCRYPT_MODE) {
cipher.init(Cipher.ENCRYPT_MODE, desKey);
CipherInputStream cis = new CipherInputStream(is, cipher);
doCopy(cis, os);
} else if (mode == Cipher.DECRYPT_MODE) {
cipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream cos = new CipherOutputStream(os, cipher);
doCopy(is, cos);
}
}

public static void doCopy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[64];
int numBytes;
while ((numBytes = is.read(bytes)) != -1) {
os.write(bytes, 0, numBytes);
}
os.flush();
os.close();
is.close();
}
}

Monday, November 11, 2013

List Of Remote Folders

Create a List Of Remote Folders using JSCH for android, Java in a ListView In Dialog Box.




import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;

import com.example.newsync.R;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Listremote extends Activity{
ChannelSftp sftpChannel;
ListAdapter adapter;
ArrayAdapter<String> adaptor;
com.jcraft.jsch.ChannelSftp.LsEntry lsEntry ;
private Item[] fileList;
ArrayList<String> list = new ArrayList<String>();
String path;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


JSch jsch = new JSch();
Session session = null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
session = jsch.getSession("USER Name", "Host Address", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("Password");
session.connect();
Channel channel = session.openChannel("sftp");
Handler h = new Handler(Listremote.this.getMainLooper());
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(Listremote.this, "Connecting",
Toast.LENGTH_LONG).show();
}
});
channel.connect();
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(Listremote.this, "Connected",
Toast.LENGTH_LONG).show();
}
});
sftpChannel = (ChannelSftp) channel;
sftpChannel.cd(".");


try {

if(path==null){
Log.e("path null", "path null");
path=".";

}
@SuppressWarnings("rawtypes")
Vector files = sftpChannel.ls(path);
if (files.size() == 0) {
Toast.makeText(getApplicationContext(),
"No files are available for download.", 4)
.show();
} else {
for (int i = 0; i < files.size(); i++) {
lsEntry = (com.jcraft.jsch.ChannelSftp.LsEntry) files
.get(i);
if (lsEntry.getAttrs().isDir()&& !lsEntry.getFilename().equals(".")
&& !lsEntry.getFilename().equals("..")&&!lsEntry.getFilename().startsWith(".")&&!lsEntry.getFilename().startsWith("..")){
// Log.e(lsEntry.toString(), "files");
//List items = Arrays.asList(lsEntry.getFilename());
list.add(lsEntry.getFilename());

//Log.e(""+items.toString(), "items");
// Log.e(lsEntry.getAttrs().getSize()+"","lsentry Size");
// Log.e(lsEntry+"","list Size");
fileList = new Item[list.size()];

for (int j = 0; j < list.size(); j++) {
fileList[j] = new Item(list.toString(), R.drawable.directory_icon);

}
Log.e("file list "+fileList, "list "+list.toString());
//List<String> colorChoices = list;
//Log.e(colorChoices+"","list ");
adaptor = new ArrayAdapter<String>(
this,android.R.layout.select_dialog_item, android.R.id.text1, list){
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);

// put the image on the text view
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);

// add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);

return view;
}
};


}

}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Remote Files");

builder.setAdapter(adaptor, new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int item) {
    String itemname = adaptor.getItem(item);
    Log.e(""+itemname,"file Clicked");
   // String chosenFile = fileList[item].file;
    path=itemname;

   }
});
builder.show();}
}catch(Exception e){e.printStackTrace();}

//sftpChannel.put("" + sel, "Desktop/");

//String r = userId + "." + sel.getName();
//sftpChannel.rename("Desktop/" + sel.getName(),
// "Desktop/" + r);
h.post(new Runnable() {
@Override
public void run() {
try {
/*
AlertDialog.Builder builder = new AlertDialog.Builder(
Listremote.this);
builder.setMessage(
"File Sent Successfully")
.setCancelable(false)
.setPositiveButton(
"Listremote More",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
//loadFileList();
//showDialog(1);

}
});
builder.setNegativeButton(
"Not now",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int id) {
//dialog.cancel();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
*/
} catch (Exception e) {
e.printStackTrace();
}
}
});
sftpChannel.exit();
session.disconnect();
//Log.e("" + sel, "FileClicked");
} catch (final JSchException e) {
runOnUiThread(new Runnable() {
@SuppressLint("ShowToast")
@Override
public void run() {
Toast.makeText(
Listremote.this,
"Check Host, Username and Password "
+ e.getMessage().toString(),
10).show();
}
});

e.printStackTrace();
} catch (final SftpException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(
Listremote.this,
"error - server not responding"
+ e.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();

}


}private class Item {
public String file;
public int icon;

public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}

@Override
public String toString() {
return file;
}
}

}

Friday, October 4, 2013

Rsync Working Example Android


Rsync Working Sample Android
Properly Tested Example
If need any help just mail @ rajeshsaini890@gmail.com

first you need to download rsyncdroid project from google project by svn
http://code.google.com/p/rsyncdroid/source/checkout
type command in terminal sudo apt-get install subversion
to install svn then copy svn command from project page and paste to terminal 
then import the downloaded project to eclipse
now 
first replace the complete code given in Rsyncdroid.class file with the give below
and now copy rsync binary file form R.raw.rsync and paste it to device folder /system/xbin/rsync you can use rootexplorer.apk to do this
now 
you need to generate dss_key and dss_key.pub by using dropbearkey
then put dss_key and dss_key.pub file in sdcard.
then copy contents of dss_key.pub and paste to the server or your computers folder Home/.ssh/ AuthorizedKeys file.
This is posswordless authentication.

now put your host username in rsync command source directory and resource directory and path of dss_key file in sdcard  as given below
and run program.




import java.io.BufferedOutputStream;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


import android.util.Log;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RsyncDroid extends Activity {

private static final String LOG_TAG = "RsyncDro";
private static final String RSYNCD_DIR = "/sdcard/rsyncdroid/";
private static final String RSYNCD_CONF = "/sdcard/rsyncdroid/rsyncd.conf";
private String RSYNCD_BIN = "/system/xbin/rsync";
private String RSYNC_PATH = "";
private String RSYNC_BIN = "rsync";
private Process process;
private Boolean USE_ROOT = true;
// private String MY_USERNAME = "";
private static final String[] DEFAULT_CONF = { "uid=0", "gid=0",
"read only = yes", "use chroot = no", "", "[sdcard]",
" path = /sdcard/Urotab/", " comment = SD Card" };
OutputStream os;
CheckBox CheckboxRunning;
Button btnStart;
Button btnStop;
EditText txtBox;
TextView conftxt;
Boolean bool1 = true;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

CheckboxRunning = (CheckBox) findViewById(R.id.Running);
txtBox = (EditText) findViewById(R.id.RsyncdConf);
conftxt = (TextView) findViewById(R.id.ConfText);

btnStart = (Button) findViewById(R.id.ButtonStart);
btnStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// save conf in file
saveConf();
startRsync();
Log.d(LOG_TAG, "onCreate() rsync started...");
changeStatus();
if (statusRsync()) {
showMsg("rsync started");
}
setResult(android.app.Activity.RESULT_OK);
}

});

btnStop = (Button) findViewById(R.id.ButtonStop);
btnStop.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
if (stopRsync()) {
showMsg("rsync stopped");
setResult(android.app.Activity.RESULT_OK);
}
changeStatus();
}

});

// load configuration in txtBox
txtBox.setText(loadConf().toString());

// MY_USERNAME=getUsername();

// change checkbox status
changeStatus();

RSYNC_PATH = rsync_path();
RSYNCD_BIN = RSYNC_PATH + RSYNC_BIN;

if (!new File(RSYNCD_BIN).exists()) {
installRsync(RSYNCD_BIN, R.raw.rsync);
showMsg("rsync installed on " + RSYNCD_BIN);
}
}

public void changeStatus() {
if (statusRsync()) {
CheckboxRunning.setChecked(true);
txtBox.setVisibility(View.INVISIBLE);
conftxt.setVisibility(View.INVISIBLE);
} else {
CheckboxRunning.setChecked(false);
txtBox.setVisibility(View.VISIBLE);
conftxt.setVisibility(View.VISIBLE);
}

}

@SuppressWarnings("static-access")
public void startRsync() {


if (!new File(RSYNCD_BIN).exists()) {
showMsg("rsync not installed");
return;
}

Thread thread = new Thread() {
@Override
public void run() {
try {
List<String> commands = new ArrayList<String>();
int i = 1, j = 1;

commands.add("/rsync".substring(i));
commands.add("-vvvrHrltD");

commands.add("--chmod=Du+rwx,go-rwx,Fu+rw,go-rw");
commands.add("--no-perms");
commands.add("-e");
commands.add("/ssh".substring(j) + " -y -p "
+ Integer.valueOf(22)
+ " -i '/sdcard/dss_key' ");
commands.add("/sdcard/Urotab/");
commands.add(("root") + "@" + "YOUR IP"
+ ":" + "Desktop/urosecure/");

ProcessBuilder pb = new ProcessBuilder(commands);
try {
Process prs = pb.start();
InputStream stderr = prs.getErrorStream();
InputStream stdout = prs.getInputStream();

BufferedReader stdoutReader = new BufferedReader(
new InputStreamReader(stdout));
BufferedReader stderrReader = new BufferedReader(
new InputStreamReader(stderr));

System.out
.println("Here is the output from stdout:");

while (true) {
String line = stdoutReader.readLine();
if (line == null) {
stdoutReader.close();
break;
}
System.out.println(line);
}

System.out
.println("Here is the output from stderr:");

while (true) {
String line = stderrReader.readLine();
if (line == null) {
stderrReader.close();
break;
}
System.out.println(line);
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (Exception e) {
e.printStackTrace();
}

}

};
thread.start();

try {
Thread.currentThread().sleep(2000);// sleep for 2000 ms
} catch (InterruptedException e) {
e.printStackTrace();
}


}




public boolean stopRsync() {
String pid;
String temp;
pid = "";
int i;
try {
Process p = Runtime.getRuntime().exec("ps");
p.waitFor();

BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((temp = stdInput.readLine()) != null) {
// Log.d(LOG_TAG, "stopRsync() temp='"+temp+"'");
if (temp.contains(RSYNCD_BIN)) {
// Log.d(LOG_TAG, "statusRsync() temp='"+temp+"'");
String[] cmdArray = temp.split(" +");
for (i = 0; i < cmdArray.length; i++) {
Log.d(LOG_TAG, "loop i=" + i + " => " + cmdArray[i]);
}
pid = cmdArray[1];
}
}

} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

Log.d(LOG_TAG, "statusRsync() pid='" + pid + "'");

// if pid
if (pid != "") {
Log.d(LOG_TAG, "statusRsync() killing='" + pid + "' ...");
try {
if (USE_ROOT) {
process = Runtime.getRuntime().exec("su -c sh");
OutputStream os = process.getOutputStream();
writeLine(os, "kill -9 " + pid);
os.flush();
writeLine(os, "exit \n");
os.flush();
process.waitFor();
return true;
} else {
process = Runtime.getRuntime().exec("sh");
OutputStream os = process.getOutputStream();
writeLine(os, "kill -9 " + pid);
os.flush();
writeLine(os, "exit \n");
os.flush();
process.waitFor();
return true;
}

} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(LOG_TAG, "statusRsync() pid empty='" + pid + "'");
return false;
}

public boolean statusRsync() {
boolean run;
String temp;

run = false;
Log.d(LOG_TAG, "statusRsync() init");

try {
Process p = Runtime.getRuntime().exec("ps");
p.waitFor();

BufferedReader stdInput = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((temp = stdInput.readLine()) != null) {
// Log.d(LOG_TAG, "statusRsync() temp='"+temp+"'");
if (temp.contains("app_bin/rsync")) {
Log.d(LOG_TAG, "statusRsync() FOUND temp='" + temp + "'");
run = true;
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return run;
}

public String loadConf() {
String Script = "";
File rsyncd_conf_folder = new File(RSYNCD_DIR);

if (!rsyncd_conf_folder.exists()) {
Log.d(LOG_TAG, "Creating " + RSYNCD_DIR + " folder");
rsyncd_conf_folder.mkdir();
showMsg("Created " + RSYNCD_DIR + " folder");
} else {
Log.d(LOG_TAG, RSYNCD_DIR + " exists");
}

// create rsyncd.conf
if (!new File(RSYNCD_CONF).exists()) {
showMsg("rsyncd.conf no exists");
for (int i = 0; i < DEFAULT_CONF.length; i++) {
Script += DEFAULT_CONF[i] + "\n";
}
return Script;
}

try {
BufferedReader in = new BufferedReader(new FileReader(RSYNCD_CONF));
String str;

while ((str = in.readLine()) != null) {
Script += str + "\n";
}
in.close();
} catch (Exception ex) {
showMsg("Can't read rsyncd.conf");
return Script;
}

return Script;
}

public void saveConf() {
Writer output = null;
Log.d(LOG_TAG, "saveConf() init");
try {
output = new BufferedWriter(new FileWriter(RSYNCD_CONF));
output.write(txtBox.getText().toString());
output.close();
Log.d(LOG_TAG, "saveConf() saved and closed");
} catch (IOException e) {
e.printStackTrace();
}
}

public void showMsg(String txt) {
CharSequence text = txt;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(this, text, duration);
toast.show();
Log.d(LOG_TAG, "showMsg() txt='" + txt + "'");
}

public static void writeLine(OutputStream os, String value)
throws IOException {
String line = value + "\n";
os.write(line.getBytes());
}

private void installRsync(String ff_file, int rawid) {

Log.d(LOG_TAG, "installRsync() **rsync_abspath=" + ff_file + "**");

if (!new File(ff_file).exists()) {
InputStream rsyncraw;
Log.d(LOG_TAG, "installRsync() **no exists, copy...**");
try {
rsyncraw = getResources().openRawResource(rawid);
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "installRsync() **Exception**");
return;
} finally {
Log.d(LOG_TAG, "installRsync() ** OPENED rsync_abspath="
+ ff_file + "**");
}
BufferedOutputStream fOut = null;
try {
fOut = new BufferedOutputStream(new FileOutputStream(ff_file));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
while ((bytesRead = rsyncraw.read(buffer)) != -1) {
fOut.write(buffer, 0, bytesRead);
}
Log.d(LOG_TAG, "installRsync() **no exists, copy done**");
Runtime.getRuntime().exec("chmod 755 " + ff_file);
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "installRsync() **Exception**");
} finally {
try {
rsyncraw.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
Log.d(LOG_TAG, "installRsync() **Exception**");
}
}
}
}

private String rsync_path() {
ContextWrapper cw = new ContextWrapper(getBaseContext());
File directory = cw.getDir("bin", Context.MODE_PRIVATE);
String rsync_abspath = directory + "/";
return rsync_abspath;
}

/*
* private String getUsername() { String temp=""; try{ Process p =
* Runtime.getRuntime().exec("whoami"); p.waitFor();
*
* BufferedReader stdInput = new BufferedReader(new
* InputStreamReader(p.getInputStream())); while ( (temp =
* stdInput.readLine()) != null ) { Log.d(LOG_TAG,
* "getUsername() temp='"+temp+"'"); if ( temp != "" ) { return temp; } }
*
* } catch (IOException e) { e.printStackTrace(); } catch
* (InterruptedException e) { e.printStackTrace(); }
*
* return temp; }
*/
}