Senin, 28 November 2016

Android Login Using .txt

package com.example.lp2maray;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;
import android.util.Log;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.view.KeyEvent;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Menu_Login extends ActionBarActivity {
    EditText edPass,edUser;
    private static final String TAG = Menu_Login.class.getName();
    private static final String FILENAME = "myFiles.txt";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);


        String textFromFileString =  "";

        try{
            textFromFileString=readFromFile();
            if(textFromFileString.length()<1){
                String passDefault = "admin#admin#";
                writeToFile(passDefault);
            }

        }catch(Exception ee){}


        edUser=(EditText)findViewById(R.id.editText);
        edPass=(EditText)findViewById(R.id.editText2);

        Button btnLogin=(Button)findViewById(R.id.button);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                String user=edUser.getText().toString();
                String pass=edPass.getText().toString();
                if(user.length()<1){
                    lengkapi("User");
                }
                else if(pass.length()<1){
                    lengkapi("Pass");
                }
                else{
                    String textToSaveString=readFromFile();
                    String[]ar=textToSaveString.split("#");
                    if ( user.equalsIgnoreCase(ar[0]) && pass.equalsIgnoreCase(ar[1]) )
                        sukses();
                    else
                        gagal();
                }
            }});
    }

    private void writeToFile(String data) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(FILENAME, Context.MODE_PRIVATE));
            outputStreamWriter.write(data);
            outputStreamWriter.close();
        }
        catch (IOException e) {
            Log.e(TAG, "File write failed: " + e.toString());
        }
    }

    private String readFromFile() {
        String ret = "";
        try {
            InputStream inputStream = openFileInput(FILENAME);
            if ( inputStream != null ) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ( (receiveString = bufferedReader.readLine()) != null ) {
                    stringBuilder.append(receiveString);
                }
                inputStream.close();
                ret = stringBuilder.toString();
            }
        }
        catch (FileNotFoundException e) {
            Log.e(TAG, "File Tidak Ditemukan : " + e.toString());
        } catch (IOException e) {
            Log.e(TAG, "Tidak Dapat Membaca File: " + e.toString());
        }
        return ret;
    }
    public void keluar(){
        new AlertDialog.Builder(this)
                .setTitle("Menutup Aplikasi")
                .setMessage("Terimakasih... Anda Telah Menggunakan Aplikasi Ini")
                .setNeutralButton("Tutup", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {
                        finish();
                    }})
                .show();
    }

    public void sukses(){
        new AlertDialog.Builder(this)
                .setTitle("Sukses Masuk")
                .setMessage("Berhasil Masuk...")
                .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {
                        edPass.setText("");
                        edUser.setText("");
                        Intent i = new Intent(Menu_Login.this, Menu_Utama.class);
                        startActivity(i);
                    }})
                .show();
    }

    public void gagal(){
        new AlertDialog.Builder(this)
                .setTitle("Login Gagal")
                .setMessage("Maaf, Anda Gagal Tidak Bisa Masuk.. Silakan Cek Kembali")
                .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {

                    }})
                .show();
    }

    public void lengkapi(String u){
        new AlertDialog.Builder(this)
                .setTitle("Login Gagal")
                .setMessage("Maaf, Silakan Isi Data "+u+" Anda")
                .setNeutralButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int sumthin) {

                    }})
                .show();
    }

    public void keluarYN(){
        AlertDialog.Builder ad=new AlertDialog.Builder(Menu_Login.this);
        ad.setTitle("Konfirmasi");
        ad.setMessage("Apakah Benar Ingin Keluar?");
        ad.setPositiveButton("Yes",new OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }});

        ad.setNegativeButton("No",new OnClickListener(){
            public void onClick(DialogInterface arg0, int arg1) {
            }});
        ad.show();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            keluarYN();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}



 Intent io = this.getIntent();
        myLati=io.getStringExtra("myLati");
        myLongi=io.getStringExtra("myLongi");
        myPosisi=io.getStringExtra("myPosisi");


String message = "Text I want to share.";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);

