Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

How to get date time and device id from BlackBerry device programatically Java

These are very basic things in mobile development. but its very useful to keep them documented.First we will see how to get date time
public static String  getCurrentDateTime()
    {
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aaa");
    return dateFormat.format(new Date(System.currentTimeMillis()));

    }

Then we will see how to get device id from device 
net.rim.device.api.system.DeviceInfo.getDeviceId()

How to encrypt and decrypt data using Advanced Encryption Standard(AES) Java BlackBerry Pragramming

sample code provides information on how to encrypt and decrypt data using the most common symmetric key algorithm, Advanced Encryption Standard


package com.DataStore;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javacard.security.CryptoException;
import net.rim.device.api.crypto.AESDecryptorEngine;
import net.rim.device.api.crypto.AESEncryptorEngine;
import net.rim.device.api.crypto.AESKey;
import net.rim.device.api.crypto.BlockDecryptor;
import net.rim.device.api.crypto.BlockEncryptor;
import net.rim.device.api.crypto.CryptoTokenException;
import net.rim.device.api.crypto.CryptoUnsupportedOperationException;
import net.rim.device.api.crypto.PKCS5FormatterEngine;
import net.rim.device.api.crypto.PKCS5UnformatterEngine;
import net.rim.device.api.crypto.RandomSource;
import net.rim.device.api.crypto.SHA1Digest;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.util.Arrays;
import net.rim.device.api.util.DataBuffer;

public class CryptoRSA {

    private String keyMessage = "Data sent between a BlackBerry device and the BlackBerry Enterprise Server is encrypted using Triple DES (Date Encryption Standard) or AES (Advanced Encrption Standard). This is performed automatically and does not require application implementation to use it.There are cases where encrypting data can be required, such as secure communication with an external application using the BlackBerry Mobile Data Server. Communication between the BlackBerry and BlackBerry Mobile Data Server would be automatically encrypted but communication between the BlackBerry Mobile Data Server and an application server would not unless implemented in the BlackBerry application.";

    public byte[] encrypt(byte[] data ) throws CryptoException, IOException, CryptoTokenException, CryptoUnsupportedOperationException
    {
    AESKey key = new AESKey( keyMessage.getBytes() );
    // Now, we want to encrypt the data.
    // First, create the encryptor engine that we use for the actual
    AESEncryptorEngine engine = new AESEncryptorEngine( key );

    // Since we cannot guarantee that the data will be of an equal block
    // length we want to use a padding engine (PKCS5 in this case).
    PKCS5FormatterEngine fengine = new PKCS5FormatterEngine( engine );

    // Create a BlockEncryptor to hide the engine details away.
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    BlockEncryptor encryptor = new BlockEncryptor( fengine, output );

    // Now we need to do is write our data to the output stream.
    // But before doing so, let's calculate a hash on the data as well.
    // A digest provides a one way hash function to map a large amount
    // of data to a unique 20 byte value (in the case of SHA1).
    SHA1Digest digest = new SHA1Digest();
    digest.update( data );
    byte[] hash = digest.getDigest();
    // Now, write out all of the data and the hash to ensure that the
    // data was not modified in transit.
    encryptor.write( data );
    encryptor.write( hash );
    encryptor.close();
    output.close();

    // Now, the encrypted data is sitting in the ByteArrayOutputStream.
    // We simply want to retrieve it.
    return output.toByteArray();
    }

