C implementation of AES Algorithm on Nios2 Soft Processor

A Field Programmable Gate Array (FPGA) is a re-programmable logic device used as
a re-programmable alternative to ASIC chip devices. FPGAs can be used for specific
operational behavior, or general purpose CPU functionality depending on the complexity
of the device.

Alteras NiosII is a soft processor, dened in a hardware description language, which can
be implemented in Alteras FPGA devices by using the Quartus RII CAD system. To
implement a useful system it is necessary to add other funcional units such as memories,
input/output interfaces, timers, and communications interfaces. To facilitate the
implementation of such systems, it is useful to have computer-aided-design (CAD)
software for implementing a system-on-a-programmable-chip (SOPC). Alteras SOPC
Builder is the software needed for this task.

image

                                      Nios 2 processor archtecture

First download nios2 soft processor into Altera de2 board by using byte blaster or some interfacing software.Then open nios2 eclipse software and start new project in c++.don't forget to point the instance of your soft processor instance then it will creates project corresponded to your processor. then copy the below code.build it and run as nios 2 software.then it will encrypt your input text into cipher text with given key size and key.

image

               Eclipse ide when running program.output results will show in nios2 terminal

==================================Code============================================

#include <stdio.h>
#include <alt_types.h>
#include <io.h>
#include <system.h>
#include <string.h>
#include <time.h>
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf( "%6.3f seconds used by the processor.", ((double)stopm-startm)/CLOCKS_PER_SEC);
// The number of columns comprising a state in AES. This is a constant in AES. Value=4
#define Nb 4
// The number of rounds in AES Cipher. It is simply initiated to zero. The actual value is recieved in the program.
int Nr=0;
// The number of 32 bit words in the key. It is simply initiated to zero. The actual value is recieved in the program.
int Nk=0;
unsigned char in[16], out[16], state[4][4];
unsigned char RoundKey[240];
unsigned char Key[32];

#define MenuCase(letter,proc) case letter:proc; break;

#ifdef DMA_NAME
static volatile int rx_done = 0;
#endif /* DMA_NAME */

static void MenuHeader(void)
{
  printf("\n\n");
  printf("             <---->   Aes Test Programm.   <---->\n");
  printf("This software example tests the execution time of aes algorithm\n");
  printf("Enter operation.\n");
}

static void MenuBegin( char *title )
{
  printf("\n\n");
  printf("----------------------------------\n");
  printf("%s\n",title);
  printf("----------------------------------\n");
}

static void MenuItem( char letter, char *name )
{
  printf("     %c:  %s\n" ,letter, name);
}

void GetInputString( char* entry, int size, FILE * stream )
{
  int i;
  int ch = 0;

  for(i = 0; (ch != '\n') && (i < size); )
  {
    if( (ch = getc(stream)) != '\r')
    {
      entry[i] = ch;
      i++;
    }
  }
}

static int MenuEnd( char lowLetter, char highLetter )
{
  static char entry[4];
  static char ch;

  printf("     q:  Exit\n");
  printf("----------------------------------\n");
  printf("\nSelect Choice (%c-%c): [Followed by <enter>]",lowLetter,highLetter);

  GetInputString( entry, sizeof(entry), stdin );
  if(sscanf(entry, "%c\n", &ch))
  {
    if( ch >= 'A' && ch <= 'Z' )
      ch += 'a' - 'A';
    if( ch == 27 )
      ch = 'q';
  }
  return ch;
}

