Running scripting language in Java

Last week while I was working on an application which needed the maximum use of Scripting language, a thing just stroked in my mind, can’t we run scripts directly in different languages????

On lot of searching, I just came up with the solution of using scripting language like JavaScript, python, NetRexx, TCL etc. within the java language with utmost ease.

Java 6 introduces scripting engine support in to Java, and this new support provides a link between the Java and delayed binding world of scripting languages.

This all is possible with a simple package that java provides us. The Java Scripting functionality is in the javax.script package. This is a relatively small, simple API. Scripts can be executed from within java in the JVM. Many independent scripting packages have been available for Java for some time, including Rhino, Jacl, Jython, BeanShell, JRuby, and others. To work with scripts, you only need to know a couple of key classes, form which here we will learn two of them:

1)     ScriptEngineManager

2)     ScriptEngine

The ScriptEngine interface models script engines, and the ScriptEngineManager class provides convenient methods to register and obtain a ScriptEngine object.

ScriptEngineManager:

To instantiate a script engine, you use the ScriptEngineManagerclass to retrieve a ScriptEngine object for the scripting language you’re interested in. Each scripting language has a name like JavaScript, rhino etc.

Generally it handles two key functions:

i.            Discovery of script engine

ii.            Storing data in context

It provides a key value pair, which is provided to all the instances of ScriptEngine created by the ScriptEngineManager and it is referred as “Global state”.

ScriptEngine:

ScriptEngine is an interface which handles script interpreting and evaluation. This is implemented separately for every single language. Apache commons provides a project Jakarta Bean Scripting Framework (BSF) which gives implementation for a several set of scripting languages like TCL, NetRexx, JavaScript, Python lot more…

Let’s take an example using JavaScript as a scripting language:

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

public class ScriptDemo {

public static void main(String[] args) {

// create a ScriptEngineManager object

ScriptEngineManager manager = new ScriptEngineManager();

// get the ScriptEngine instance

ScriptEngine engine = manager.getEngineByName("javascript");

// execute script

String script = "print('This is an example to run JavaScript in java')";

try {

engine.eval(script);

engine.eval("var a= 10;");

engine.eval("var b = 10;");

engine.eval("var c = a + b;");

engine.eval("print (c);");

} catch (ScriptException e) {

e.printStackTrace();

}

}

}

The output of the program will be:

 

 

 

 

 

For more information on scripting packages, its variables, API and various examples to work with you can visit Java Scripting guide.

So if you find a problem like mine and hopefully you come across this article, I would be grateful helping you with your queries 🙂

Advertisements

Magento – Fatal error: Out of memory (allocated 14680064) (tried to allocate 1245184 bytes)

Hello friends,
In last week I have faced one horrible issue in our live website. Due to that issue our live site had stopped working and gave the under given error:

Fatal error: Out of memory (allocated 14680064) (tried to allocate 1245184 bytes)

Inadequate memory limit caused the above error. And to solve that I had searched the web and found a proper solution, which I want to share here.
Now to solve the above error follow the under given steps:
Step 1: Open the .htaccess file from the magento root directory and around line 35 replace the

    php_value memory_limit 256M

with

    php_value memory_limit 512M

Step 2: From the magento root directory rename the php.ini.sample file to php.ini
Step 3: Open the php.ini file and replace the

memory_limit = 64M

with

memory_limit = 512M

Step 4: Go to Admin -> System -> Cache Management and refresh all the cache.
That’s it.
Hope this will help you.
Thanks.

Posted in Magento. 1 Comment »

Magento admin input form fields through coding

Every Magento developer who’s ever worked with backend forms knows the need to add, edit or delete various types of fields through coding. Be it a simple text box or a drop down list, any field can be added with its attributes and values from your PHP file. Each time you create of those fields you’d need to refer to the syntax of each field. So for the benefit of all of us here’s a quick reference to the proper syntax of all field types that can be added into a form.

Here is how to add a text field to an admin form, with a list of all the options.

Time

