add

Friday, September 7, 2012

Simple XML parsing

Xml File
"
<methodResponse>
<params>
<param>
<value>
<struct>
<member>
<name>originTransactionID</name>
<value><string>102511650088881951</string></value>
</member>
<member>
<name>responseCode</name>
<value><i4>100</i4></value>
</member>
</struct>
</value>
</param>
</params
</methodResponse>"

PHP :
" $xml = new SimpleXMLElement($xml);
$items = $xml->xpath('/methodResponse/fault/value/struct/member/name');
                $firstArr=$this->objectsIntoArray($items[0]);//convert XML Object to Php Array


function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
$arrData = array();
// if input is object, convert into array
if (is_object($arrObjData)) {
$arrObjData = get_object_vars($arrObjData);
}

if (is_array($arrObjData)) {
foreach ($arrObjData as $index => $value) {
if (is_object($value) || is_array($value)) {
$value = objectsIntoArray($value, $arrSkipIndices); // recursive call
}
if (in_array($index, $arrSkipIndices)) {
continue;
}
$arrData[$index] = $value;
}
}
return $arrData;
}


"

Monday, July 9, 2012

Auto highlight text inside pre tags using jQuery

We use pre tags to display the embed codes and short URLs. We use pre tags because it formats the text inside the tags as we insert it, which is ideal for displaying code in particular. The thing is, people like to copy this code and they have to go to the awful bother of selecting all the text manually if they wish to copy the code or URL.

jQuery hack to auto select all the text inside the pre tags. The only complication with this appears to be a cross platform solution as each browser appears to have their own way of selecting text.

Internet Explorer uses createTextRange.
Opera and Firefox use createRange.
Safari uses DOMSelection.
So with a pre tag like (just click anywhere in the code)…


jQuery( document ).ready(function() {	
	jQuery( 'pre.code' ).click( function() {
		var refNode = $( this )[0];
		if ( $.browser.msie ) {
			var range = document.body.createTextRange();
			range.moveToElementText( refNode );
			range.select();
		} else if ( $.browser.mozilla || $.browser.opera ) {
			var selection = window.getSelection();
			var range = document.createRange();
			range.selectNodeContents( refNode );
			selection.removeAllRanges();
			selection.addRange( range );
		} else if ( $.browser.safari ) {
			var selection = window.getSelection();
			selection.setBaseAndExtent( refNode, 0, refNode, 1 );
		}
	} );
 	} );


here goes the code :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
jQuery( document ).ready(function() { jQuery( 'pre.code' ).click( function() {
var refNode = $( this )[0];
if ( $.browser.msie ) {
var range = document.body.createTextRange();
range.moveToElementText( refNode );
range.select();
} else if ( $.browser.mozilla || $.browser.opera ) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents( refNode );
selection.removeAllRanges();
selection.addRange( range );
} else if ( $.browser.safari ) {
var selection = window.getSelection();
selection.setBaseAndExtent( refNode, 0, refNode, 1 );
}
} );
  } );
</script>
</head>
<body>
<pre class='code'>jQuery( document ).ready(function() { jQuery( 'pre.code' ).click( function() {
var refNode = $( this )[0];
if ( $.browser.msie ) {
var range = document.body.createTextRange();
range.moveToElementText( refNode );
range.select();
} else if ( $.browser.mozilla || $.browser.opera ) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents( refNode );
selection.removeAllRanges();
selection.addRange( range );
} else if ( $.browser.safari ) {
var selection = window.getSelection();
selection.setBaseAndExtent( refNode, 0, refNode, 1 );
}
} );
  } );
</pre>
</body>
</html>

Wednesday, July 4, 2012

post a file using PHP to remote server without ftp


Recently I was working for a product where i have to post a file to a remote server where remote server dont allow outbout FTP.
And in this process i found a couple of methods to post file to server;

my required file was in Xml and have to post that xml to remote server where I can fetch that data
Its quite simple and easy method.

here are my findings

local file name : postfile.php
remote file name : receivexml.php

code for postfile.php