static int TopMenu( void )
{
  char ch;

  /* Print the top-level menu to stdout */
  while (1)
  {
    MenuBegin("     AES Main Menu    ");
    MenuItem( 'a', "Test AES" );
    MenuItem( 'b', "Test Rsa");
#ifdef EPCS_CONTROLLER_NAME
    MenuItem( 'c', "Test EPCS Serial Flash");
    ch = MenuEnd( 'a', 'c' );
#else
    ch = MenuEnd( 'a', 'b' );
#endif /* EPCS_CONTROLLER_NAME */

    switch(ch)
    {
      MenuCase('a',TestRam());
      //MenuCase('b',TestFlash(TEST, CFI));
#ifdef EPCS_CONTROLLER_NAME
#endif
      case 'q':    break;
      default:    printf("\n -ERROR: %c is an invalid entry.  Please try again\n", ch); break;
    }
    if (ch == 'q')
      break;
    printf("\nPress enter to continue...\n");
    while( (( ch = getc(stdin)) != '\n' ) && ( ch != EOF ));

  }
  return (ch);
}

static int TestRam()
{
    printf("AES Running..........\n");

    START;
    int i=0;
        for(i=0;i<1000;i++)
        {
            runAes();
        }
    STOP;
    PRINTTIME;

    printf("elaaaaaa");
}

int main(void)
{

  int ch;

  /* Print the Header */
  MenuHeader();
  /* Print the menu and do what the user requests, until they hit 'q' */
  while (1)
  {
    ch = TopMenu();
    if (ch == 'q')
    {
      printf( "\nExiting from Memory Test.\n");
      break;
    }
  }
  return (0);
}