    public byte[] decrypt(byte[] ciphertext ) throws CryptoException, IOException, CryptoTokenException, CryptoUnsupportedOperationException
    {
    // First, create the AESKey again.
    AESKey key = new AESKey( keyMessage.getBytes() );

    // Now, create the decryptor engine.
    AESDecryptorEngine engine = new AESDecryptorEngine( key );
    // Since we cannot guarantee that the data will be of an equal block length
    // we want to use a padding engine (PKCS5 in this case).
    PKCS5UnformatterEngine uengine = new PKCS5UnformatterEngine( engine );

    // Create the BlockDecryptor to hide the decryption details away.
    ByteArrayInputStream input = new ByteArrayInputStream( ciphertext );
    BlockDecryptor decryptor = new BlockDecryptor( uengine, input );

    // Now, read in the data. Remember that the last bytes represent
    // the SHA1 hash of the decrypted data.
    byte[] temp = new byte[ 100 ];
    DataBuffer buffer = new DataBuffer();

    for( ;; ) {
        int bytesRead = decryptor.read( temp );
        buffer.write( temp, 0, bytesRead );

        if( bytesRead < 100 ) {
        // We ran out of data.
        break;
        }
    }

    byte[] plaintextAndHash = buffer.getArray();
    int plaintextLength = plaintextAndHash.length - SHA1Digest.DIGEST_LENGTH;
    byte[] plaintext = new byte[ plaintextLength ];

    System.arraycopy( plaintextAndHash, 0, plaintext, 0, plaintextLength );
   
    return plaintext;
    }
}

How to use PersistentStore to store objects in BlackBerry Java programming

Here in this post we will see how to store customer data using PersistentStore.
In my DataObject class used to store customer data. it has 2 parameters customer ID and some string property it may be name address or any other parameter. Also you can change those parameters according to your requirements. we are suing vector to store those pairs in runtime. Hope this will useful for you
============================================
package com.DataStore;

import java.util.Vector;
import net.rim.device.api.util.Persistable;

public final class DataObject implements Persistable
{

    private Vector elements;
    public static final int CLIENT_ID = 0;

    public DataObject()
    {
    elements = new Vector(1);
    int capacity = elements.capacity();
    for (int i = 0; i < capacity; ++i)
    {
        elements.addElement(new String(""));
    }
    }

    /**
     * @param id
     * @return String
     * String getElement(int id)
     */
    public String getElement(int id)
    {
    return (String) elements.elementAt(id);
    }

    public void setElement(int id, String value)
    {
    elements.setElementAt(value, id);
    }
}

==============================================
package com.DataStore;

import java.util.Vector;

import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
public class DataHandler {

    private static Vector data;
    private static PersistentObject store;

    static
    {
    store =    PersistentStore.getPersistentObject(1);

    synchronized (store) {
        if (store.getContents() == null) {
        store.setContents(new Vector());
        store.commit();
        }
    }

    data = (Vector) store.getContents();

    }

    /**
     * @param info
     * static void saveObject(DataObject info)
     */
    public static void saveObject(DataObject info)
    {
    data.addElement(info);
    synchronized (store) {
        store.setContents(data);
        store.commit();
    }
    }

    /**
     * @return String
     * static String getClient()
     */
    public static String getClient() {

    synchronized (store) {
        data = (Vector) store.getContents();
        if (!data.isEmpty()) {
        DataObject info = (DataObject) data.lastElement();
        return info.getElement(DataObject.CLIENT_ID);
        }
        else
        {
        //If data is empty here we return empty string
        return "";
        }
    }
    }
}

How to detect transparent pixel in java and how change transparent pixels

In images we represent each pixel represent by 32 bits.Bit assignment is doing as follows. Normally in Buffered images if we used type TYPE_INT_ARGB we do this way.See the image shown below.

 

So you can see if we need to detect alpha part we have to consider bits 31 to 24 so we need to shift right side by 24 bits then color related bits will go out. Then we will have only Alpha bits at location 7 to 0 then we will do and operation with 0xFF (that means 11111111) so we will get only 0 to 7 bits.
Same way you can use to detect red ,blue and green components by shifting 0,8,16.

