Saturday, October 4, 2014

Open video from www.clt20.com in a new tab

If you want to see the video at clt website in fullscreen ot you want to open the video in a new tab, it is not possible directly. Just follow the following simple steps to achieve these
1) In chrome browser, right click on the page and click on inspect elements. It will open a new section
2) At the top left corner of this section, a magnifying glass can be found. Click on this magnifying glass and then click on the video. This will take to the section which is forming the video.
3)That will actually point to an object tag which is collapsed. Click on the small right arrow mark which is present before <object> This will result in opening of parameters for this tag (<param>)
4)Check the last parameter with name=flashVars and corresponding to this there is a value. Copy whatever is present in the value section i.e. inside the double quotes.
5)Append whatever is copied at step 4 in following string
http://assets.delvenetworks.com/player/loader.swf?
6)So your final string will look something like
http://assets.delvenetworks.com/player/loader.swf?deepLink=true&mediaId=5934f92944374ffa96db68deaed3f316&playerForm=b2eecbdf5bfb4e0faf1923076fc47b12
7)Paste this url in a separate tab and click enter.
Voila! It's done

You can even save the page which will actually save just the video as only video is present in this page.

Friday, September 19, 2014

Google Summer of Code Project

https://www.dropbox.com/s/0azhjxjs15r3s8l/vivek_kumar_verma.zip?dl=0

Saturday, August 23, 2014

Access an exteral url using php curl

I will start will a working code:
<?php
$handle=curl_init('complete url here');
curl_setopt($handle, CURLOPT_VERBOSE, true);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$content = curl_exec($handle);

if(!curl_errno($handle))
{
    $info = curl_getinfo($handle);

    echo '<br/> Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}
else
{
    echo 'Curl error: ' . curl_error($handle);
}

echo $content;
?>


This will first initialize the handle. Then it is setting properties which will be used to access the webpage.
After that it is checking for errors,if any. And finally it is printing the obtained webpage.

This can be modified a little bit by setting url external to curl_init:

<?php

$ch=curl_init();
$url="url";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$curlresult=curl_exec($ch);
curl_close($ch);
echo $curlresult;

?>

Monday, June 23, 2014

Handle oracle cursor in java program

In my previous post, i explained how to create a cursor in pl/sql to be used in the java program.
In this post, i will be showing how to use a cursor inside a java program

First connection can be made using following string
dbConnection= DriverManager.getConnection(
                                                        "jdbc:oracle:thin:@host_name:port_name:sid/service_name", "user_id",
                                                        "password");

This connection can be used to call the function and get cursor reference:
CallableStatement cstmt = dbConnection.prepareCall("{? = call GetRefCursors1.sfGetAccountInterval1}");
after call package_name.function_name is given

cstmt.setFetchSize(500);
This statement will restrict the number of rows to be fetched by the cursor in one run
cstmt.registerOutParameter(1,OracleTypes.CURSOR);
This statement will set the return type as oracle cursor. After this cursor reference will be obtained.
cstmt.executeQuery();

ResultSet rs = (ResultSet)cstmt.getObject(1);
This will be used to traverse the cursor
Data can be obtained from the resultset in following manner:

rs.getInt("id");
rs.getString("from_email_address");
These can be used in any manner required.

Use cursor to fetch data in java

Suppose following table is present in the database:
Queue (id NUMBER(10),email1 VARCHAR2(100), email2 VARCHAR2(100),head VARCHAR2(200),body VARCHAR2(1000));


In the backend package can be defined as 

CREATE OR REPLACE PACKAGE GetRefCursors1 IS
TYPE csGetResultSet is REF CURSOR;
function sfGetAccountInterval1
return csGetResultSet;

end GetRefCursors1;


CREATE OR REPLACE package body GetRefCursors1 is
function sfGetAccountInterval1
return csGetResultSet is

csGetAccounts csGetResultSet;

begin

open csGetAccounts for

SELECT Queue.id,Queue.email1,Queue.email2,Queue.head,Queue.body
FROM Queue
ORDER BY Queue.id ;

return csGetAccounts;

end sfGetAccountInterval1;

end GetRefCursors1;

This function will return a cursor which can be used in the java program to access backend data

#Check next post to get handling of cursor in java program

Send mail using gmail SMTP server

First of all three libraries need to be added in the JDK
jaf-1_1_1.zip,
ojdbc6_g.jar and
javax.mail.jar

javax.mail.jar contains the mail server libraries

Complete working code for sending mail using gmail smtp server
===============================================
package com.javapapers.java;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JavaEmail {

  Properties emailProperties;
  Session mailSession;
  MimeMessage emailMessage;

  public static void main(String args[]) throws AddressException,
      MessagingException {

    JavaEmail javaEmail = new JavaEmail();

    javaEmail.setMailServerProperties();
    javaEmail.createEmailMessage();
    javaEmail.sendEmail();
  }

  public void setMailServerProperties() {

    String emailPort = "587";//gmail's smtp port

    emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.ssl.trust", "smtp.gmail.com");
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", "true");
    emailProperties.put("mail.smtp.starttls.enable", "true");

  }

  public void createEmailMessage() throws AddressException,
      MessagingException {
    String toEmails =  "complete_email_address_of_receiver" ;
    String emailSubject = "Java Email";
    String emailBody = "This is an email sent by <b>JavaMail</b> api.";//here we can add HTML syntax also

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

   // for (int i = 0; i < toEmails.length; i++) {
      emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails));
 //   }

    emailMessage.setSubject(emailSubject);
    emailMessage.setContent(emailBody, "text/html");//for a html email
    //emailMessage.setText(emailBody);// for a text email

  }

  public void sendEmail() throws AddressException, MessagingException {

    String emailHost = "smtp.gmail.com";
    String fromUser = "gmail_id_of_sender_without_@gmail.com";//just the id alone without @gmail.com
    String fromUserEmailPassword = "password_of_the_gmail_account";

    Transport transport = mailSession.getTransport("smtp");

    transport.connect(emailHost, fromUser, fromUserEmailPassword);
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    transport.close();
    System.out.println("Email sent successfully.");
  }

}