int getSBoxValue(int num)
{
    int sbox[256] =   {
    //0     1    2      3     4    5     6     7      8    9     A      B    C     D     E     F
    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0
    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1
    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2
    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3
    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4
    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5
    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6
    0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7
    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8
    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9
    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //A
    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //B
    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //C
    0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //D
    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //E
    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; //F
    return sbox[num];
}

// The round constant word array, Rcon[i], contains the values given by
// x to th e power (i-1) being powers of x (x is denoted as {02}) in the field GF(28)
// Note that i starts at 1, not 0).
int Rcon[255] = {
    0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
    0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
    0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
    0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
    0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,
    0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
    0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,
    0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
    0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
    0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,
    0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
    0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
    0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
    0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,
    0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
    0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb  };

// This function produces Nb(Nr+1) round keys. The round keys are used in each round to encrypt the states.
void KeyExpansion()
{
    int i,j;
    unsigned char temp[4],k;

    // The first round key is the key itself.
    for(i=0;i<Nk;i++)
    {
        RoundKey[i*4]=Key[i*4];
        RoundKey[i*4+1]=Key[i*4+1];
        RoundKey[i*4+2]=Key[i*4+2];
        RoundKey[i*4+3]=Key[i*4+3];
    }

    // All other round keys are found from the previous round keys.
    while (i < (Nb * (Nr+1)))
    {
                    for(j=0;j<4;j++)
                    {
                        temp[j]=RoundKey[(i-1) * 4 + j];
                    }
                    if (i % Nk == 0)
                    {
                        // This function rotates the 4 bytes in a word to the left once.
                        // [a0,a1,a2,a3] becomes [a1,a2,a3,a0]

                        // Function RotWord()
                        {
                            k = temp[0];
                            temp[0] = temp[1];
                            temp[1] = temp[2];
                            temp[2] = temp[3];
                            temp[3] = k;
                        }

                        // SubWord() is a function that takes a four-byte input word and
                        // applies the S-box to each of the four bytes to produce an output word.

                        // Function Subword()
                        {
                            temp[0]=getSBoxValue(temp[0]);
                            temp[1]=getSBoxValue(temp[1]);
                            temp[2]=getSBoxValue(temp[2]);
                            temp[3]=getSBoxValue(temp[3]);
                        }

                        temp[0] =  temp[0] ^ Rcon[i/Nk];
                    }
                    else if (Nk > 6 && i % Nk == 4)
                    {
                        // Function Subword()
                        {
                            temp[0]=getSBoxValue(temp[0]);
                            temp[1]=getSBoxValue(temp[1]);
                            temp[2]=getSBoxValue(temp[2]);
                            temp[3]=getSBoxValue(temp[3]);
                        }
                    }
                    RoundKey[i*4+0] = RoundKey[(i-Nk)*4+0] ^ temp[0];
                    RoundKey[i*4+1] = RoundKey[(i-Nk)*4+1] ^ temp[1];
                    RoundKey[i*4+2] = RoundKey[(i-Nk)*4+2] ^ temp[2];
                    RoundKey[i*4+3] = RoundKey[(i-Nk)*4+3] ^ temp[3];
                    i++;
    }
}

// This function adds the round key to state.
// The round key is added to the state by an XOR function.
void AddRoundKey(int round)
{
    int i,j;
    for(i=0;i<4;i++)
    {
        for(j=0;j<4;j++)
        {
            state[j][i] ^= RoundKey[round * Nb * 4 + i * Nb + j];
        }
    }
}

// The SubBytes Function Substitutes the values in the
// state matrix with values in an S-box.
void SubBytes()
{
    int i,j;
    for(i=0;i<4;i++)
    {
        for(j=0;j<4;j++)
        {
            state[i][j] = getSBoxValue(state[i][j]);

        }
    }
}

// The ShiftRows() function shifts the rows in the state to the left.
// Each row is shifted with different offset.
// Offset = Row number. So the first row is not shifted.
void ShiftRows()
{
    unsigned char temp;

    // Rotate first row 1 columns to left
    temp=state[1][0];
    state[1][0]=state[1][1];
    state[1][1]=state[1][2];
    state[1][2]=state[1][3];
    state[1][3]=temp;

    // Rotate second row 2 columns to left
    temp=state[2][0];
    state[2][0]=state[2][2];
    state[2][2]=temp;

    temp=state[2][1];
    state[2][1]=state[2][3];
    state[2][3]=temp;

    // Rotate third row 3 columns to left
    temp=state[3][0];
    state[3][0]=state[3][3];
    state[3][3]=state[3][2];
    state[3][2]=state[3][1];
    state[3][1]=temp;
}

// xtime is a macro that finds the product of {02} and the argument to xtime modulo {1b}
#define xtime(x)   ((x<<1) ^ (((x>>7) & 1) * 0x1b))

// MixColumns function mixes the columns of the state matrix
void MixColumns()
{
    int i;
    unsigned char Tmp,Tm,t;
    for(i=0;i<4;i++)
    {
        t=state[0][i];
        Tmp = state[0][i] ^ state[1][i] ^ state[2][i] ^ state[3][i] ;
        Tm = state[0][i] ^ state[1][i] ; Tm = xtime(Tm); state[0][i] ^= Tm ^ Tmp ;
        Tm = state[1][i] ^ state[2][i] ; Tm = xtime(Tm); state[1][i] ^= Tm ^ Tmp ;
        Tm = state[2][i] ^ state[3][i] ; Tm = xtime(Tm); state[2][i] ^= Tm ^ Tmp ;
        Tm = state[3][i] ^ t ; Tm = xtime(Tm); state[3][i] ^= Tm ^ Tmp ;
    }
}

// Cipher is the main function that encrypts the PlainText.
void Cipher()
{
    int i,j,round=0;

    //Copy the input PlainText to state array.
    for(i=0;i<4;i++)
    {
        for(j=0;j<4;j++)
        {
            state[j][i] = in[i*4 + j];
        }
    }

    // Add the First round key to the state before starting the rounds.
    AddRoundKey(0);

    // There will be Nr rounds.
    // The first Nr-1 rounds are identical.
    // These Nr-1 rounds are executed in the loop below.
    for(round=1;round<Nr;round++)
    {
        SubBytes();
        ShiftRows();
        MixColumns();
        AddRoundKey(round);
    }

    // The last round is given below.
    // The MixColumns function is not here in the last round.
    SubBytes();
    ShiftRows();
    AddRoundKey(Nr);

    // The encryption process is over.
    // Copy the state array to output array.
    for(i=0;i<4;i++)
    {
        for(j=0;j<4;j++)
        {
            out[i*4+j]=state[j][i];
        }
    }
}
static int runAes()
{
    int i;

    // Recieve the length of key here.
    while(Nr!=128 && Nr!=192 && Nr!=256)
    {
        //printf("Enter the length of Key(128, 192 or 256 only): ");
        //scanf("%d",&Nr);
        Nr=256;
    }
    // Calculate Nk and Nr from the recieved value.
    Nk = Nr / 32;
    Nr = Nk + 6;

// Part 1 is for demonstrative purpose. The key and plaintext are given in the program itself.
//     Part 1: ********************************************************

    // The array temp stores the key.
    // The array temp2 stores the plaintext.
    unsigned char temp[32] = {0x00  ,0x01  ,0x02  ,0x03  ,0x04  ,0x05  ,0x06  ,0x07  ,0x08  ,0x09  ,0x0a  ,0x0b  ,0x0c  ,0x0d  ,0x0e  ,0x0f};
    unsigned char temp2[32]= {0x00  ,0x11  ,0x22  ,0x33  ,0x44  ,0x55  ,0x66  ,0x77  ,0x88  ,0x99  ,0xaa  ,0xbb  ,0xcc  ,0xdd  ,0xee  ,0xff};

    // Copy the Key and PlainText
    for(i=0;i<Nk*4;i++)
    {
        Key[i]=temp[i];
        in[i]=temp2[i];
    }

    // The KeyExpansion routine must be called before encryption.
    KeyExpansion();

    // The next function call encrypts the PlainText with the Key using AES algorithm.
    Cipher();

    // Output the encrypted text.
    printf("\nText after encryption:\n");
    for(i=0;i<Nb*4;i++)
    {
        printf("%02x ",out[i]);
    }
    printf("\n\n");
}

//=============================End of Code=============================================

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();
                }
           }
        }

