Calling a C program from java

Java provides us with a native interface which allows calling native programs (code) like C, C++, etc. and this interface is called as Java Native Interface (JNI).

Java Native Interface(JNI): The Java SDK’s Java Native Interface (JNI) is a programming framework that enables Java code running in a Java Virtual Machine (JVM) to call, and to be calledby, native applications (programs specific to a hardware and operating system platform) and libraries written in other languages such as C, C++ and assembly.

At compile time, JNI defines how Java data types correspond to C data types. C programs get this

Information from JNI header files that come with the Java SDK.

The header files for specific application/program are created using a tool named Javah.

Javah: A tool that comes with the SDK, creates application-specific header files that helps to eliminate programming errors in communication between Java and C routines.

At run time, JNI lets Java objects be passed to C code, and lets C code access Java properties and methods. Thus, C code can set properties of Java classes, making it possible to call Java methods from C and vice versa.

image

JNI acts as an intermediate between Java Code and  other native languages, this calling of native code can be used to avoid the rewriting the code in java, and implements the functionality of code reusability.

Some simple steps to call a c method from java program:

Step-1: Create a Java program that contains the declaration of the C methods as native. 

Step-2: Compile the java program. 

Step-3: Use the Javah tool to create a header file that corresponds to the Java program.          

Step-4: Write the C code and compile the program.                                    

Step-5: Generate the shared library.                

Step-6: Execute the Java program.

 

Step-1: Creating a java program with declaration of C methods as native

In our example we will take a simple example with a welcometoC() method which is a native method of C to be called from java program.

The code to call the native method is:

public native void welcometoC(); 

The above declaration instructs the Java compiler that the program calls a native method. This declaration enables the integration of a C method (welcometoC) within a Java program.

After the native method is declared, you need to load the library that contains the implementation of the method you are going to call in the Java code. The following statement loads the library:

static {
System.loadLibrary("DemoC");
} 

So the complete java program is:-

//Demo.java
public class Demo {

// Declaration of the native method

public native void welcometoC();

/*The native keyword tells the compiler that the implementation of this method is in a native language*/
/*Loading the library containing the implementation of the native method*/

    static {
      	  System.loadLibrary("DemoC");
               }
//invoking the native method
    public static void main(String[] args)
   {
        new Demo().welcometoC();
    }
}

Step-2: Compile the java program   Compile the java program with javac compiler. During compilation, the compiler includes information about the native methods declared in the code. This helps to develop the header file.


 Step-3: Use the Javah tool to create a header file that corresponds to the Java program                   

For creating the header files use the Javah tool, which is available in the JDK in the Bin folder.

Do place the header file in the include directory in the JDK folder, as this file provides the signature of the native method declared in the java program.

The header file provides the following signature:

Java_Demo_welcometoC(JNIEnv*, jobject);

  • JNIEnv*: Represents an interface pointer.
  • jobject: Signifies a reference to the Java object for which the native method is invoked.

The JNIEnv* is the pointer to the thread that invokes a native method. This pointer is used by the C implementation code to access objects or variables from the Java code.

The header file is generated as shown below:

//Demo.h

/* DO NOT EDIT THIS FILE - it is machine generated */

#include <jni.h>

/* Header for class Demo */

#ifndef _Included_Demo

#define _Included_Demo

#ifdef __cplusplus

extern "C"

{

#endif

/*

* Class:     Demo

* Method:    welcometoC

* Signature: ()V

*/

JNIEXPORT void JNICALL Java_Demo_welcometoC (JNIEnv *, jobject);

#ifdef __cplusplus

}

#endif

#endif

//end of Demo.h

Step-4: Write the C code and compile the program

// DemoC.c

#include <stdio.h>

#include <jni.h>

#include "Demo.h"

//definition of methodOfC()

&nbsp;

JNIEXPORT void JNICALL Java_Demo_welcometoC (JNIEnv *env, jobject javaobj)

{

printf("Hello this is C program\n");

printf("Going back to Java program…");

return;

}

In the above C program some terms to get known are:

  • jni.h: Provides the interface between Java and C.
  • Demo.h: Represents the header file generated from Demo.class.
  • stdio.h: Represents a standard library C header file needed for printf().