$thistext="<?xml version="1.0"?>
        <SERVICES>
          <serv1234>
                <short>1234</short>
                <isuser>0</isuser>
                <keyword>keyword</keyword>
                <table>wltable</table>
                <expiry>
                        <expiry_status>1</expiry_status>
                        <expiry_startdate>04-JUL-12</expiry_startdate>
                        <expiry_enddate>27-JUL-12</expiry_enddate>
                        <expiry_message>Expiry Message</expiry_message>
                </expiry>
             
          </serv1234>
        </SERVICES>";



$ch = curl_init('http://rem.ote.server.ip/receivexml.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $thistext);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/xml',
'Content-Length: ' . strlen($thistext)) );                                                                                                                  
$result = curl_exec($ch);
print_r($result);
curl_close($ch);

code for  receivexml.php


echo "test xml";
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
    $postText = file_get_contents('php://input');
}
//print_r($postText);
$shortcode='';
$xml = new SimpleXMLElement($postText);
$result = $xml->xpath('/SERVICES/ serv1234/short');
while(list( , $node) = each($result)) {
    echo $short=$node;
}
$myFile = "/directory/path/to/xml/".$short.".xml";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData=$postText;
fwrite($fh, $stringData);
fclose($fh);
?>

in receivexml.php
  1. received the file and stored in  $postText
  2. parsed the xml data with xpath
  3. set the file name to a tag value in this case "short"
  4. write data to file.


Wednesday, June 27, 2012

how to get the return code of a command


how to get the return code of a command??

you can get the retun code of a command using $? operator.Make sure to save the returncode in a variable just after the command completed.otherwise this will hold the code of the next command executed after your desired.
have a look
ncftpput -u user-name -p P@sswORD 192.168.168.9 / $filename
RET=$?
echo $RET


Thursday, June 21, 2012

Linux BASH - Comparison Operators


Linux BASH - Comparison Operators

 Integer Comparison Operators
OperatorDescriptionExample
-eqIs Equal Toif [ $1 -eq 200 ]
-neIs Not Equal Toif [ $1 -ne 1 ]
-gtIs Greater Thanif [ $1 -gt 15 ]
-geIs Greater Than Or Equal Toif [ $1 -ge 10 ]
-ltIs Less Thanif [ $1 -lt 5 ]
-leIs Less Than Or Equal Toif [ $1 -le 0 ]
==Is Equal Toif (( $1 == $2 )) [Note: Used within double parentheses]
!=Is Not Equal Toif (( $1 != $2 ))
<Is Less Thanif (( $1 < $2 ))
<=Is Less Than Or Equal Toif (( $1 <= $2 ))
>Is Greater Thanif (( $1 > $2 ))
>=Is Greater Than Or Equal Toif (( $1 >= $2 ))

 String Comparison Operators
OperatorDescriptionExample
= or ==Is Equal Toif [ "$1" == "$2" ]
!=Is Not Equal Toif [ "$1" != "$2" ]
>Is Greater Than (ASCII comparison)if [ "$1" > "$2" ]
>=Is Greater Than Or Equal Toif [ "$1" >= "$2" ]
<Is Less Thanif [ "$1" < "$2" ]
<=Is Less Than Or Equal Toif [ "$1" <= "$2" ]
-nIs Not Nullif [ -n "$1" ]
-zIs Null (Zero Length String)if [ -z "$1"]

Thursday, June 14, 2012

Shell Script for updating an Oracle table through a file (from a remote Server)


a simple Script for updating an Oracle table through a file (from a remote Server)
we will b using a shell script for all this
process is described step by step as
1. first Of all create a virtual directory and external table use this page http://eaziweb.blogspot.com/2012/03/oracle-create-external-table.html
2. get file from remote server using ncftpget
3. create Oracle Procedure for data insertions
4. Oracle Procedure uses  UTL_FILE utility for logging different file events like success and failure

Summary
Serrver : server IP like 192.168.168.0
directory Object Name : DIR_3352
directory Object Path : /home/xyz/3352
External File : xtern_3352.txt
Upload File Name Format : add_20120612.csv
Upload File Format : 03007236317,09-MAR-12,C2676M0749
External Table :
create table xtern_3352 ( mobile varchar2(100),dateCol varchar2(20),id varchar2(20))
organization external (
type oracle_loader
default directory DIR_3352
access parameters (
records delimited by newline
FIELDS TERMINATED BY ','
)
location ('xtern_3352.txt')
)
reject limit unlimited;
Procedure : TEST_PARAMETER