Zooming Bitmap images in blackberry Mobile Development

In our projects we may need zoom in or out images before they display.so this method will do it for you.simple but useful. you must have access to signed api's in blackberry
   private Bitmap ZoomImage(String FilePath, int zoomFactor) {

    Bitmap pictureDisplayed = null;

    try {
        // open the file connection to retrieve the picture from the saved
        // place
        FileConnection fconnForZoom = (FileConnection) Connector
        .open("file://" + FilePath);
        if (fconnForZoom.exists()) {
        InputStream input = fconnForZoom.openInputStream();
        int available = (int) fconnForZoom.fileSize();
        byte[] data = new byte[available];
        input.read(data, 0, available);
        EncodedImage ePictureOriginal = EncodedImage
        .createEncodedImage(data, 0, data.length);
        ePictureOriginal.setScale(20);
        if (zoomFactor == 100) {
            int scaleFP = Fixed32.tenThouToFP((int) 1 * 10000);
            EncodedImage ePictureDisplayed = ePictureOriginal
            .scaleImage32(scaleFP, scaleFP);
            pictureDisplayed = ePictureDisplayed.getBitmap();
        } else if (zoomFactor == 200) {
            int scaleFP = Fixed32.tenThouToFP((int) 2 * 10000);
            EncodedImage ePictureDisplayed = ePictureOriginal
            .scaleImage32(scaleFP, scaleFP);
            pictureDisplayed = ePictureDisplayed.getBitmap();
        }
        // I keep in memory the bitmap to get a smooth picture scrolling

        input.close();
        } else {
        pictureDisplayed = new Bitmap(0, 0);
        }

        fconnForZoom.close();

    } catch (Exception ioe) {

    }

    return pictureDisplayed;

    }

Best way to Block Accessing given URL’s in Windows