Next we will see how we can do this by programme using java language.Here below you can see how to load gif transparent image and how to store it after modification to transparent pixels.
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class test {
    public static void main() {
        // Get Image
        ImageIcon icon = new ImageIcon("/home/sanjeewa/Desktop/xparent.gif");
        Image image = icon.getImage();
        // Create empty BufferedImage, sized to Image
        BufferedImage buffImage =
                new BufferedImage(
                        image.getWidth(null),
                        image.getHeight(null),
                        BufferedImage.TYPE_INT_ARGB);
        Graphics g = buffImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        //Dispose the Graphics
        g.dispose();
        //Here 2 for loops used for iterate through each and every pixel in image
        for (int i = 0; i < buffImage.getWidth(); i++) {
            for (int j = 0; j < buffImage.getHeight(); j++) {
                //signed bit shift right
                /*
                How to extract different color components
                blue = pix & 0xFF;
                green = (pix>>8) & 0xFF;
                red = (pix>>16) & 0xFF;
                alpha = (pix>>24) & 0xFF;
                 */
                int alpha = (buffImage.getRGB(i, j) >> 24) & 0xff;
                if (alpha == 0) {
                   //Now we will have pixel with Alpha 0 (Transparent pixel)
                   //As example If you need to fill transparent pixels with white color
                   //use this code 
                   //buffImage.setRGB(i, j, Color.white.getRGB());
                   buffImage.setRGB(i, j, 0);
                } else {

                }
            }
        }
        try {
             //Write back modified file to file system
            String file_name = "/home/sanjeewa/Desktop/sss.png";
            File file = new File(file_name);
            ImageIO.write(buffImage, "png", file);
        } catch (Exception e) {
        }
    }
}

How to generate Axiom OMElement Using input Stream

The method showed below is generate   Axiom OMElement  from input stream
  
   /**
     * @param inputStream Reads input stream that use to build OMElement
     * @return  OMElement that generated from input stream
     * @throws Exception at error in generating parser
     */
    public static OMElement buildOMElement(InputStream inputStream) throws Exception {
        XMLStreamReader parser;
        try {
            parser = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        }
        catch (XMLStreamException e) {
            String msg = "Error in initializing the parser to build the OMElement.";
            log.error(msg, e);
            throw new Exception(msg, e);
        }
        finally {
           log.info("Reading data from configuration file");
        }
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        return builder.getDocumentElement();
    }


we can call this method as follows

OMElement  element=buildOMElement(new FileInputStream("File path String"));

If you need more information go to this link

How to read user input at command line -Java


    public String readUserInput(String printMessage) throws IOException{
        System.out.println(printMessage);
        InputStreamReader isr = new InputStreamReader ( System.in );
        BufferedReader br = new BufferedReader (isr);
        String returnString;
        try {
            returnString=br.readLine();
        } catch (IOException e) {
           String message="error while reading user input";
           log.error(message,e);
           throw new IOException(e);
        }
        finally {
            br.close();
            isr.close()
        }
        return returnString;
    }

Get Present Working Directory in Java Code

Most of projects we don't use absolute path instead we use relative path thats best practice. in this discussion we will see how to get string name of current working folder so after that we can get relative path corresponding to that base location . so simple just few lines :)
   public static String getCurrentDirectory(){
        String cwd = null;
        try{
            cwd = new java.io.File( "." ).getCanonicalPath();

        } catch (java.io.IOException e)
        {
            log.error("Error in getting present working Directory");
        }
        return cwd;
    }

How to use regular Expressins in String manipulation

Regular expressions are power full and efficient. i used them recently for my project and here i will just show few usages of it

Its so simple

Pattern p = Pattern.compile(regexPatternString);
Matcher m = p.matcher(textString);