//Enjoy using gmail to make your own mail client

Sunday, August 18, 2013

Sphinx extension

Sphinx is a tool to provide a special feature for the documentation of a python project. It can used to test snippets in the documentation, to link to another project's documentation, to add links to highlighted source code, to generate autodoc summaries etc. These can be achieved by some of the inbuilt extensions of the sphinx. Sphinx also provide a facility of third party extension in which a user can write an extension for some specific purpose and can upload the extension in sphinx repository.

Understanding the working of sphinx project
Sphinx project is built in several phases.
In phase0, source files are searched from the source directory and initialization of extension takes place. In phase 1, parsing of the source file takes place leading to the formation of doctree(tree formation by the use of docutils). Separate nodes are created for the directives defined in the extension. In phase 2, the doctree is checked for the formation of proper nodes with proper tagname and classes. In phase 3, the temporary nodes created in phase 1 due to improper data are converted in to nodes which can be converted into output using the meta data obtained in phase 2. In phase 4, output is obtained in desired output format.

Steps in designing of sphinx extension
Basically sphinx extension consists of four main components: Directives, Treenodes, Config files and Event handlers.Each extension consists of a setup function which registers all of these components.
Treenodes can be defined by extending the docutil classes defined in docutils.node . These are the nodes of the doctree formed during step 1 of building of sphinx project. Directives can be derived from docutils.parsers.rst.Directives or sphinx.util.compat.Directives . Config files can be used to decide the behavior extension. Finally the event handler does the main function of the extension. There are a lot of phinx APIs which can be used while writing an extension. Those can be found from http://sphinx-doc.org/ext/appapi.html

Tuesday, July 9, 2013

Running robot tests from rst test files

Current rst parser of robotframework recognizes just the test cases in rst format inside the rest files.

To run the text cases in rst files, it has to be first extracted into a separate file and run using text parser.

The extraction can be done by two methods, either by using regex or by using docutils.

In implementation using regex, to detect the literal block, some prefix or suffix needs to be added so that it doesn't consider the statements after the literal blocks used in the statements as test cases.
 eg. in the following statement "Create an example ReST-file with multiple ``.. code:: robotframework``
   -parts and figure out," ".code::robotframework" is the literal block, but  " -parts and figure out," should not be confused with the test case.
Also an indication has to be made to inform that test case has ended.
So while using regex a lot of changes has to be made in the predefined format.

So on the safer side, docutils can be used to bring out the txt test cases. This can be done by forming the doctree using docutils. Then each nodes of  the doctree can be traversed to find if the tagname of the node is the desired literal block. If desired tagname is found at any node, the content of that node can be appended in a temporary file. After the completion of traversal, the temporary file contains all the txt test cases present in the rst file. This temporary file can be run using text parser of robot framework. 

Friday, June 21, 2013

Docutils Structure



DOCUTILS

Docutils is a python docstring processing system. It reads the statements from an input file parses the document and prints the output in a specified format. This is a tool which can be used to process restructured text. The structure of docutils is highly modular and well defined. It has got readers, parsers, transformers and writers.