Now to compile the c program we need the c compiler, so I have used the Tiny C. Download and unzip the file and set the OS path to tcc.exe

Step-5: Generate the shared library

To generate the shared library file dll use the following command:

tcc DemoC.C -I C:/Progra~1/Java/jdk1.7.0_07/include -I C:/Progra~1/Java/jdk1.7.0_07/include/win32 -shared -o Demo.dll

Two directories are included in the compile command, those are to include the jni.h and jni_md.h

Step-6: Execute the Java program

As we are done with all the compilations, run the java program with specific java tool.

OUTPUT:                           

Hello this is C program

Going back to Java program…

Your Queries are always welcomed 🙂

Solutions for some standard erros in joomla

Hello friends,
Today we will discuss here about some standard errors comes in joomla website development.
1) Solve the error of function ereg() is deprecated :-
Generally this error comes when we are using ereg() functions. There is a standard solutions of it by using preg() function instead of ereg() function. Because ereg() functions are deprecated.
Suppose if you are using,

ereg_match("/foo/g",$needle,$haystack);

and you are getting the error like function ereg() is deprecated then you should write like,

preg_match("/foo/g",$needle,$haystack);

2) Solve the error of Call-time pass-by-reference has been deprecated :-
This type of errors because of some minor mistakes we made or it is in the module file that we use ready made.

Suppose if you are using,

call_user_func('Formo_'.$name.'::load', & $this);

and you are getting error like Call-time pass-by-reference has been deprecated than you have to just remove the & before $this.

call_user_func('Formo_'.$name.'::load', $this);

3) Solve the error of function split() is deprecated :-
Generally this error comes when we are using split functions. There is a standard solutions of it by using explode() function instead of split() function. Because split() functions are deprecated.
Suppose if you are using,

split_match("/foo/g",$needle,$haystack);

and you are getting the error like function split() is deprecated then you should write like,

explode_match("/foo/g",$needle,$haystack);

4) Another general error comes like Could not instantiate mail function :-

In this case you would have to follow the steps written as below,

Go to Admin panel > Global Configuration > Server > Mail Settings > Mailer and select SENDMAIL there,instead of PHP MAIL FUNCTION.

5) Remove index.php from the url :-

After making a joomla site many developers faces the problem of removing the index.php from the url.

For that you would have to follow below steps :-
• Go to the Global Configuration area within your Joomla admin.
• Under SEO Settings, click YES for the following 3 items:
• Search Engine Friendly URLs Yes
• Use Apache mod_rewrite Yes
• Add suffix to URLs Yes
• Rename you htaccess.txt file to .htaccess
• Use a text editor to remove the “#” before the words RewriteBase on line 70 (Joomla 1.5.23)

These were some standard errors comes in joomla website development. Solve and Enjoy.

Javascript Validation in Magento

Hello friends,

Validation is most important thing in any sort of website development to get proper user input. There are mainly two types of validation: Client Side and Server Side. In order to perform client side validation javascript is one of the best options.

While working in magento it is good to know that magento uses a file called form.js (/js/varien/form.js) which has Validation class and it is part of the Prototype javascript library. In Validation class, javascript functions are there to perform form validation. So there is no need to write extra code to perform javascript validation.

In magento applying javascript validation to any form is so simple. Follow the under given steps to apply javascript validation to your custom form.

Step 1: Apply the validation class to your form controls according to your requirement.

For Example:

<input type="text" id="name" name="name" value="" class="required-entry" />
<input type="text" id="dob" name="dob" value="" class="required-entry validate-date"/>
<input type="text" id="email" name="email" value="" class="required-entry validate-email"/>

In above example we have three form controls name, dob and email. There we apply required-entry, validate-date and validate-email classes to form controls. And those classes will perform required field validation, date validation and email validation for their respective form control.

Here we applied validation class to form controls because Validation class works by checking form inputs for certain class names.

Step 2: Create a form object to represent your form.

<script type="text/javascript">
//< ![CDATA[
var customForm= new VarienForm('customFormId', true);
//]]>
</script>

Here the first argument customFormId is the Id of your form. And if you set true to second argument then the cursor will automatically move into the first input field. You can also set second argument to false.

Now when user will submit the form and if any improper data is there in user input then validate class will give the proper error message and will not submit the form until user enters proper data.