Shell Script :
######################################################################
##                                              USAGE                                                                         ##
##      call it as 3355.sh action-parameter                                                                          ##
##      eg. source 3355.sh add                                                                                          ##
##      current action parameters are                                                                                  ##
##      1.add                                                                                                                     ##
##      2.delete                                                                                                                  ##
######################################################################
#!/bin/sh
action=$1
day=1
date_var=`date -d "-$day days" +%Y-%m-%d`
#backup old files
mv -f /home/xyz/3352/xtern_3352.txt /home/xyz/3352/xtern_3352_`echo $date_var`.txt
#get the file from remote Server and put in /path/to/local/dir/ directory
ncftpget -u ftp-user-name -p paSSword rem.ote.Ser.ver.IP /path/to/local/dir/ /file`echo $date_var`_sub.csv
mv -f  /home/xyz/file`echo $date_var`_sub.csv  /home/xyz/new.txt
cat /home/xyz/new.txt | cut -d ' ' -f1> /home/xyz/xtern_3352.txt
source /file_validation_script.sh 3352/xtern_3352.txt
ORACLE_HOME=/Oracle/app/oracle/product/11.2.0/dbhome_1
export ORACLE_HOME
ORACLE_SID=orcl
export ORACLE_SID
/Oracle/app/oracle/product/11.2.0/dbhome_1/bin/sqlplus /NOLOG << EOF

connect db_user/db_pwd
set serveroutput on
exec TEST_PARAMETER('`echo $action`');
EXIT;
echo "Now making file"
EOF

Oracle Procedure : TEST_PARAMETER

 ( action IN varchar2 )
  AS CURSOR C_CONTENT IS SELECT * from xtern_3352 ;
--============================================================
-- --
-- Initialization --
--===========================================================--
datecheck number;
v_message varchar2(100);
ERROR_mobile_FORMAT exception;
ERROR_mobile_VALUE exception;
ERROR_DATE_VALUE exception;
ERROR_DUPLICATE_mobile exception;
ERROR_NO_mobile_FOUND  exception;
v_file  UTL_FILE.FILE_TYPE;
s_file  UTL_FILE.FILE_TYPE;
cur_date varchar2(100);
file_Name varchar2(100);
success_File_Name varchar2(100);
var_query varchar2(100);
--=============================================================--
-- --
--                        Start of Logic -- --                                                                   --
--=============================================================--
BEGIN

    -------------------------------------------------------------------------------------------
    --                       File details               --
    -------------------------------------------------------------------------------------------
  SELECT  to_char(sysdate, 'DDMonYYYY_HH24MISS') into cur_date from dual;
  file_Name := '' ;
  success_File_Name := '' ;
  if ( action = 'add') then
    dbms_output.put_line('add Action');
    file_Name := 'add_error_'||cur_date||'.txt' ;
    success_File_Name := 'add_success_'||cur_date||'.txt' ;
    --var_query := 'insert into WHITE_LIST_auto values('||wl_DATA.mobile||','||wl_DATA.dateCol||','||wl_DATA.ID||')' ;
    var_query := 'insert into WHITE_LIST_auto values(wl_DATA.mobile,wl_DATA.dateCol,wl_DATA.ID)' ;
  else if ( action = 'delete') then
    dbms_output.put_line('delete Action');
    file_Name := 'delete_error_'||cur_date||'.txt' ;
    success_File_Name := 'delete_success_'||cur_date||'.txt' ;
    var_query := 'delete from WHITE_LIST_auto where mobile=wl_DATA.mobile' ;
  else
    dbms_output.put_line('What do u want to do ??? Please Select an action (add or delete)');
    return;
 
    dbms_output.put_line('else Action');
    --return 'Please Select an action (add or delete)';
  end if;
  end if;

  SELECT  to_char(sysdate, 'DDMonYYYY_HH24MISS') into cur_date from dual;
  --file_Name := 'error_'||cur_date||'.txt' ;
  dbms_output.put_line('error is '|| file_Name);
  v_file := UTL_FILE.FOPEN(location     => 'dir_3352',
                           filename     => file_Name,
                           open_mode    => 'w',
                           max_linesize => 32767);
  --success_File_Name := 'success_'||cur_date||'.txt' ;
  dbms_output.put_line('success_File_Name is '|| success_File_Name);
  s_file := UTL_FILE.FOPEN(location     => 'dir_3352',
                           filename     => success_File_Name,
                           open_mode    => 'w',
                           max_linesize => 32767);