Reader: Reader understand the input and sends the file to the parser. It sends the file to the parser as a whole or in chucks. If it uses the chuck form, it provides context so the the system can be consolidated again in a single form. It can read normal text format and rest format. It also recognizes FAQs and email.

Parser: It gets the input from the reader and construct document tree from the given input. At present only one parser has been implemented that is rest parser, other parsers are in the way of development.

Transformer: It is related to the formatting of the document tree. It can add to the tree, prune it, change from one form to another and many others. Some transformers are document.Splitter which splits the document into tree structure of sub-documents, document.Merger which combines multiple doctrees into one, parts.Content which generates a table of content for a document etc.

Writer: The writer produces the final output. The output can be in any one of many available formats. Some of the available formats are pdf, HTML, plain text restructured text etc.

Robot Framework test cases


Robotframeworks recognizes some well-defined patterns for it’s test cases. So test data should be entered in these special formats.
Following are the formats known by Robotframework:
n         HTML format
n        TSV format
n        Plain text (.txt) format
n        reStructured text format
HTML format: In HTML format test cases are written in tabular form. It has got separate tables for Settings, Variables, Test Cases and Keywords. The main problem with this format is that the tabular form becomes hectic sometimes as it is not very easy to format tables with normal text readers. In this form everything outside the table is ignored.
Eg
Setting
Value
Value
Value
Library
OperatingSystem







Variable
Value
Value
Value
${MESSAGE}
Hello, world!







Test Case
Action
Argument
Argument
My Test
[Documentation]
Example test


Log
${MESSAGE}


My Keyword
/tmp





Another Test
Should Be Equal
${MESSAGE}
Hello, world!

Keyword
Action
Argument
Argument
My Keyword
[Arguments]
${path}


Directory Should Exist
${path}






TSV format: In TSV format all the data is fed into one table which can be formatted using some spreadsheet programs. The test data are recognized by one or more asterisks followed by a normal table name and an optional closing asterisks. Still it is not preffered to use TSV format over normal text format.
Eg
*Setting*
*Value*
*Value*
*Value*
Library
OperatingSystem










*Variable*
*Value*
*Value*
*Value*
${MESSAGE}
Hello, world!










*Test Case*
*Action*
*Argument*
*Argument*
My Test
[Documentation]
Example test


Log
${MESSAGE}


My Keyword
/tmp





Another Test
Should Be Equal
${MESSAGE}
Hello, world!








*Keyword*
*Action*
*Argument*
*Argument*
My Keyword
[Arguments]
${path}


Directory Should Exist
${path}


Plain text format: This is the most popular data format for robot framework. In this format everything is similar to TSV format except the absence of table. In this content are separated by one or more spaces. This can be very easily edited by any normal text reader. In this the separator is space, so empty cells shouls be entered as ${empty} or /.

Eg 
*** Settings ***
Library       OperatingSystem

*** Variables ***
${MESSAGE}    Hello, world!

*** Test Cases ***
My Test
    [Documentation]    Example test
    Log    ${MESSAGE}
    My Keyword    /tmp

Another Test
    Should Be Equal    ${MESSAGE}    Hello, world!

*** Keywords ***
My Keyword
    [Arguments]    ${path}
    Directory Should Exist    ${path}

Restructured Text format: This is commonly used for the documentation of python projects. In this format simple formatted text is mixed with test tables and the complete file is recognized by robot frameworks. So text cases are embedded in the HTML format in the normal formatted document which are extracted while robot frameworks is parsing through the document. There is a tool called docutils which can easily process the restructured text. At present test cases in normal text format can’t be embedded in the reST file.
Eg
When the is in following format
 =========    ===============    ====================
Settings            Value                             Value
==========    ===============   =====================
Library               Selenium2Library
Test Setup          Open browser              about: browser=firefox
Test Teardown   Close all browsers
===========  ===============   ======================

============           ===================        =================
Test Cases                     Value                                         Value
============            ===================       =================
Plone.org is up              Go to                                          http://www.plone.org/
----------------------          ---------------------------------      ------------------------------
..                                    Capture page Screenshot            plone-org.png
============            ===================       =================

It gets converted by robotframeworks in the following format:
Settings
Value
Value
Library
Selenium2Library

Test Setup
Open browser
about: browser=firefox
Test Teardown
Close all browsers


Test Cases
Value
Value
Plone.org is up
Go to

Capture page Screenshot
plone-org.png

This will now run similar to html test case.