Go To directory
C:\Windows\System32\drivers\etc
open hosts file in notepad and add following text and save it.make sure you are the admin of the system else you may not be able to modify this file.site name and domain select as you need.in this case what windows system does is send request with the given site name to to the network address that we provided.since 127 is private ip range it does not redirect to any web site on internet.so this will shows server not found message.

127.0.0.1 www.sitename.com

-Java Blackberry application to send byte stream to some server via socket

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

public class Main {
    private static ServerSocket serverSocketin;
     private static ServerSocket serverSocketout;

    public static void main(String[] args) {
        try {
            serverSocketin = new ServerSocket(8206);
            serverSocketout = new ServerSocket(8207);
            DataSender dtsender = new DataSender();
            DataRiciver dataRiciver=new DataRiciver();
            dtsender.start();
            dataRiciver.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    static class DataRiciver extends Thread{
        public void run(){
            while (true){
                try {
                    Socket incoming = serverSocketin.accept();
                    DataInputStream in = new DataInputStream(incoming.getInputStream());
                    String data="";
                    data = in.readLine();
                    System.out.println(data);
                    in.close();
                    incoming.close();
                     Thread.sleep(1000);
                } catch (Exception e) {
                                 }
        }

        }
    }

    static class DataSender extends Thread {
        public DataSender() {

        }

        public void run() {
            while (true) {
                try {
                    Scanner reader = new Scanner(System.in);
                    String data = reader.nextLine();
                    Socket outgoing = serverSocketout.accept();
                    PrintStream out = new PrintStream(outgoing.getOutputStream());
                    data=data+ "\n";
                    out.write(data.getBytes());
                    out.flush();
                    out.close();
                    outgoing.close();
                    Thread.sleep(1000);
                }
                catch (Exception ioe)
                {
                }
            }
        }
    }

}

How to change value of form element before submit(Remove white space from a form variable before submit) - java script code

Here what i need to do is remove white spaces from the username variable before submit to server.This add advantage because server no need to do additional processing. This is very useful because in most cases before submit usernames and most of other parameters we have to remove white spaces

 

<script type="text/javascript">

    function checkform()
    {
        var username=document.getElementById('txtUserName').value;
        username=username.trim();
        document.getElementById('txtUserName').value=username;
        return true;
    }

      String.prototype.trim = function ()
     {
         return this.replace(/^\s*/, "").replace(/\s*$/, "");

//Regular expression is used to remove white space
     }

    </script>

Add above script to your page and modify your submit action as follows so it will call above methods when submitting

 

<form target="_self" method="POST" action="../admin/login_action.jsp" id="loginForm" onSubmit="return checkform()">

How to modify redirector to direct somewhere we need in WSO2 Stratos

 

Here we will discuss how to modify AllPagesFilter.java file to redirect requests.Check the comments shown in the below code.That will show you how to modify this file to add new redirector.

package org.wso2.stratos.redirector.servlet.ui.filters;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.stratos.common.constants.StratosConstants;
import org.wso2.stratos.redirector.servlet.ui.clients.RedirectorServletServiceClient;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class AllPagesFilter implements Filter {
    private static final Log log = LogFactory.getLog(AllPagesFilter.class);
    private static Map<String, Boolean> tenantExistMap = new HashMap<String, Boolean>();
    ServletContext context;
    public void init(FilterConfig filterConfig) throws ServletException {
        context = filterConfig.getServletContext();
    }

    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse, FilterChain filterChain) throws
            IOException, ServletException {
        if (!(servletRequest instanceof HttpServletRequest)) {
            // no filtering
            return;
        }

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String requestedURI = request.getRequestURI();

        StringTokenizer tokenizer = new StringTokenizer(requestedURI.substring(1), "/");
        String[] firstUriTokens = new String[2];
        int i = 0;
        while (tokenizer.hasMoreElements()) {
            firstUriTokens[i] = tokenizer.nextToken();
            i ++;
            if ( i > 1) {
                break;
            }
        }
        if (i > 1 && firstUriTokens[0].equals("t")) {
            if (requestedURI.startsWith("//")) {
                requestedURI = requestedURI.replaceFirst("//", "/");
            }
            String path = requestedURI.substring(firstUriTokens[0].length() +
                                                 firstUriTokens[1].length() + 2);

            // need to validate the tenant exists
            String tenantDomain = firstUriTokens[1];
            boolean tenantExists = true;
            boolean tenantInactive = false;
            if (tenantExistMap.get(tenantDomain) == null) {
                // we have to call the service :(
                RedirectorServletServiceClient client;
                try {
                    client =
                            new RedirectorServletServiceClient(context, request.getSession());
                } catch (Exception e) {
                    String msg = "Error in constructing RedirectorServletServiceClient.";
                    log.error(msg, e);
                    throw new ServletException(msg, e);
                }

                try {
                    String status = client.validateTenant(tenantDomain);
                    tenantExists = StratosConstants.ACTIVE_TENANT.equals(status);
                    if (!tenantExists &&
                            StratosConstants.INACTIVE_TENANT.equals(status)) {
                        tenantExists = true;
                        tenantInactive = true;
                    }
                } catch (Exception e) {
                    String msg = "Error in checking the existing of the tenant domain: " +
                            tenantDomain + ".";
                    log.error(msg, e);
                    throw new ServletException(msg, e);
                }
                // we have some backup stuff, if the tenant doesn't exists
                if (tenantExists) {
                    // we put this to hash only if the original tenant domain exist
                    tenantExistMap.put(tenantDomain, true);
                }
            }
            if (tenantInactive) {
                String contextPath = request.getContextPath();
                if (contextPath == null || contextPath.equals("/")) {
                    contextPath = "";
                }
                String errorPage = contextPath +
                        "/carbon/admin/error.jsp?The Requested tenant domain: " +
                        tenantDomain + " is inactive.";
                RequestDispatcher requestDispatcher =
                        request.getRequestDispatcher(errorPage);
                requestDispatcher.forward(request, servletResponse);
            } else if (tenantExists) {
                request.setAttribute(MultitenantConstants.TENANT_DOMAIN, tenantDomain);
//===========================================================
//Here wi will identify wether request contains docs/about.html
//Normally this will redirect to carbon about page if we didnt add this code. if we need to  redirect it somewhere else in
//Stratos we can do it here
                if(path.indexOf("docs/about.html")>=0)
                {
//checking and replacing doing here.So we can create "about_stratos.html" file inside
//stratos/services/manager/modules/styles/src/main/resources/web/docs folder. So once we requested docs/about.html
//it will redirect to about_stratos.html located in styles/src/main/resources/web/docs

                    path=path.replace("/docs/about.html","/docs/about_stratos.html");                   
                    request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
                    System.out.println("url is"+path);
                }
//=========================================================
                if (path.indexOf("admin/login.jsp") >= 0) {
                    // we are going to apply the login.jsp filter + tenant specif filter both in here
                    path = path.replaceAll("admin/login.jsp",
                            "tenant-login/login_ajaxprocessor.jsp");
                    request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
                }
                if (path.indexOf("/admin/index.jsp") >= 0) {
                    // we are going to apply the login.jsp filter + tenant specif filter both in here
                    path = path.replaceAll("/admin/index.jsp", "/tenant-dashboard/index.jsp");
                    request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
                }
                if (path.indexOf("admin/docs/userguide.html") >= 0) {
                    // we are going to apply the dasbhoard docs.jsp filter +
                    // tenant specif filter both in here
                   path = path.replaceAll("admin/docs/userguide.html","tenant-dashboard/docs/userguide.html");
                    request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
                }
                if ("".equals(path) || "/".equals(path) ||  "/carbon".equals(path) ||
                        "/carbon/".equals(path) || "/carbon/admin".equals(path) ||
                        "/carbon/admin/".equals(path)) {
                    // we have to redirect the root to the login page directly
                    path = "/t/" + tenantDomain + "/carbon/admin/login.jsp";
                    ((HttpServletResponse)servletResponse).sendRedirect(path);
                    return;
                }
                RequestDispatcher requestDispatcher =
                        request.getRequestDispatcher(path);
                requestDispatcher.forward(request, servletResponse);
            } else {
                String contextPath = request.getContextPath();
                if (contextPath == null || contextPath.equals("/")) {
                    contextPath = "";
                }
                String errorPage = contextPath +
                        "/carbon/admin/error.jsp?The Requested tenant domain: " +
                        tenantDomain + " doesn't exist.";
                RequestDispatcher requestDispatcher =
                        request.getRequestDispatcher(errorPage);
                requestDispatcher.forward(request, servletResponse);
            }
        }
    }
    public void destroy() {
        // nothing to destroy
    }
}

How to create redirector in WSO2 Stratos

The url's that we typed normally goes through the redirector and filters so if you want to add
some changes you must aware about these.there so many files with same name in different components
so we have to redirect correctly and carefully
Let's see how we can add redirector
First we have to open redirector component in idea

1

then we have to create redirector file AboutPageFilter.java as follows and add to filters

package org.wso2.stratos.redirector.servlet.ui.filters;
import org.wso2.stratos.common.constants.StratosConstants;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class AboutPageFilter implements Filter {
    ServletContext context;
    public void init(FilterConfig filterConfig) throws ServletException {
        context = filterConfig.getServletContext();
    }

    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse, FilterChain filterChain) throws
            IOException, ServletException {
        if (!(servletRequest instanceof HttpServletRequest)) {
            // no filtering
            return;
        }
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        if (request.getAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED) != null) {
            // if the tenant specifc url filter is passed, we are not calling the login.jsp filter
            return;
        }