There are many inbuilt validation classes in magento to perform different types of validation. Here I have listed those:

validate-select

Please select an option

required-entry

This is a required field

validate-number

Please enter a valid number in this field

validate-digits

Please use numbers only in this field. please avoid spaces or other characters such as dots or commas

validate-alpha

Please use letters only (a-z or A-Z) in this field.

validate-code

Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

validate-alphanum

Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed

validate-street

Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field

validate-phoneStrict

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890

validate-phoneLax

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890

validate-fax

Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890

validate-date

Please enter a valid date

validate-email

Please enter a valid email address. For example johndoe@domain.com.

validate-emailSender

Please use only letters (a-z or A-Z), numbers (0-9) , underscore(_) or spaces in this field.

validate-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored

validate-admin-password

Please enter 7 or more characters. Password should contain both numeric and alphabetic characters

validate-cpassword

Please make sure your passwords match

validate-url

Please enter a valid URL. http:// is required

validate-clean-url

Please enter a valid URL. For example http://www.example.com or http://www.example.com

validate-identifier

Please enter a valid Identifier. For example example-page, example-page.html or anotherlevel/example-page

validate-xml-identifier

Please enter a valid XML-identifier. For example something_1, block5, id-4

validate-ssn

Please enter a valid social security number. For example 123-45-6789

validate-zip

Please enter a valid zip code. For example 90602 or 90602-1234

validate-zip-international

Please enter a valid zip code

validate-date-au

Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006

validate-currency-dollar

Please enter a valid $ amount. For example $100.00

validate-one-required

Please select one of the above options.

validate-one-required-by-name

Please select one of the options.

validate-not-negative-number

Please enter a valid number in this field

validate-state

Please select State/Province

validate-new-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored

validate-greater-than-zero

Please enter a number greater than 0 in this field

validate-zero-or-greater

Please enter a number 0 or greater in this field

validate-cc-number

Please enter a valid credit card number.

validate-cc-type

Credit card number doesn’t match credit card type

validate-cc-type-select

Card type doesn’t match credit card number

validate-cc-exp

Incorrect credit card expiration date

validate-cc-cvn

Please enter a valid credit card verification number.

validate-data

Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

validate-css-length

Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%

validate-length

Maximum length exceeded

Hope this will help you.

Thanks.

Magento: Redirect to Checkout after “Add to Cart”

Magento uses the default process that when product is “Add to Cart” from category page or from product detail page then product is added to cart and redirect to the cart page. Here, we are directly redirect to the checkout onepage from the category list and product detail page.

The Process of redirection is done by using the event observer.

Your config would look something like this:

<frontend>
    <events>
   	<checkout_cart_add_product_complete>
      	     <observers>
        	 <packagename_modulename_observer>
         	      <type>singleton</type>
         	      <class>packagename_modulename/observer</class>
          	      <method>addToCartComplete</method>
        	 </packagename_modulename_observer>
      	     </observers>
     	 </checkout_cart_add_product_complete>
     </events>
</frontend>

You could create an observer listening for the checkout_cart_add_product_complete event and in there you could do something like the following:

public function addToCartComplete(Varien_Event_Observer $observer) {
    // Send the user to the Item added page
    $response = $observer->getResponse();    
    $request = $observer->getRequest();
    $response->setRedirect(Mage::getUrl('checkout/onepage'));
    Mage::getSingleton('checkout/session')->setNoCartRedirect(true);
}

The another method to Redirect to Checkout after “Add to Cart” like the following :
The URL for the redirect process can be found under
app/code/core/Mage/Checkout/controllers/ in CartController.php

Copy this File (or just change it quick) and search function

protected function _goBack()

the first part is for redirecting to product if this is set in backend. but take a closer look at

$this->_redirect('checkout/cart');

Change it to

$this->_redirect('checkout/onepage');

Hope it helps you while you’re treading you way though Magento addtocart process. Comment here for any questions or suggestions.

Magento: Paging in Custom Collection

Hello friends,

In last week I had a requirement to add paging facility in our custom module’s collection. Normally, magento provides paging in products collection. But this time, it is something different.

To satisfy that requirement, I had searched the web and found the best solution which I want to discuss here.

So now follow the under given steps:

Note: Here my module is Indies_Custom, so you have to change the class names according to your module.

Step 1: Controller (IndexController.php) file

In index controller simply load the layout and render it.

<?php
class Indies_Custom_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }
}

Step 2: Layout (custom.xml) file

Put the under given code in the layout file of module.

<?xml version="1.0"?>
<layout version="0.1.0">
   <custom_index_index>
       <reference name="content">
           <block type="custom/collection" name="collection" template="custom/collection.phtml" />
       </reference>
   </custom_index_index>
</layout>

Step 3: Block (Collection.php) file

Here we will create a ‘custom/collection’ block for the pager to set our collection in it.

<?php
class Indies_Custom_Block_Collection extends Mage_Core_Block_Template
{
    public function __construct()
    {
        parent::__construct();
        $collection = Mage::getModel('custom/collection')->getCollection();
        $this->setCollection($collection);
    }

    protected function _prepareLayout()
    {
        parent::_prepareLayout();

        $pager = $this->getLayout()->createBlock('page/html_pager', 'custom.pager');
        $pager->setAvailableLimit(array(5=>5,10=>10,20=>20,'all'=>'all'));
        $pager->setCollection($this->getCollection());
        $this->setChild('pager', $pager);
        $this->getCollection()->load();
        return $this;
    }

    public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }
}

Step 4: Template (collection.phtml) file

At last, put the under given code in the template file of module.

Note: You can change the designing structure of this file according to your requirement.

<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
<?php $collection = $this->getCollection(); ?>
<div>
    <h1><?php echo $this->__('My Custom Collection') ?></h1>
</div>
<?php echo $this->getPagerHtml(); ?>
<?php if($collection->getSize()): ?>
<table id="my-custom-table">
    <col width="1" />
    <col width="1" />
    <col />
    <col width="1" />
    <col width="1" />
    <col width="1" />
    <thead>
        <tr>
            <th><?php echo $this->__('ID #') ?></th>
            <th><?php echo $this->__('Title') ?></th>
            <th><span><?php echo $this->__('Created') ?></span></th>
        </tr>
    </thead>
    <tbody>
        <?php $_odd = ''; ?>
        <?php foreach ($collection as $_obj): ?>
            <tr>
                <td><?php echo $_obj->getCollectionId() ?></td>
                <td><span><?php echo $_obj->getTitle(); ?></span></td>
                <td><?php echo $this->formatDate($_obj->getCreatedTime()) ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<script type="text/javascript">decorateTable('my-custom-table');</script>
<?php echo $this->getPagerHtml(); ?>
<?php else: ?>
    <p><?php echo $this->__('The collection is empty.'); ?></p>
<?php endif ?>

That’s it. Now you can see the paging in your custom collection page.

Hope this will help you.

Thanks.

Fetch attribute value from database and populate admin drop down list

Hello Friends , today we will discuss here to fetch the attribute value from the database and showing it into the attribute dropdown list.

Code for fetching the value from the database :-


Class Namespace_Modulename_Model_Sourcefilename  extends Mage_Eav_Model_Entity_Attribute_Source_Abstract

{

public function getAllOptions()

{

$var = Mage::getModel('modulename/modelname')->getCollection();

foreach ($var as $var1)

{

$label = $var1->getName();//Name of your option displayed in dropdown of attribute

$value = $var1->getId(); // Id of attribute for product

$this->_options[]= array('label'=> $label, 'value'=> $value );

}

return $this->_options;

}

}

  •  First of all you have to create a new source file for your attribute in that you will have to write the above code.
  •  At the first you have to write a class hierarchy as mentioned above in the first line.
  •  After that you have write a function called getAllOptions() which is magento default function for this process.
  •  After that you would have to call your respective model for your attribute and use getCollection method to collect all the data stored in the database through that model.
  •  Now you will have set a foreach loop to distinguish the data stored in model.You will have to fatch the data required to you.
  •  In the foreach loop the value stored in $var is assigned to $var1.
  •  Than to display the label in the dropdown list you will have to fetch the respective database field.(suppose your database field name is name than use getName() method.)
  •  Similarly you will have to fatch the relative Id for your name from the database.
  •  In last you will have to just return it.
  • Below I have shown snapshot which shows  the Dropdown list of Department attribute.