then evaluate using
if(m.matches()){
 //write what ever if that match you want to do

//pattern to get character contains only 1 to 3(1,2,3) and letter c( C and c)
Pattern p = Pattern.compile("[.1-3cC]");

//only Numerical values string that contains only digits and any number of digits
Pattern p = Pattern.compile(("[0-9].*")

//get string that only contains "sanjeewa" or "malalgoda"
Pattern p = Pattern.compile(("sanjeewa|malalgoda")

How to extract element of XML file using apache axiom which is mainly use in WSO2 products

In our projects we need to extract elements from xml files. later i was use some other jar that allows xml manipulation. but when started working with WSO2 i have to use axiom.Now I'm comfortable with it and decide to put this post about it

<packages xmlns="http:tempuri.org/">
    <package name="free">
        <users>
            <limit>5</limit>
            <charge>0</charge>
        </users>
        <resourceVolume>
            <limit>10</limit>
        </resourceVolume>
        <bandwidth>
            <limit>1000</limit>
            <overuseCharge>0</overuseCharge>
        </bandwidth>
    </package>
    <package name="small">
        <users>
            <limit>10</limit>
            <charge>10</charge>
        </users>
        <resourceVolume>
            <limit>25</limit>
        </resourceVolume>
        <bandwidth>
            <limit>2000</limit>
            <overuseCharge>0.1</overuseCharge>
        </bandwidth>
        <userLimit>10</userLimit>
    </package>
</packages>

just assume that we have XML in above format.its about packages of service provider.so we may need to get packages objects and extract the

name of each package
users limit
resourceVolume limit
bandwidth limit

So we will see how to extract those elements.in my code first while loop iterates through the objects and second while loop iterates through the elements of each object.

String configFileName = "path_to_file/file_name.xml";
if (new java.io.File(configFileName).exists())
{
    //if file exsists then only proceeds
    try
    {
    //create OMElement from the file given
    org.apache.axiom.om.OMElement userConfigRoot =
    org.wso2.stratos.common.util.CommonUtil.buildOMElement(new java.io.FileInputStream(configFileName));
    //iterates through the elements of the file in this case we will go through package elements
    java.util.Iterator userConfigChildIt = userConfigRoot.getChildElements();
       while (userConfigChildIt.hasNext())
    //this reads through all elements in the file till end
       {
          Object userConfigChild = userConfigChildIt.next();
    //get element of package         
        if (!(userConfigChild instanceof OMElement))
               {
        //if that is not OMElement we will skip
              continue;
               }
       OMElement meteringConfigChildEle = (OMElement) userConfigChild;
       String parameterValue=
       meteringConfigChildEle.getAttributeValue(new javax.xml.namespace.QName(null, "name"));
    //get the variable name by parameter name in this case we will extract name parameter of the
    //package object.we can use string value of given parameter name
       Iterator userParametersChildIt = meteringConfigChildEle.getChildElements();
       //again iterates through the sub elements of the package object
              while (userParametersChildIt.hasNext())
              {
             param_number=param_number+1;
             Object userParameterChild = userParametersChildIt.next();
                 if (!(userParameterChild instanceof OMElement))
        {
                    continue;
                }
              OMElement userParameterChildEle = (OMElement) userParameterChild;
             if(userParameterChildEle.getFirstElement()!=null)
        {
         //in this we will get the elements of the object
                 String temp= userParameterChildEle.getFirstElement().getText();
                }
           }
        }

MULTI THREADED WEB SERVER IN JAVA SOURCE CODE(LODE PAGES FROM GIVEN FOLDER LOCATION AND PUBLISH THEM)

//  THIS IS THE  HTTPREQUEST CLASS TO HANDLES REQUEST FROM THE USER

import java.io.*;
import java.net.*;
import java.util.regex.*;
import java.util.*;

final class HttpRequest implements Runnable
    {
        private static final Pattern REQUEST_PATTERN = Pattern.compile("^GET (/.*) HTTP/1.[01]$");
        private final File documentDir;
        private final Socket socket;
    //------------------------------------------------------------
    //CONSTRUCTOR METHOD OF HttpRequest TWO ARGUMENTS
    // socket and documentDir FOR NEW REQUEST
        public HttpRequest(Socket socket, File documentDir)
        {
        this.socket = socket;
        this.documentDir = documentDir;
        }
    //---------------------------------------------------------------------------
    //METHOD TO REQUEST THE PATH FROM BROWSER
        private String readRequestPath() throws IOException
        {    //READ THE REQUEST
            BufferedReader reader = new BufferedReader(new InputStreamReader(
            this.socket.getInputStream()));
            String firstLine = reader.readLine();
            if (firstLine == null)
                {
                return null;
                }
        //COMPILE THE CODE
        //THIS PART OF CODE TAKEN FROM INTERNET (SUN JAVA).INSTEAD OF THIS WE CAN USE SRTING
        //TOKENIZER ALSO BUT THAT SPENTS LOT OF CODE
        Matcher matcher = REQUEST_PATTERN.matcher(firstLine);
        return matcher.matches() ? matcher.group(1) : null;
        }
    //-------------------------------------------------------------------------------------
    //THIS METHOD USED FOR SEND RESPONSE
    //IN THIS CASE I USED STRING BUFFER AND APPEND NECESSERY PARTS OF IT
        private OutputStream sendResponseHeaders(int status, String message,long len) throws IOException
        {
        StringBuffer response = new StringBuffer();
        response.append("HTTP/1.0 ");
        response.append(status).append(' ').append(message).append("\r\n");
        response.append("Content-Length: ").append(len).append("\r\n\r\n");
        OutputStream out = this.socket.getOutputStream();
        //SEND response TO THE OUT PUT STREAM OF CURRENT SOCKET
        //WHEN WE NEED TO PRINT THE MESSAGE ON WEB BROESER WE CAN USE THIS
        out.write(response.toString().getBytes());
        out.flush();
        return out;
        }
    //--------------------------------------------------------------------------------
    //THIS METHOD USED TO SEND ERROR MESSAGE TO THE BROWSER WHEN WE GIVE ERROR
    //NUMBER AND MESSAGE THAT WILL PRIN USING ABOVE METHOD (sendResponseHeaders)
       private int sendErrorResponse(int status, String message) throws IOException
        {
        OutputStream out = sendResponseHeaders(status, message,message.length());
        out.write((message+"\nerror number :"+status).getBytes());
        out.flush();
        return status;
        }
    //------------------------------------------------------------------------------
    //THIS METHOD IS USED FOR READ FILE IN THE DOCUMENT DIRECTORY AND SEND THE CONTENT
    // OF THE FILE TO THE SOCKET.THEN WEB BROWSER CAN ACCES THEM VIA PORT
    // OF THE FILE TO THE SOCKET.THEN WEB BROWSER CAN ACCES THEM VIA PORT
        private long sendFile(File file) throws IOException
        {
        long len = file.length();
        OutputStream out = sendResponseHeaders(200, "OK", len);
        InputStream in = new FileInputStream(file);
        try {
            byte[] buffer = new byte[1024];
            int nread = 0;
            while ((nread = in.read(buffer)) > 0)
                {
                out.write(buffer, 0, nread);
                }
            }
        finally
            {
                in.close();
            }
        out.flush();
        return len;
        }
    //----------------------------------------------------------------------------
    //THIS IS THE MAIN ENTRY TO THIS HttpRequest
        public void run()
        {
        //IN THIS PART INITIALIZE LOGIN INFOMATION
        int status = 200;
        long len = 0;
        String path = null;
        //TRY TO HANDLE THE REQUEST
        try {
            path = readRequestPath();
            //THIS IS FOR BONUS MARK ,IF PATH CONTAINSONLY"/"
            //THAT TAKES AS index.html FILE BELOW IF LOOP CHECK THAT
            //THIS ALSO DISPLAYS THE CURRENTLY SHOWING FILE NAME AT COMMAND LINE
                if(path.equals("/"))
                {
                    path=path+"index.html";
                    System.out.println("RETTEIVING FILE IS "+this.documentDir.getAbsolutePath()+path);
                }
                //IF PATH NOT AVAILABLE SEND ERROR MESSAGE TO THE BROWSER
                if (path == null)
                {
                    status = sendErrorResponse(400, "Bad Request");
                }
                //IF HAS SOME PATH TRY TO ACCCESS GIVEN PATH
                else
                {
                    File file = new File(this.documentDir, path);
                    //CHECK GIVEN FILE IS AVAILABLE IN THE GIVEN DOCUMENT AND CHECK WETHER IT CAN READ  OR NOT
                    //ONLY FOR READABLE FILES IN THE CORRECT PATH GIVEN
                        if (!file.getAbsolutePath().startsWith(this.documentDir.getAbsolutePath())|| (file.exists() && (!file.isFile() || !file.canRead())))
                        {
                        status = sendErrorResponse(403, "Forbidden");
                        }
                        //IF FILE DOES NOT FOUN SEN MESSAGE TO AWARE THATS NOT AVAILABLE
                        else if (!file.exists())
                        {
                        status = sendErrorResponse(404, "Not Found");
                        }
                        //IF NO ANY ISSUE SEND THE FILE
                        else
                        {
                        len = sendFile(file);
                        }
                }
            }
            //ERROR HANDLING PART
            catch (IOException e)
                {
                System.out.println("Error while serving request for " + e.getMessage());
                e.printStackTrace();
                }
            finally
                {
                    try
                        {
                        this.socket.close();
                        }
                    catch (IOException e)
                        {
                            System.out.println("Error while closing socket to " + e.getMessage());
                        }
                }
        }
    }
//================================




//    THIS IS THE  WEB SERVER CLASS TO ACCEPT AND PARSE THE REQUEST
//**************************************************

import java.io.*;
import java.net.*;
import java.util.*;

public class WebServer
    {
    public static void main(String[] args)
        {
         int port = 8080;
        //SET THE PORT NUMBER
         File documentDir = new File("localhost");
        //NAME OF THE DOCUMENT DIRECTORY
        //IF DOCUMENT DIRECTORY DOES NOT CONTAIN OR ITS NOT DIRECTORY PRINT ERR MESSAGE
        if (!documentDir.exists()&&!documentDir.isDirectory())
        {
            System.out.println("No such directory exists make directory named ["
            + documentDir.getAbsolutePath()+ " ] localhost and put files");
        }
        //ELSE RUN THE SERVER
    else
        {
            System.out.println("web server is running");
        try {
            //STABILISH A NEW SOCKET TO START CONNECTION
            ServerSocket serverSocket = new ServerSocket(port);
            try {
                //INFINITE LOOP TO PROCESS REQUESTS
                while (true)
                    {
                    // wait for the next client to connect and get its socket connection
                    Socket socket = serverSocket.accept();
                    // handle the socket connection by a handler in a new thread
                    new Thread(new HttpRequest(socket, documentDir)).start();
                    }
                }
                //IF ERROR OCCURED WHEN CONNECT TO PORT
                catch (IOException e)
                    {
                    System.err.println("Error while accepting connection on port "+ port);
                    }
                    finally
                    {
                        serverSocket.close();
                    }
            }
            //IF ERROR OCCURED WHEN BIND TO THE PORT
            catch (IOException e)
            {
            System.err.println("Failed to bind to port " + port);
            }
        }
    }
}
//==============end of the class==

Post method in java

public String postObject(String url,String object)
       {

          String resultsPage="";
         try{
              String urlStr=url;
              String val=object;
              URL postURL = new URL( urlStr );
              HttpURLConnection con = (HttpURLConnection) postURL.openConnection();
              con.setUseCaches(false);      
              con.setDoOutput(true);        
              con.setDoInput(true);         
              con.setRequestMethod("POST");  
              PrintWriter out = new PrintWriter(con.getOutputStream());
              String postStr = "link="+URLEncoder.encode(val);
              out.println(postStr); 
              out.close();
              String inputLine="";
        BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
              while ((inputLine = in.readLine()) != null)
                   resultsPage+=inputLine;
              in.close();
              System.out.println(resultsPage); //Final output
          }
         catch(Exception ex)
          {
             System.out.println(ex);
          }

      return resultsPage;
       }

Add APN to http request automatically for BlackBerry device

Add this to the url As follows
you can add this part to url
URL+";trustAll;deviceside=true;apn=APN"

ex: get APN from mobile service provider
and add to above code

Empowering the Future of API Management: Unveiling the Journey of WSO2 API Platform for Kubernetes (APK) Project and the Anticipated Alpha Release

  Introduction In the ever-evolving realm of API management, our journey embarked on the APK project eight months ago, and now, with great a...