        String url = request.getRequestURI();
        // use the name admin in place of admin
        url = url.replaceAll("admin/docs/about.html", "tenant-dashboard/docs/about.html"); //url replace here
        RequestDispatcher requestDispatcher =
                request.getRequestDispatcher(url);
        requestDispatcher.forward(request, servletResponse);
    }

    public void destroy() {
        // nothing to destory
    }
}

Then we have to register that filter in utils.java file. We can add new method to utils file to register our filter
as follows.so below code registers our filter

public static void adminAboutRegisterServlet(BundleContext bundleContext) throws Exception {
        if (!CarbonUtils.isRemoteRegistry()) {
            HttpServlet reirectorServlet = new HttpServlet() {
                // the redirector filter will forward the request before this servlet is hit
                protected void doGet(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                }
            };
            Filter redirectorFilter = new AboutPageFilter();
            Dictionary redirectorServletAttributes = new Hashtable(2);
            Dictionary redirectorParams = new Hashtable(2);
            redirectorParams.put("url-pattern", "/carbon/admin/docs/about.html"); //This url pattern will identified and apply filter
            redirectorParams.put("associated-filter", redirectorFilter);
            redirectorParams.put("servlet-attributes", redirectorServletAttributes);
            redirectorServiceRegistration = bundleContext.registerService(Servlet.class.getName(),
                    reirectorServlet, redirectorParams);
        }
    }

 