$fieldset->addField('time', 'time', array(
          'label'     => Mage::helper('form')->__('Time'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
          'onclick' => "",
          'onchange' => "",
          'value'  => '12,04,15',
          'disabled' => false,
          'readonly' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

TextArea

$fieldset->addField('textarea', 'textarea', array(
          'label'     => Mage::helper('form')->__('TextArea'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
          'onclick' => "",
          'onchange' => "",
          'value'  => '<b><b/>',
          'disabled' => false,
          'readonly' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Note

$fieldset->addField('note', 'note', array(
          'text'     => Mage::helper('form')->__('Text Text'),
        ));

Submit Button

$fieldset->addField('submit', 'submit', array(
          'label'     => Mage::helper('form')->__('Submit'),
          'required'  => true,
          'value'  => 'Submit',
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Text Field

$fieldset->addField('title', 'text', array(
          'label'     => Mage::helper('form')->__('Title3'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
          'onclick' => "alert('on click');",
          'onchange' => "alert('on change');",
          'style'   => "border:10px",
          'value'  => 'hello !!',
          'disabled' => false,
          'readonly' => true,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Multiselect

$fieldset->addField('multiselect2', 'multiselect', array(
          'label'     => Mage::helper('form')->__('Select Type2'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
          'onclick' => "return false;",
          'onchange' => "return false;",
          'value'  => '4',
          'values' => array(
                                '-1'=> array( 'label' => 'Please Select..', 'value' => '-1'),
                                '1' => array(
                                                'value'=> array(array('value'=>'2' , 'label' => 'Option2') , array('value'=>'3' , 'label' =>'Option3') ),
                                                'label' => 'Size'    
                                           ),
                                '2' => array(
                                                'value'=> array(array('value'=>'4' , 'label' => 'Option4') , array('value'=>'5' , 'label' =>'Option5') ),
                                                'label' => 'Color'   
                                           ),                                         
                                  
                           ),
          'disabled' => false,
          'readonly' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Submit Button

$fieldset->addField('radio', 'radio', array(
          'label'     => Mage::helper('form')->__('Radio'),
          'name'      => 'title',
          'onclick' => "",
          'onchange' => "",
          'value'  => '1',
          'disabled' => false,
          'readonly' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));
	
$fieldset->addField('radio2', 'radios', array(
          'label'     => Mage::helper('form')->__('Radios'),
          'name'      => 'title',
          'onclick' => "",
          'onchange' => "",
          'value'  => '2',
          'values' => array(
                            array('value'=>'1','label'=>'Radio1'),
                            array('value'=>'2','label'=>'Radio2'),
                            array('value'=>'3','label'=>'Radio3'),
                       ),
          'disabled' => false,
          'readonly' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Link

$fieldset->addField('link', 'link', array(
          'label'     => Mage::helper('form')->__('Link'),
          'style'   => "",
          'href' => 'https://indiestechtips.wordpress.com',
          'value'  => 'Magento Blog',
          'after_element_html' => ''
        ));

DropDown

$fieldset->addField('select', 'select', array(
          'label'     => Mage::helper('form')->__('Select'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
          'onclick' => "",
          'onchange' => "",
          'value'  => '1',
          'values' => array('-1'=>'Please Select..','1' => 'Option1','2' => 'Option2', '3' => 'Option3'),
          'disabled' => false,
          'readonly' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Here is another version of the drop down

$fieldset->addField('select2', 'select', array(
          'label'     => Mage::helper('form')->__('Select Type2'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
          'onclick' => "",
          'onchange' => "",
          'value'  => '4',
          'values' => array(
                                '-1'=>'Please Select..',
                                '1' => array(
                                                'value'=> array(array('value'=>'2' , 'label' => 'Option2') , array('value'=>'3' , 'label' =>'Option3') ),
                                                'label' => 'Size'    
                                           ),
                                '2' => array(
                                                'value'=> array(array('value'=>'4' , 'label' => 'Option4') , array('value'=>'5' , 'label' =>'Option5') ),
                                                'label' => 'Color'   
                                           ),                                         
                                  
                           ),
          'disabled' => false,
          'readonly' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Password Field

$fieldset->addField('password', 'password', array(
          'label'     => Mage::helper('form')->__('Password'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
          'onclick' => "",
          'onchange' => "",
          'style'   => "",
          'value'  => 'hello !!',
          'disabled' => false,
          'readonly' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));
	
$fieldset->addField('obscure', 'obscure', array(
          'label'     => Mage::helper('form')->__('Obscure'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'obscure',
          'onclick' => "",
          'onchange' => "",
          'style'   => "",
          'value'  => '123456789',
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

File Upload

$fieldset->addField('file', 'file', array(
          'label'     => Mage::helper('form')->__('Upload'),
          'value'  => 'Uplaod',
          'disabled' => false,
          'readonly' => true,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Multiline

$fieldset->addField('multiline', 'multiline', array(
          'label'     => Mage::helper('form')->__('Multi Line'),
          'class'     => 'required-entry',
          'required'  => true,
          'name'      => 'title',
          'onclick' => "",
          'onchange' => "",
          'style'   => "border:10px",
          'value'  => 'hello !!',
          'disabled' => false,
          'readonly' => true,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Label

$fieldset->addField('label', 'label', array(
          'value'     => Mage::helper('form')->__('Label Text'),
        ));

Image Upload

$fieldset->addField('image', 'image', array(
          'value'     => 'https://indiestechtips.wordpress.com/wp-themes/test/images/logo.gif ',
        ));

Checkbox

$fieldset->addField('checkbox', 'checkbox', array(
          'label'     => Mage::helper('form')->__('Checkbox'),
          'name'      => 'Checkbox',
          'checked' => false,
          'onclick' => "",
          'onchange' => "",
          'value'  => '1',
          'disabled' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

$fieldset->addField('checkboxes', 'checkboxes', array(
          'label'     => Mage::helper('form')->__('Checkboxs'),
          'name'      => 'Checkbox',
          'values' => array(
                            array('value'=>'1','label'=>'Checkbox1'),
                            array('value'=>'2','label'=>'Checkbox2'),
                            array('value'=>'3','label'=>'Checkbox3'),
                       ),
          'onclick' => "",
          'onchange' => "",
          'value'  => '1',
          'disabled' => false,
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1
        ));

Date

$fieldset->addField('date', 'date', array(
          'label'     => Mage::helper('form')->__('Date'),
          'after_element_html' => '<small>Comments</small>',
          'tabindex' => 1,
          'image' => $this->getSkinUrl('images/grid-cal.gif'),
          'format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT)
        ));

If you want a look at all the fields that can be created by Magento you can find all of them in here.
lib\Varien\Data\Form\Element

Hope it helps you while you’re treading you way though Magento backend forms creation. Comment here for any questions or suggestions.

Learning a simple hibernate program

Here I will explain Hibernate sample program using Java Application in Eclipse IDE. In this example we will insert record in MySQL database.

Follow the instructions step by step to run your Simple Hibernate Program in Eclipse IDE

Step – 1 Creating Java Project

Step – 2 Project Structure For Hibernate Example

Step – 3 Create hibernate.cfg.xml(Configuration file)

Step – 4 Create a Pojo File(mapping to database table)

Step – 5 Creatingusercontact.hbm.xml

Step – 6 Create The Class To Insert Records

Step – 7 Adding Jar Files

Step – 8 Run Your Main Class File

Step- 1 Creating Java Project

Start Eclipse and go to File -> New -> Project -> Java Project

On clicking next you will have to enter the Project name and your project gets created.

Step- 2 Project structure for Hibernate example

– The project structure for Hibernate_Example is shown below:

Step- 3 Create hibernate.cfg.xml (Configuration file)

-hibernate.cfg.xml:

<property  name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>

The above shown is the property is for loading the Drivers in MySQL database.

<property name=”hibernate.connection.url”>jdbc:mysql://localhost/usercontact</property>

The above property is used to open connection to database named usercontact which runs in localhost.

<property name=”hibernate.connection.username”>root</property>

The above property shows that the username for the database connection is root.

<property name=” hibernate .connection. password”> </property>

The above property shows that there is no password used for the database connection.

<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>

The dialect property  is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL Database.

Hibernate supports many databases for Object/Relational Mapping and Transparent Object Persistence for Java. We can use following databases dialect type property:

<mapping resource=”usercontact.hbm.xml”/>

The above property is used for mapping  usercontact table.


<?xml version=<em>'1.0'</em> encoding=<em>'utf-8'</em>?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name=<em>"hibernate.connection.driver_class"</em>>com.mysql.jdbc.Driver</property>

<property name=<em>"hibernate.connection.url"</em>>jdbc:mysql://<span style="text-decoration: underline;">localhost</span>/<span style="text-decoration: underline;">usercontact</span></property>

<property name=<em>"hibernate.connection.username"</em>>root</property>

<property name=<em>"hibernate.connection.password"</em>></property>

<property name=<em>"hibernate.connection.pool_size"</em>>10</property>

<property name=<em>"show_sql"</em>>true</property>

<property name=<em>"dialect"</em>>org.hibernate.dialect.MySQLDialect</property>

<property name=<em>"hibernate.hbm2ddl.auto"</em>>update</property>

<!-- Mapping files -->

<mapping resource=<em>"usercontact.hbm.xml"</em>/>

</session-factory>

</hibernate-configuration>

Step- 4 Create a pojo file (mapping to database table)

Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for usercontact.java:


package com.demojava;

public class usercontactVO {

private String firstName;

private String lastName;

private int phone;

private String email;

private long id;

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

public int getPhone() {

return phone;

}

public void setPhone(int phone) {

this.phone = phone;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

}

Step- 5 Creating usercontact.hbm.xml

This file is used to map the usercontact object to usercontact table in database. Here is the code for usercontact.hbm.xml:


<?xml version=<em>"1.0"</em> encoding=<em>"UTF-8"</em>?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name=<em>"com.demojava.usercontactVO"</em> table=<em>"usercontact"</em>>

<id name=<em>"id"</em> type=<em>"long"</em> column=<em>"ID"</em> >

<generator class=<em>"assigned"</em>/>

</id>

<property name=<em>"firstName"</em>>

<column name=<em>"FIRSTNAME"</em> />

</property>

<property name=<em>"lastName"</em>>

<column name=<em>"LASTNAME"</em>/>

</property>

<property name=<em>"email"</em>>

<column name=<em>"EMAIL"</em>/>

</property>

<property name=<em>"phone"</em> type=<em>"int"</em>>

<column name=<em>"PHONE"</em>/>

</property>

</class>

</hibernate-mapping>

Step- 6 Creating the class to insert records.

Before creating a class we should be clear about hibernate session.

Hibernate session: Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.

On session.save(contact) will save the information into database.


package com.demojava;

import org.hibernate.Session;

import org.hibernate.Transaction;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class main1

{

public static void main (String[] args) {

Session session = null;

try{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory = new

Configuration().configure().buildSessionFactory();

session =sessionFactory.openSession();

Transaction tx=(Transaction)session.beginTransaction(); // Add this soon after initializing session object

//Create new instance of usercontactVO and set values in it by reading them from form object

System.out.println("Inserting Record");

usercontactVO contact = new usercontactVO();

contact.setId(1);

contact.setFirstName("Indies");

contact.setLastName("Services");

contact.setEmail("indies.co.in");

contact.setPhone(12345);

session.save(contact);

tx.commit();

System.out.println("Done");

}

catch(Exception e){

System.out.println(e.getMessage());

}

finally {

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

}

}

Step- 7 Adding jar files

The following jar files needs to be added to run the application/Example in Hibernate

You can add jar files as shown below:

Click on project on right click select properties which will open the following Dialog box.

Step- 8 Run your Main Class Files

Right click  project -> Run As -> Java Application

This is the output you will find- And you records get inserted.

Hope this helps you 🙂 Your queries are always welcomed…