FOR wl_DATA in C_CONTENT
LOOP
  begin
    begin
    -------------------------------------------------------------------------------------------
    -- Error Validations      --
    -------------------------------------------------------------------------------------------
      if length(wl_DATA.mobile) <> 11 or substr(wl_DATA.mobile,0,2) <> '03' then
raise ERROR_mobile_FORMAT;
      else if  ( (LENGTH(TRIM(TRANSLATE(wl_DATA.mobile, '+0123456789',' '))) is not null)  ) then
raise ERROR_mobile_VALUE;
      else if (is_date(wl_DATA.dateCol, 'dd-mon-yy') = 0) then
raise ERROR_DATE_VALUE;
      else if (CHECK_WHITELIST(wl_DATA.mobile) = 1 and action = 'add') then
raise ERROR_DUPLICATE_mobile;
      else if (CHECK_WHITELIST(wl_DATA.mobile) = 0 and action = 'delete') then
raise ERROR_NO_mobile_FOUND;
      else
          -----------------------------------------------------------------------------
 -- Dumping Valid Data      --
 -----------------------------------------------------------------------------
 if ( action = 'add') then
   insert into WHITE_LIST_auto values(wl_DATA.mobile,wl_DATA.dateCol,wl_DATA.ID);
 else if ( action = 'delete') then
   delete from WHITE_LIST_auto where mobile=wl_DATA.mobile;
 else
   dbms_output.put_line('else Action');
   return;
   --return 'Please Select an action (add or delete)';
   end if;
   end if;
   
--dbms_output.put_line(var_query);
--execute immediate var_query ;
--insert into WHITE_LIST_auto values(wl_DATA.mobile,wl_DATA.dateCol,wl_DATA.ID);
UTL_FILE.PUT_LINE(s_file,wl_DATA.mobile|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID);
      end if;
      end if;
      end if;
      end if;
      end if;
      exception
          -----------------------------------------------------------------------------
 -- Exception Handling      --
 -----------------------------------------------------------------------------
        when ERROR_mobile_FORMAT then
          v_message:='Mobile number Format is invalid';
 UTL_FILE.PUT_LINE(v_file,wl_DATA.mobile|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);
        when ERROR_mobile_VALUE then
          v_message:='Mobile number is invalid';
 UTL_FILE.PUT_LINE(v_file,wl_DATA.mobile|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);
when ERROR_DATE_VALUE then
          v_message:='date is invalid';
 UTL_FILE.PUT_LINE(v_file,wl_DATA.mobile|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);
        when ERROR_DUPLICATE_mobile then
          v_message:='Duplictae mobile';
 UTL_FILE.PUT_LINE(v_file,wl_DATA.mobile|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);
        when ERROR_NO_mobile_FOUND then
          v_message:='No mobile Found';
 UTL_FILE.PUT_LINE(v_file,wl_DATA.mobile|| ',' ||wl_DATA.dateCol|| ',' ||wl_DATA.ID|| ',' ||v_message);
    end;
  end;
  END LOOP;
  UTL_FILE.FCLOSE(v_file);        
  UTL_FILE.FCLOSE(s_file);        
commit;

END;
--=============================================================
-- --
-- End of Logic --
-- =============================================================

Monday, June 11, 2012

oracle procedure : number validation

if ( (LENGTH(TRIM(TRANSLATE(contentcode, ‘+0123456789′,’ ‘))) is not null) or (LENGTH(TRIM(TRANSLATE(otherfield, ‘+0123456789′,’ ‘))) is not null)) then
dbms_output.put_line(‘contentcode or otherfield is invalid’);