startActivity(Intent.createChooser(share, "Title of the dialog the system will open"));
exact package name dari aplikasi
Facebook - "com.facebook.katana"
Twitter - "com.twitter.android"
Instagram - "com.instagram.android"
Pinterest - "com.pinterest"
====
Intent intent = context.getPackageManager().getLaunchIntentForPackage(application);
if (intent != null) {
     // The application exists
     Intent shareIntent = new Intent();
     shareIntent.setAction(Intent.ACTION_SEND);
     shareIntent.setPackage(application);

     shareIntent.putExtra(android.content.Intent.EXTRA_TITLE, title);
     shareIntent.putExtra(Intent.EXTRA_TEXT, description);
     // Start the specific social application
     context.startActivity(shareIntent);
} else {
    // The application does not exist
    // Open GooglePlay or use the default system picker
}

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is the text that will be shared.");
startActivity(Intent.createChooser(sharingIntent,"Share using"));
Sharing binary objects (Images, videos etc.)
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);

sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

http://stackoverflow.com/questions/6814268/android-share-on-facebook-twitter-mail-ecc






Minggu, 27 November 2016

Caesar Chipper






  1. package com.sanfoundry.setandstring;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class CaesarCipher
  6. {
  7.     public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
  8.  
  9.     public static String encrypt(String plainText, int shiftKey)
  10.     {
  11.         plainText = plainText.toLowerCase();
  12.         String cipherText = "";
  13.         for (int i = 0; i < plainText.length(); i++)
  14.         {
  15.             int charPosition = ALPHABET.indexOf(plainText.charAt(i));
  16.             int keyVal = (shiftKey + charPosition) % 26;
  17.             char replaceVal = ALPHABET.charAt(keyVal);
  18.             cipherText += replaceVal;
  19.         }
  20.         return cipherText;
  21.     }
  22.  
  23.     public static String decrypt(String cipherText, int shiftKey)
  24.     {
  25.         cipherText = cipherText.toLowerCase();
  26.         String plainText = "";
  27.         for (int i = 0; i < cipherText.length(); i++)
  28.         {
  29.             int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
  30.             int keyVal = (charPosition - shiftKey) % 26;
  31.             if (keyVal < 0)
  32.             {
  33.                 keyVal = ALPHABET.length() + keyVal;
  34.             }
  35.             char replaceVal = ALPHABET.charAt(keyVal);
  36.             plainText += replaceVal;
  37.         }
  38.         return plainText;
  39.     }
  40.  
  41.     public static void main(String[] args)
  42.     {
  43.         Scanner sc = new Scanner(System.in);
  44.         System.out.println("Enter the String for Encryption: ");
  45.         String message = new String();
  46.         message = sc.next();
  47.         System.out.println(encrypt(message, 3));
  48.         System.out.println(decrypt(encrypt(message, 3), 3));
  49.         sc.close();
  50.     }
  51. }

Senin, 12 Oktober 2015

Compressi ShannonFano Source Code Using Java







package lp2maray.com;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Vector;

public class ShannonFano{
   
   
public static void main(String[] args){
InputStream is, isDecompress;
OutputStream os, osDecompress;
String filename = "file3MB.txt";
               
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);