Then we have to activate our filter. We can activate our filter in RedirectorServletUIComponent.java file

public class RedirectorServletUIComponent {
     private static Log log = LogFactory.getLog(RedirectorServletUIComponent.class);

    protected void activate(ComponentContext context) {
        try {
            Util.domainRegisterServlet(context.getBundleContext());
            Util.loginJspRegisterServlet(context.getBundleContext());
            Util.indexJspRegisterServlet(context.getBundleContext());
            Util.adminDocsRegisterServlet(context.getBundleContext());
           Util.adminAboutRegisterServlet(context.getBundleContext());

//Here we have activated our filter
            log.debug("******* Multitenancy Redirector Servlet UI bundle is activated ******* ");
        } catch (Exception e) {
            log.error("******* Multitenancy Redirector Servlet UI bundle failed activating ****", e);
        }
    }
    protected void deactivate(ComponentContext context) {
        log.debug("******* Multitenancy Redirector Servlet UI bundle is deactivated ******* ");
    }
}

So now we have successfully add filter and activated it.Now you can use this as you need in different locations in WSO2 Stratos

How to run server in debug mode with idea

Go to servers bin folder and start server as follws
sanjeewa@sanjeewa-laptop:/media/New Volume/wso2stratos-manager-1.0.0/bin$ sh wso2server.sh debug 5005

  1. Go to Run > Edit Configurations.
  2. Click the plus icon and choose Remote.
  3. Name your profile and hit "OK".
  4. Go to Run > Debug to connect to begin debugging

Then go to idea interface open corresponding project source go to remote debug
then set the same port from the UI, then press debug button. server will not start till we press debug button from idea UI

How to set session variables from JSP

set session variables using the command given below
session.setAttribute( "theName", "sanjeewa malalgoda" );
//session.setAttribute( "Attribute name", "Value" );

Get session variables using the command given below
<%= session.getAttribute( "theName" ) %>
//this may return null if there no such session variable

Set Cookies from JSP - example

Set Cookies as follows
You may need to add page import
<%@ page language="java" import="java.util.*"%>
<%
Cookie cookie = new Cookie ("username","sanjeewa malalgoda");
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
%>

Get Cookies as Follows
Here we search cookie for name username and display the results
<%
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i]; break;
}
}
}
%>
<%
if (myCookie == null)
{
%>No Cookie found with the name <%=cookieName%>
<%
}
else
{
%>
Welcome: <%=myCookie.getValue()%>.
<%
}
%>

How to display given location in google map

Use this code
later i have described how to get coordinates from given location name so you can pass that coordinates to this form

http://code.google.com/apis/maps/documentation/javascript/v2/examples/map-simple.html

How to install sinhala fonts on ubuntu

First you have to download the font file "filename.ttf" to you machine.
Then you need some permissions to add those files to folder named
/usr/share/fonts/truetype
To do that first goto truetype folder by using following command
sanjeewa@sanjeewa-laptop:~$ cd /usr/share/fonts/truetype
Then use next command to grant file permissions to that folder(Else you wont be able to copy files to that folder)
sanjeewa@sanjeewa-laptop:/usr/share/fonts/truetype$ sudo chmod 777 ttf-sinhala-lklug/
Then copy your font file into folder named ttf-sinhala-lklug/

Then refresh browser

Change the order of window buttons and move side from left to right in Ubuntu 10.04

One of the change in the Ubuntu 10.04  is the  window buttons on the left side. We’ll show you how to move the buttons back to the right.

Press Alt+F2 to bring up the Run Application, enter “gconf-editor” in the text field, and click on Run.

The key that we want to edit is in apps/metacity/general.

Click on the + button next to the “apps” folder, then beside “metacity” in the list of folders expanded for apps, and then click on the “general” folder.

The button layout can be changed by changing the “button_layout” key. Double-click button_layout to edit it.
Change the text in the Value text field to:
menu:maximize,minimize,close
Click OK and the change will occur immediately

How to create mysql database with all permissions to users

This command can use to  grant all permissions to given user for given database at given host. So you can easili change capitalized fields and use it
mysql> grant all privileges on DATABASENAME.* to "USERNAME"@"HOSTNAME" identified by 'PASSWORD';
mysql> grant all on DATABASENAME.* to "USERNAME"@"HOSTNAME" identified by 'PASSWORD';

Next command can use to grant all permissions to all users at given host here "% " sign denotes all
mysql> grant all privileges on DBNAME.* to "%"@"HOSTNAME" identified by 'PASSWORD';

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==

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...