    String fileCom = s+"/doc/file3MB.txt";
    String fileDec = s+"/doc/dec.zsf";
    //file3MB.txt.zsf
   new ShannonFanoCompress(fileCom,null,true); //compress

}

    public ShannonFanoCompress(String filename,String destination,boolean verbose){           

                if(verbose)
                 System.out.println("compression started, source : "+filename);
            
                 HashMap<String,Integer> occurenceTable=new HashMap<String,Integer>();
                 int total=0;
             try{
                 if(verbose)
                 System.out.println("counting occurences...");
                 BufferedReader in=new BufferedReader(new FileReader(filename));                   
                 String s=null,c=null;
                 char tab[]=new char[1];
                 int i,lineCount=0;
                 while((s=in.readLine())!=null){
                         for(i=0;i<s.length();i++)
                          {tab[0]=s.charAt(i);
                           c=new String(tab);
                           if(occurenceTable.containsKey(c))
                               occurenceTable.put(c,new Integer(occurenceTable.get(c).intValue()+1));
                           else
                               occurenceTable.put(c,new Integer(1));
                          }
                      total+=s.length()+1;
                      //count each newline too
                      lineCount++;
                     }//while
                  in.close();
                  //put ("newline",...) in occurenceTable
                  occurenceTable.put("newline",new Integer(lineCount));
                  if(verbose){
                      System.out.println(lineCount+" line(s) in the file : "+filename);
                       System.out.println("occurence table");
                       for(Map.Entry<String,Integer> m:occurenceTable.entrySet())
                           System.out.println(m.getKey()+" "+m.getValue());
                      }
             }
             catch(IOException ioe){ioe.printStackTrace();
              return;
             }
            
             if(verbose)
                     System.out.println("computing frequency table...");
                    LinkedHashMap<String,Float> tmpfrequencyTable=new LinkedHashMap<String,Float>();  
             for(String tmp:occurenceTable.keySet())
             tmpfrequencyTable.put(tmp,new Float(((float)occurenceTable.get(tmp).intValue())/total));      
            
             Vector<Float> l=new Vector<Float>();
             l.addAll(tmpfrequencyTable.values());
             Collections.sort(l,Collections.reverseOrder());
             LinkedHashMap<String,Float> frequencyTable=new LinkedHashMap<String,Float>();
             for(Float value:l)
                 for(String key:tmpfrequencyTable.keySet())             
                     if(tmpfrequencyTable.get(key).equals(value))
                         {frequencyTable.put(key,value);
                          tmpfrequencyTable.remove(key);
                          break;
                         }
             if(verbose)
                 {System.out.println("frequency table");
                  for(Map.Entry<String,Float> m:frequencyTable.entrySet())
                      System.out.println(m.getKey()+" "+m.getValue());
                 }
             if(verbose)
                 System.out.println("computing code table...");
             LinkedHashMap<String,StringBuffer> codeTable=new LinkedHashMap<String,StringBuffer>();
             for(String tmp:frequencyTable.keySet())
                 codeTable.put(tmp,new StringBuffer(""));              
             updateTables(frequencyTable,codeTable);   
             if(verbose)
                 {System.out.println("code table");
                  for(Map.Entry<String,StringBuffer> m:codeTable.entrySet())
                      System.out.println(m.getKey()+" "+m.getValue());
                 }
            
            
            
             File f;
             if(destination==null)
                 f=new File(filename+".zsf");
             else
                 f=new File(destination);
             if(verbose)
                 System.out.println("destination file : "+f.getName());     
             try {
                 if(verbose)
                 System.out.println("computing bit set from source file by using code table (main compression step)...");
                  BufferedReader in=new BufferedReader(new FileReader(filename));
                  String s=null,c=null;
                  char tab[]=new char[1];
                  int i=0,j=0,k=0;               
                  BitSet content=new BitSet();           
                  String value=null,newlineValue=new String(codeTable.get("newline"));
                  while((s=in.readLine())!=null)
                      {for(i=0;i<s.length();i++)
                          {tab[0]=s.charAt(i);
                           c=new String(tab);
                           value=new String(codeTable.get(c));
                           for(j=0;j<value.length();j++,k++)
                               if(value.charAt(j)=='1')
                                   content.set(k,true);
                          }
                       for(j=0;j<newlineValue.length();j++,k++)
                           if(newlineValue.charAt(j)=='1')
                               content.set(k,true);                   
                      }
                  content.set(k,true);
                  in.close();            
                  if(f.createNewFile() && verbose)
                      System.out.println("file "+f.getName()+" created");
                 
                 
                  if(verbose)
                      System.out.println("writing code table...");
                  PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(f)));
                  out.println(codeTable.size());
                  for(Map.Entry<String,StringBuffer> m:codeTable.entrySet())
                      out.println(m.getKey()+" "+m.getValue());          
                  byte[] byteContent=convertBitSetInBytes(content);
                  if(verbose)
                      System.out.println("writing size of compressed content : "+byteContent.length+" bytes");
                  out.println(byteContent.length);
                  out.close();
                  if(verbose)
                      System.out.println("writing compressed content...");
                  BufferedOutputStream out2=new BufferedOutputStream(new FileOutputStream(f,true));
                  out2.write(byteContent);               
                  out2.close();
                  if(verbose)
                      System.out.println("compression successful");
                 }
             catch(IOException ioe)
             {ioe.printStackTrace();
              return;
             }
        
    }
   
    private static void updateTables(LinkedHashMap<String,Float> frequencyTablePart,
                                     LinkedHashMap<String,StringBuffer> codeTablePart){
        float leftSum=0,rightSum=0;
        int limit=0;
        for(Float val:frequencyTablePart.values())
            rightSum+=val.floatValue();
        for(Float x:frequencyTablePart.values())
            {leftSum+=x;
             rightSum-=x;
             limit++;
             if(leftSum>=rightSum)
                 break;     
            }
        int j=0;
        for(Map.Entry<String,StringBuffer> m:codeTablePart.entrySet())
            {if(j<limit)
                 codeTablePart.put(m.getKey(),m.getValue().append("0"));
             else
                 codeTablePart.put(m.getKey(),m.getValue().append("1"));
             j++;
            }  
        LinkedHashMap<String,Float> nextFrequencyTablePart;
        LinkedHashMap<String,StringBuffer> nextCodeTablePart;
        Iterator<String> frequencyKeySetIterator;
        Iterator<Float> frequencyValuesIterator;
        Iterator<String> codeKeySetIterator;
        Iterator<StringBuffer> codeValuesIterator;
        if(limit>1)
            {frequencyKeySetIterator=frequencyTablePart.keySet().iterator();
             frequencyValuesIterator=frequencyTablePart.values().iterator();
             codeKeySetIterator=codeTablePart.keySet().iterator();
             codeValuesIterator=codeTablePart.values().iterator();
             nextFrequencyTablePart=new LinkedHashMap<String,Float>();      
             for(int i=0;i<limit;i++)
                 nextFrequencyTablePart.put(frequencyKeySetIterator.next(),frequencyValuesIterator.next());
             nextCodeTablePart=new LinkedHashMap<String,StringBuffer>();
             for(int i=0;i<limit;i++)
                 nextCodeTablePart.put(codeKeySetIterator.next(),codeValuesIterator.next());
             updateTables(nextFrequencyTablePart,nextCodeTablePart);
            }
        if(limit<codeTablePart.size()-1)
            {frequencyKeySetIterator=frequencyTablePart.keySet().iterator();
             frequencyValuesIterator=frequencyTablePart.values().iterator();
             codeKeySetIterator=codeTablePart.keySet().iterator();
             codeValuesIterator=codeTablePart.values().iterator();
             for(int i=0;i<limit;i++)
                 {frequencyKeySetIterator.next();
                  frequencyValuesIterator.next();
                  codeKeySetIterator.next();
                  codeValuesIterator.next();
                 }
             nextFrequencyTablePart=new LinkedHashMap<String,Float>();      
             while(frequencyKeySetIterator.hasNext())
                 nextFrequencyTablePart.put(frequencyKeySetIterator.next(),frequencyValuesIterator.next());           
             nextCodeTablePart=new LinkedHashMap<String,StringBuffer>();
             while(codeKeySetIterator.hasNext())
                 nextCodeTablePart.put(codeKeySetIterator.next(),codeValuesIterator.next());                
             updateTables(nextFrequencyTablePart,nextCodeTablePart);
            }
    }
   
    public static byte[] convertBitSetInBytes(BitSet bitSet){
        byte[] byteContent=new byte[(int)Math.ceil(bitSet.length()/8.0f)];     
        int i;
        for(i=0;i<byteContent.length;i++)
            byteContent[i]=(byte)0x0000;
        for(i=0;i<bitSet.size();i++)
            if(bitSet.get(i))
                byteContent[i/8]|=1<<(7-(i%8));
        return(byteContent);
    }
   
    public static BitSet convertBytesInBitSet(byte[] array){       
        BitSet bitset=new BitSet();
        int j;
        byte[] mask={(byte)0x01,(byte)0x02,(byte)0x04,(byte)0x08,(byte)0x10,(byte)0x20,(byte)0x40,(byte)0x80};
        for(int i=0;i<array.length;i++)
            for(j=0;j<8;j++)
                if((array[i] & mask[j])!=0)
                    bitset.set(i*8+(7-j),true);                            
        return(bitset);
    }
   
    public static String toBitString(BitSet bitset,int length){
        String s=new String("");
        for(int i=0;i<length;i++)
            if(bitset.get(i))
                s+="1";
            else
                s+="0";
        return(s);
    }         
   
  
}
HasilCompressi: