Script to restart Tomcat in Windows


The first code
I was trying to implement a script to restart Tomcat Server without need to be aware if stopped.
My first Script was this:

restart_tomcat.bat

@echo off
set "CATALINA_HOME=C:\ServerWeb\Tomcat"
set "STOP=%CATALINA_HOME%\bin\shutdown.bat"
set "START=%CATALINA_HOME%\bin\startup.bat"
@echo on
call %STOP%
timeout /t 2
call %START%
timeout /t 2

restart_tomcat
But really, this script doesn’t work like I want.
The problem, is that this script doesn’t test the Tomcat state.
The call process to Stop it, and the Timeout really isn’t proper to wait if Tomcat was stopped.
This my first code and worst, because this method does not consider or take into account the speed of the computer (processor, memory and running processes) and the time it takes to execute.

Service or Process

Another thing that should be considered is how the Tomcat server is executing, like Process or like Service…
Other mistake was to considere Tomcat always is runnig like Service.

check_running.bat

@echo off
cls
setlocal enableextensions disabledelayedexpansion
set "serviceName="
set "SERVICE=Tomcat"
for /f "tokens=2" %%s in ('sc query state^= all ^| find /I "%SERVICE%"') do (
  set "serviceName=%%s"
)
 
 
sc query %serviceName%| find /i "RUNNING"> NUL
if not ERRORLEVEL 1 (
  echo %SERVICE% is running
  goto :end0
) else (
  echo %SERVICE% is not running
  goto :end0
)
:end0
 
 
sc query type= service state= inactive| find "%serviceName%"> NUL
if not ERRORLEVEL 1 (
  echo %SERVICE% is not running
  goto :end1
) else (
  echo %SERVICE% is running
  goto :end1
)
 
 
sc query type= service | find "%serviceName%"> NUL
if not ERRORLEVEL 1 (
  echo %SERVICE% is running
  goto :end2
) else (
  echo %SERVICE% is not running
  goto :end2
)
:end2
 
 
set "SERVICE=Tomcat"
tasklist /FI "SessionName eq services" | find /I "%SERVICE%" | find /I ".exe"> NUL
if not ERRORLEVEL 1 (
  echo %SERVICE% is running
  goto :end3
) else (
  echo %SERVICE% is not running
  goto :end3
)
:end3

Obviously this code is not debugged.

Only Checking Service
Acording to this, the Server Tomcat is not running, yes it is not running like Service.

Checking Port
But, as you can see the tomcat port is being used. Then the Server Tomcat is running like Process.

Checking the Tomcat port
Now, lets go to check who using the Tomcat port, I made my script:

check_running.bat

@echo off
 
if "x%1x" == "xx" goto displayUsage
set numberPort=%1
rem unusedPort flag to verify if PID was exploiter of required Port.
set "unusedPort="
rem lastPID avoid repeat PID
set "lastPID="
rem netstat -nao | find /i ":8080 " | find /i "LISTENING"
for /f "delims=" %%s in ('netstat -nao ^| find /i ":%numberPort% " ^| find /i "LISTENING"') do (
  rem Separate Connections using required port
  rem   TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       1960
  for /f "tokens=2" %%# in ("%%s") do (
    rem Separate Local Address
    rem 0.0.0.0:80
    echo.%%# | findstr /C:":%numberPort% " 1> nul
    if not ERRORLEVEL 1 (
      for /f "tokens=5" %%p in ("%%s") do (
        rem Separate PID
        rem 1960
        rem tasklist /fi "pid eq %%p"
        set "unusedPort=false"
        rem if not defined lastPID (
        rem if not "%%p"=="%lastPID%" (
        if not defined lastPID (
          set "lastPID=%%p"
          2>nul Wmic service where "ProcessId like '%%p'" get Name, PathName, ProcessId, State| findstr /i "Name"> nul
          if ERRORLEVEL 1 (
            rem echo %%p is a process using the Port %numberPort%!
            for /f "skip=3 delims=1" %%i in ('tasklist /fi "pid eq %%p"') do (
              for /f "tokens=1" %%n in ("%%i") do (
                echo The %numberPort% port is being used with PID %%p by %%n process:
              )
            )
            Wmic process where "ProcessId like '%%p'" get Name
          ) else (
            for /f "skip=3 delims=1" %%i in ('tasklist /fi "pid eq %%p"') do (
              for /f "tokens=1" %%n in ("%%i") do (
                echo The %numberPort% port is being used with PID %%p by %%n service:
              )
            )
            rem echo %%p is a service using the Port %numberPort%!
            Wmic service where "ProcessId like '%%p'" get Name, PathName, State
          )
        )
      )
    )
  )
)
 
netstat -nao | find /i ":%numberPort% "> nul
if ERRORLEVEL 1 (
  echo The %numberPort% port is not being used in Local Address.
) else (
  if not defined unusedPort (
    echo The %numberPort% port is not being used in Local Address.
  )
)
goto :end
 
:displayUsage
echo.
echo Usage: %~n0.bat [port]
 
 
:end
 
timeout /t 2

Testing my script I can see “who” is using the 8080 Port, and is javaw.exe like Process.
ExploiterPort 8080 Process

Starting Server Tomcat like Console:
StartingTomcat_Console_TS
ExploiterPort 8080 Tomcat_Console_TS

I turn off, the process manually.
ExploiterPort 8080 Unused

Starting Server Tomcat like Service manually and testing.
ExploiterPort 8080 Service

My Script is useful to check another port, like 80 for Httpd or another port.
ExploiterPort 80 Service

With this clear and after analyzing the behavior to start or stop the Tomcat server, such as service or process, I made my new script.

restart_tomcat.bat

@echo off
setlocal
set "CATALINA_HOME=C:\ServerWeb\Tomcat"
set "DELLOGS=%CATALINA_HOME%\logs\*.log"
set "DELTXTS=%CATALINA_HOME%\logs\*.txt"
set "DELALLS=%CATALINA_HOME%\logs\*.*"
rem  C:\ServerWeb\Tomcat\bin\tomcat7.exe //SS//Tomcat7.0.50
set "STOP=%CATALINA_HOME%\bin\shutdown.bat"
rem  C:\ServerWeb\Tomcat\bin\tomcat7.exe //RS//Tomcat7.0.50  (Doesn't work!)
set "START=%CATALINA_HOME%\bin\startup.bat"
 
 
set "serviceCheck=Tomcat"
rem serviceCheck: Tomcat7 or Tomcat8
set "processCheck=Tomcat"
rem processCheck: tomcat7.exe or tomcat8.exe
set "executorPort=8080"
set "shutdownPort=8005"
 
set "serviceName="
set "serviceRunning="
set "processPID="
 
if "x%1x" == "xx" goto beginRestart
set firstArg=%1
if "x%2x" == "xx" goto check_firstArg
set secndArg=%2
 
set "deleting="
set "bverbose="
 
rem Only 2 arguments are allowed
if not "x%3x" == "xx" goto displayUsage
 
if %firstArg% == %secndArg% goto displayUsage
 
:check_secndArg
if "%secndArg%" == "dellogs" (
  set deleting=%secndArg%
) else (
  if "%secndArg%" == "verbose" (
    set "bverbose=%secndArg%"
  ) else (
    goto displayUsage
  )
)
:check_firstArg
if "%firstArg%" == "dellogs" (
  set "deleting=%firstArg%"
) else (
  if "%firstArg%" == "verbose" (
    set "bverbose=%firstArg%"
  ) else (
    goto displayUsage
  )
)
 
:beginRestart
call :getServiceName
if defined serviceName (
  rem call :checkServiceRunning
  call :serviceAvailableStop
  if defined serviceRunning (
    rem the service is running, stop the service
    if defined bverbose (
      echo.
      echo Stopping %serviceCheck%, like %serviceName% service...
      echo.
    )
    call :getPID
    call :Restarting
  ) else (
    rem the service was not running, trying with the port like process
    call :getPID
    if defined processPID (
      for /f "delims=" %%i in ('netstat -nao ^| find /i ":%executorPort% " ^| find /i "LISTENING"') do (
        for /f "tokens=2" %%o in ("%%i") do (
          echo.%%o | findstr /C:":%executorPort% " 1>nul
          if not ERRORLEVEL 1 (
            for /f "tokens=5" %%u in ("%%i") do (
              if defined bverbose (
                echo.
                echo Stopping the %serviceCheck% like %%u PID process...
                echo.
              )
            )
          )
        )
      )
      call :Restarting
    ) else (
      if defined bverbose (
        echo.
        echo %serviceCheck% was not running.
        echo.
      )
      call :Starting
    )
  )
)
 
 
:getServiceName
rem To obtain the real (exact) name of service.
for /f "tokens=2" %%s in ('sc query state^= all ^| find /I "%serviceCheck%"') do (
  set "serviceName=%%s"
)
exit /b 0
 
 
:checkServiceRunning
rem To check if real service is running...
if defined serviceName (
  sc query %serviceName%| find /i "RUNNING">nul
  if not ERRORLEVEL 1 (
    rem service was found running
    set "serviceRunning=%serviceName%"
  )
)
exit /b 0
 
 
:serviceAvailableStop
tasklist /FI "SessionName eq services" | find /I "%processCheck%" | find /I ".exe">nul
if not ERRORLEVEL 1 (
  rem %processCheck% is running, is needed if shutdown port is available
  netstat -nao | find /i ":%shutdownPort% " | find /i "LISTENING">nul
  if not ERRORLEVEL 1 (
    set "serviceRunning=%serviceName%"
    exit /b 0
  ) else (
    rem service was found running, but is not available to stop
    goto :serviceAvailableStop
  )
) else (
  rem verify is starting
  sc query %serviceName%| find /i "START_PENDING">nul
  if not ERRORLEVEL 1 (
    rem service was found starting
    goto :serviceAvailableStop
  )
  rem verify is running
  sc query %serviceName%| find /i "RUNNING">nul
  if not ERRORLEVEL 1 (
    rem service was found running
    goto :serviceAvailableStop
  )
)
exit /b 0
 
:serviceIsOff
rem Wait until Service ends
tasklist /FI "SessionName eq services" | find /I "%processCheck%" | find /I ".exe">nul
if ERRORLEVEL 1 (
  sc query %serviceName%| find /i "STOPPED">nul
  if not ERRORLEVEL 1 (
    netstat -nao | find /i ":%executorPort% " | find /i "LISTENING">nul
    if ERRORLEVEL 1 (
      exit /b 0
    )
  )
)
ping 127.0.0.1 -n 1 >nul 2>&1 || PING ::1 -n 1 >nul 2>&1
goto :serviceIsOff
 
:processIsOff
netstat -nao | find /i ":%executorPort% " | find /i "LISTENING">nul
if ERRORLEVEL 1 (
  exit /b 0
)
ping 127.0.0.1 -n 1 >nul 2>&1 || PING ::1 -n 1 >nul 2>&1
goto :processIsOff
 
 
:serviceIsOn
rem Wait until service starts completely
sc query %serviceName%| find /i "RUNNING">nul
if not ERRORLEVEL 1 (
  netstat -nao | find /i ":%executorPort% " | find /i "LISTENING">nul
  if not ERRORLEVEL 1 (
    netstat -nao | find /i ":%shutdownPort% " | find /i "LISTENING">nul
    if not ERRORLEVEL 1 (
      exit /b 0
    )
  )
)
ping 127.0.0.1 -n 1 >nul 2>&1 || PING ::1 -n 1 >nul 2>&1
goto :serviceIsOn
 
 
:processIsOn
rem Wait until process starts completely
netstat -nao | find /i ":%executorPort% " | find /i "LISTENING">nul
if not ERRORLEVEL 1 (
  netstat -nao | find /i ":%shutdownPort% " | find /i "LISTENING">nul
  if not ERRORLEVEL 1 (
    exit /b 0
  )
)
ping 127.0.0.1 -n 1 >nul 2>&1 || PING ::1 -n 1 >nul 2>&1
goto :processIsOn
 
:getPID
rem Obtain the PID of process using the 8080 port
set "intPID="
for /f "delims=" %%s in ('netstat -nao ^| find /i ":%executorPort% " ^| find /i "LISTENING"') do (
  for /f "tokens=2" %%# in ("%%s") do (
    echo.%%# | findstr /C:":%executorPort% " 1>nul
    if not ERRORLEVEL 1 (
      for /f "tokens=5" %%p in ("%%s") do (
        if not defined intPID (
          set intPID=%%p
          goto stopGetPID
        )
      )
    )
  )
)
:stopGetPID
set "processPID=%intPID%"
exit /b 0
 
 
:Restarting
rem if process or services is running, then call stop
rem after wait until 8080 TIME_WAIT was finished,
rem later call process to start again
 
rem avoid call STOP if server is starting then wait...
 
if defined serviceRunning (
  call :serviceIsOn
  if defined bverbose (
    net session>nul 2>&1
    if not ERRORLEVEL 1 (
      net stop %serviceName%
    ) else (
      call %STOP%
    )
  ) else (
    call %STOP%>nul
  )
  call :serviceIsOff
  call :processIsOff
  if defined bverbose (
    echo.
    echo The %serviceCheck% like %serviceName% service was stopped.
    echo.
  )
) else (
  call :processIsOn
  if defined bverbose (
    call %STOP%
  ) else (
    call %STOP%>nul
  )
  call :serviceIsOff
  call :processIsOff
  if defined bverbose (
    echo.
    echo The %serviceCheck% with %processPID% PID was stopped.
    echo.
  )
)
 
call :Starting
goto:eof
 
 
:Starting
rem The Start process or service take a time, this in charge to do it.
rem before check if deleted logs file is requested
if not defined deleting goto nodellogs
if defined bverbose (
  echo Deleting the log files...
  echo.
)
del %DELALLS% /q
:nodellogs
net session>nul 2>&1
if not ERRORLEVEL 1 (
  if defined bverbose (
    echo Starting the %serviceCheck% service...
    echo.
    net start %serviceName%
  ) else (
    net start %serviceName%>nul
  )
  call :serviceIsOn
  if defined bverbose (
    echo.
    echo The %serviceCheck% was started like %serviceName% service.
  )
) else (
  if defined bverbose (
    echo Starting the %serviceCheck% process...
    echo.
    call %START%
  ) else (
    call %START%>nul
  )
  call :processIsOn
  set "processPID="
  call :getPID
  if defined bverbose (
    echo.
    echo The %serviceCheck% was started like process with %processPID% PID.
  )
)
goto:eof
 
 
:displayUsage
echo.
echo Usage: %~n0.bat [dellogs] [verbose]
 
 
:end

I included two optional arguments:
[dellogs] to delete all files of \logs subdirectory of Tomcat’s folder, useful when you want to see clean start or stop of Tomcat.
[verbose] to show greater information of process stop and start of Tomcat.

Testing my code:

RestartingTomcat

Now lets go make test in quietly manner.

RestartingTomcatAndCheckingPort

Running my script like Administrator, I can Stop and Start Tomcat like Service:
RestartingTomcat_Service

After of Stop Tomcat manually, I run this Script without Delete log files:
StartingTomcat_ServiceLikeAdministrator_NoDeleting
Now, with this We finished with my post of Tomcat’s restart.

I like your comments about this post.

Bye.

Anuncios
Publicado en Scripts, Server, Software, Tomcat, Web Server, Windows | Etiquetado , , , | Deja un comentario

Working RTF, HTML, CSS and Script Files with my own Packages Java and PHP


A while ago I explained my scripts (JSP and PHP) to handle RTF files, now I will show my built packages (Java and PHP) that include how to handle RTF, HTML, CSS and Script Files basically.
First you need to obtain my packages (Java or PHP)
bz-htmlcss2rtf.zip This zip file contains bz-htmlcss2rtf.jar and bz-htmlcss2rtf.phar and files used in this example.
The Java package can be used with Servlet or JSP scripts, my example for simplicity purpose will be in JSP scripts, you can to adapt it to Servlet.

I made two scripts to show you my examples both in JSP and PHP languages.

First Code – DBPer.xxp

DBPer.jsp

<%@page import="java.sql.*"%><%@page import="static bz.htmlcss2rtf.Ini.*"%>
<%@page import="bz.htmlcss2rtf.*"%><%@page errorPage ="error.jsp"%><%  
  try {
    setPageContext(pageContext);
    String webFile = getNameScript();
    
    CSS CSSFile = new CSS("CSS0");  //Name
    
    CSSFile.addInputStyle("Boton"," background-color:rgb(255,255,255); color:rgb(0,0,0);"
        +" cursor:pointer; width:150px; padding:1px; border-width:4px;"
        +" border-color:rgb(127,127,127); border-style:double; margin:1px; font-size: 8pt;"
        +" font-family: Courier;");//Boton
    CSSFile.addInputPseudoStyle("Boton","hover"," background-color:rgb(0,0,0);"
        +" color:rgb(255,255,255); font-weight:bold;");
    CSSFile.addInputPseudoStyle("Boton","disabled"," background-color:rgb(200,200,200);"
        +" color:rgb(64,64,64);");
    CSSFile.addDivStyle("Mssg"," background-color:rgb(220,220,220); position:absolute;"
        +" padding-top: 4px; padding-bottom: 4px; padding-left: 4px; border-style:double;"
        +" font-size:13px; text-shadow: rgb(255,255,255) 2px 2px; Width:37%; left:62%;"
        +" top:2%; z-index:1;");//Mssg
    CSSFile.addBodyStyle("Bod1","color:#7F7F7F;");
    
    HTMLFile MsgFl = new HTMLFile("MsgFl","Messages","0");  //Name,[Title],[Charset_#]
    MsgFl.setCSSObject(CSSFile);
    MsgFl.setShortCutIcon("BZ.ico");
    
    String StrMessg = "";
    
    String mHost = "192.168.97.21";
    String mUser = "root";
    String mPass = "MyPassword";
    
    String newHost = "%";  // or "localhost";
    String newUser = "dbUser";
    String newPass = "dbKey";
    String newDB = "dbCompany";
    
    setSessionObj("newUser",newUser);
    setSessionObj("newPass",newPass);
    setSessionObj("newDB",newDB);
    
    String FindDB = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA"
        +" WHERE SCHEMA_NAME = '"+newDB+"';";
    String CreateDB = "CREATE DATABASE "+newDB+";";
    String DeleteDB = "DROP DATABASE IF EXISTS "+newDB+";";
    String UseDB = "USE "+newDB+";";
    String CreateTbl = "CREATE TABLE tblRecords (FirsLastName varchar(30),"
        +"Salary int(11),JoinDate DATE,Photo MEDIUMBLOB,Resume MEDIUMTEXT);";
    String CreateUser = "CREATE USER '";
    String DropUser = "DROP USER '";
    String GrantAll = "GRANT ALL ON ";
    String Atsign = "'@'";
    String Identified = "' IDENTIFIED BY '";
    String FlushPriv = "FLUSH PRIVILEGES;";
    String CreatingUser = CreateUser+newUser+Atsign+newHost+Identified+newPass+"';";
    String GrantOverDB = GrantAll+newDB+".* TO '"+newUser+Atsign+newHost+"';";
    
    Connection conn = newMySQLConn(mHost,mUser,mPass); //Host,User,Pass,[DB],[Port]
    setConnection(conn);
    ResultSet result = doQry(FindDB);  //Peek for Database
    
    if (qtyQry(result) < 1) {
      if(getRequestStr("bCrtDB") != null) {
        try {
          doQry(CreateDB);
          doQry(UseDB);
          doQry(CreateTbl);
          doQry(CreatingUser);
          doQry(GrantOverDB);
          doQry(FlushPriv);
        } catch (Exception e) {
          StrMessg += "Error: "+e.getMessage();
        }
        StrMessg += "The '"+newDB+"' database has been created...<br>";
        
        HTMLFile gtFl = new HTMLFile("gtFl","create","0");  //Name,[Title],[Charset_#]
        gtFl.setCSSObject(CSSFile);
        gtFl.setShortCutIcon("BZ.ico");
        
        HTMLForm gtFr = new HTMLForm("Etiq","Form",HTMLForm.FORM_POSTMULTIPART,
            "PersEng.jsp");  //Name,FormID,Method,[Action]
        gtFr.setCSSObject(CSSFile);
        
        gtFl.addScriptPiece("FisrtScript","text/javascript");  //Name,Type
        gtFl.addScriptLine("FisrtScript","var myVar=\"hello\";");  //Name,Line
        gtFl.addScriptLine("FisrtScript","function showAlert() { alert('My alert!'); }");
        
        gtFr.addInput("bgtPE",HTMLForm.INPUT_SUBMIT,"PersEng.jsp",
            "Boton","");  //Name,Type,Value(TextToShow),Style,Argument0,[Argument1]
        String insertButton = gtFr.getInput("bgtPE");  //Name,[...Events]
        gtFr.addElement(insertButton);  //insert the button to the Form
        String insertForm = gtFr.getForm();  
        gtFl.addElement(insertForm);  //insert the form to the File
        String insertMessage = gtFl.getNewDiv(StrMessg,"Mssg"); //Content,[Style]
        gtFl.addElement(insertMessage);
        gtFl.closeFile();
        String insertFile = gtFl.getFile("Bod1"); //[Style]
        printSng(insertFile); //PrintSingle(TextToShow)
      } else {
        HTMLFile CrtFl = new HTMLFile("CreateDBFile","create","0");
        CrtFl.setCSSObject(CSSFile);
        CrtFl.setShortCutIcon("BZ.ico");
        HTMLForm CrtFr = new HTMLForm("Etiq","Form",
            HTMLForm.FORM_POST);  //Name,FormID,Method,[Action]
        CrtFr.setCSSObject(CSSFile);
        CrtFr.addInput("bCrtDB",HTMLForm.INPUT_SUBMIT,"Create DB","Boton","");
        CrtFr.addElement(CrtFr.getInput("bCrtDB"));
        CrtFl.addElement(CrtFr.getForm());
        CrtFl.addElement(CrtFl.getNewDiv(StrMessg,"Mssg"));
        CrtFl.closeFile();
        printSng(CrtFl.getFile("Bod1"));
      }
    } else {
      if(getRequestStr("bDelDB") != null) {
        StrMessg = "";
        String DropAdmins = DropUser+newUser+Atsign+newHost+"';";
        doQry(DropAdmins);
        int RDropDB = doQry(DeleteDB);
        if(RDropDB != 0) {
          StrMessg += "The '"+newDB+"' database has been deleted...<br>";
          MsgFl.resetFile();
          MsgFl.addElement(MsgFl.getNewDiv(StrMessg,"Mssg"));
          MsgFl.closeFile();
          printSng(MsgFl.getFile("Bod1"));
        }
      } else {
        HTMLFile DelFl = new HTMLFile("UserFile","delete","0");
        DelFl.setCSSObject(CSSFile);
        DelFl.setShortCutIcon("BZ.ico");
        
        HTMLForm DelFr = new HTMLForm("Etiq","Form",HTMLForm.FORM_POST);
        DelFr.setCSSObject(CSSFile);
        DelFr.addInput("bDelDB",HTMLForm.INPUT_SUBMIT,"Borrar DB","Boton","");
        DelFr.addElement(DelFr.getInput("bDelDB"));
        
        DelFr.addInput("bgtPE",HTMLForm.INPUT_SUBMIT,"PersEng.jsp","Boton","");
        DelFr.addFormEvent("bgtPE","PersEng","onClick","PersEng.jsp");
        DelFr.addElement(DelFr.getInput("bgtPE","PersEng"));
        DelFl.addElement(DelFr.getForm());
        DelFl.addElement(DelFl.getNewDiv(StrMessg,"Mssg"));
        DelFl.closeFile();
        printSng(DelFl.getFile("Bod1"));
      }
    }
    result.close();
    conn.close();
  }
  catch (Exception e) {
    printErr(e.getMessage());
  }
%>

DBPer.php

<?php
  namespace bz\htmlcss2rtf;
  require_once("phar://bz-htmlcss2rtf.phar/HTMLFile.php");
  require_once("phar://bz-htmlcss2rtf.phar/HTMLTable.php");
  require_once("phar://bz-htmlcss2rtf.phar/HTMLForm.php");
  require_once("phar://bz-htmlcss2rtf.phar/RTFFile.php");
  require_once("phar://bz-htmlcss2rtf.phar/RTFTable.php");
  require_once("phar://bz-htmlcss2rtf.phar/RTFImage.php");
  require_once("phar://bz-htmlcss2rtf.phar/Ini.php");
  require_once("phar://bz-htmlcss2rtf.phar/CSS.php");
  require_once("error.php");
  use Exception;
  try {
    $WebFile = getNameScript();
    
    $CSSFile = new CSS("CSS0");  //Name
    
    $CSSFile->addInputStyle("Boton"," background-color:rgb(255,255,255); color:rgb(0,0,0);"
        ." cursor:pointer; width:150px; padding:1px; border-width:4px;"
        ." border-color:rgb(127,127,127); border-style:double; margin:1px; font-size: 8pt;"
        ." font-family: Courier;");//Boton
    $CSSFile->addInputPseudoStyle("Boton","hover"," background-color:rgb(0,0,0);"
        ." color:rgb(255,255,255); font-weight:bold;");
    $CSSFile->addInputPseudoStyle("Boton","disabled"," background-color:rgb(200,200,200);"
        ." color:rgb(64,64,64);");
    $CSSFile->addDivStyle("Mssg"," background-color:rgb(220,220,220); position:absolute;"
        ." padding-top: 4px; padding-bottom: 4px; padding-left: 4px; border-style:double;"
        ." font-size:13px; text-shadow: rgb(255,255,255) 2px 2px; Width:37%; left:62%;"
        ." top:2%; z-index:1;");//Mssg
    $CSSFile->addBodyStyle("Bod1","color:#7F7F7F;");
    
    $MsgFl = new HTMLFile("MsgFl","Messages","0");  //Name,[Title],[Charset_#]
    $MsgFl->setCSSObject($CSSFile);
    $MsgFl->setShortCutIcon("BZ.ico");
    
    $StrMessg = "";
    
    $mHost = "192.168.97.21";
    $mUser = "root";
    $mPass = "MyPassword";
    
    $newHost = "%";  // or "localhost";
    $newUser = "dbUser";
    $newPass = "dbKey";
    $newDB = "dbCompany";
    session_start();
    setSessionObj("newUser",$newUser);
    setSessionObj("newPass",$newPass);
    setSessionObj("newDB",$newDB);
    
    $FindDB = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA"
        ." WHERE SCHEMA_NAME = '".$newDB."';";
    $CreateDB = "CREATE DATABASE ".$newDB.";";
    $DeleteDB = "DROP DATABASE IF EXISTS ".$newDB.";";
    $UseDB = "USE ".$newDB.";";
    $CreateTbl = "CREATE TABLE tblRecords (FirsLastName varchar(30),"
        ."Salary int(11),JoinDate DATE,Photo MEDIUMBLOB,Resume MEDIUMTEXT);";
    $CreateUser = "CREATE USER '";
    $DropUser = "DROP USER '";
    $GrantAll = "GRANT ALL ON ";
    $Atsign = "'@'";
    $Identified = "' IDENTIFIED BY '";
    $FlushPriv = "FLUSH PRIVILEGES;";
    $CreatingUser = $CreateUser.$newUser.$Atsign.$newHost.$Identified.$newPass."';";
    $GrantOverDB = $GrantAll.$newDB.".* TO '".$newUser.$Atsign.$newHost."';";
    
    $conn = newMySQLConn($mHost,$mUser,$mPass); //Host,User,Pass,[DB],[Port]
    setConnection($conn);
    $result = doQry($FindDB);  //Peek for Database
    
    if (qtyQry($result) < 1) {
      if(getRequestStr("bCrtDB") != NULL) {
        try {
          doQry($CreateDB);
          doQry($UseDB);
          doQry($CreateTbl);
          doQry($CreatingUser);
          doQry($GrantOverDB);
          doQry($FlushPriv);
        } catch (Exception $e) {
          $StrMessg .= "Error: ".$e.getMessage();
        }
        $StrMessg .= "The '".$newDB."' database has been created...<br>";
        
        $gtFl = new HTMLFile("gtFl","create","0");  //Name,[Title],[Charset_#]
        $gtFl->setCSSObject($CSSFile);
        $gtFl->setShortCutIcon("BZ.ico");
        
        $gtFr = new HTMLForm("Etiq","Form",HTMLForm::FORM_POSTMULTIPART,
            "PersEng.php");  //Name,FormID,Method,[Action]
        $gtFr->setCSSObject($CSSFile);
        
        $gtFl->addScriptPiece("FisrtScript","text/javascript");  //Name,Type
        $gtFl->addScriptLine("FisrtScript","var myVar=\"hello\";");  //Name,Line
        $gtFl->addScriptLine("FisrtScript","function showAlert() { alert('My alert!'); }");
        
        $gtFr->addInput("bgtPE",HTMLForm::INPUT_SUBMIT,"PersEng.php",
            "Boton","");  //Name,Type,Value(TextToShow),Style,Argument0,[Argument1]
        $insertButton = $gtFr->getInput("bgtPE");  //Name,[...Events]
        $gtFr->addElement($insertButton);  //insert the button to the Form
        $insertForm = $gtFr->getForm();  
        $gtFl->addElement($insertForm);  //insert the form to the File
        $insertMessage = $gtFl->getNewDiv($StrMessg,"Mssg"); //Content,[Style]
        $gtFl->addElement($insertMessage);
        $gtFl->closeFile();
        $insertFile = $gtFl->getFile("Bod1"); //[Style]
        printSng($insertFile); //PrintSingle(TextToShow)
      } else {
        $CrtFl = new HTMLFile("CreateDBFile","create","0");
        $CrtFl->setCSSObject($CSSFile);
        $CrtFl->setShortCutIcon("BZ.ico");
        $CrtFr = new HTMLForm("Etiq","Form",
            HTMLForm::FORM_POST);  //Name,FormID,Method,[Action]
        $CrtFr->setCSSObject($CSSFile);
        $CrtFr->addInput("bCrtDB",HTMLForm::INPUT_SUBMIT,"Create DB","Boton","");
        $CrtFr->addElement($CrtFr->getInput("bCrtDB"));
        $CrtFl->addElement($CrtFr->getForm());
        $CrtFl->addElement($CrtFl->getNewDiv($StrMessg,"Mssg"));
        $CrtFl->closeFile();
        printSng($CrtFl->getFile("Bod1"));
      }
    } else {
      if(getRequestStr("bDelDB") != NULL) {
        $StrMessg = "";
        $DropAdmins = $DropUser.$newUser.$Atsign.$newHost."';";
        doQry($DropAdmins);
        $RDropDB = doQry($DeleteDB);
        if($RDropDB != 0) {
          $StrMessg .= "The '".$newDB."' database has been deleted...<br>";
          $MsgFl->resetFile();
          $MsgFl->addElement($MsgFl->getNewDiv($StrMessg,"Mssg"));
          $MsgFl->closeFile();
          printSng($MsgFl->getFile("Bod1"));
        }
      } else {
        $DelFl = new HTMLFile("UserFile","delete","0");
        $DelFl->setCSSObject($CSSFile);
        $DelFl->setShortCutIcon("BZ.ico");
        
        $DelFr = new HTMLForm("Etiq","Form",HTMLForm::FORM_POST);
        $DelFr->setCSSObject($CSSFile);
        $DelFr->addInput("bDelDB",HTMLForm::INPUT_SUBMIT,"Borrar DB","Boton","");
        $DelFr->addElement($DelFr->getInput("bDelDB"));
        
        $DelFr->addInput("bgtPE",HTMLForm::INPUT_SUBMIT,"PersEng.php","Boton","");
        $DelFr->addFormEvent("bgtPE","PersEng","onClick","PersEng.php");
        $DelFr->addElement($DelFr->getInput("bgtPE","PersEng"));
        $DelFl->addElement($DelFr->getForm());
        $DelFl->addElement($DelFl->getNewDiv($StrMessg,"Mssg"));
        $DelFl->closeFile();
        printSng($DelFl->getFile("Bod1"));
      }
    }
    $result->close();
    $conn->close();
  }
  catch (Exception $e) {
    printErr($e->getMessage().":".$e->getFile().":".$e->getLine());
  }
?>

This code displays four pages, depending on the status of a MySQL database if not exists then create it, if there is then given the opportunity to operate it or delete it.

When DbCompany not exist.
DBPers.jsp - create
DBPers.php - create

When DbCompany created.
DBPers.jsp - created
DBPers.php - created

When DbCompany there may be operated or removed.
DBPers.jsp - delete
DBPers.php - delete

When DbCompany has been removed.
DBPers.jsp - deleted
DBPers.php - deleted

Second Code – PersEng.xxp

PersEng.jsp

<%@page import="static bz.htmlcss2rtf.Ini.*"%><%@page import="bz.htmlcss2rtf.*"%>
<%@page import="java.sql.*"%><%@page import="java.io.*"%><%@page errorPage ="error.jsp"%><%
  try {
    setPageContext(pageContext);
    String WebPath = getPathScript();
    String WebRoot = getRootService()+WebPath;
    String FS = separatorFileDir();//Separador de Archivo o de Directorio
    String ScriptRoot = getPathService(WebPath);
    
    CSS MainCSS = new CSS("MainCSS");
    HTMLFile mFile = new HTMLFile("mFile",getStrictName(),"0");  //Name,[Title],[Charset_#]
    mFile.setShortCutIcon("BZ.ico");
    mFile.setCSSObject(MainCSS);
    mFile.addCSSFile("Pers.css");
    
    HTMLForm MainForm = new HTMLForm("MainForm","Form",
        HTMLForm.FORM_POSTMULTIPART);  //Name,FormID,Method,[Action]
    MainForm.setCSSObject(MainCSS);
    MainForm.addInput("tName",HTMLForm.INPUT_TEXT,"","Texto",
        "30");  //Name,Type,Value(empty),Style,Argument0(size),[Argument1]
    MainForm.addInput("tSalary",HTMLForm.INPUT_TEXT,"","Texto","11");
    MainForm.addInput("tJoinDate",HTMLForm.INPUT_TEXT,"","Texto","10");
    MainForm.addInput("fPhoto",HTMLForm.INPUT_FILE,"","File","60");
    MainForm.addInput("fResume",HTMLForm.INPUT_FILE,"","File","60");
    
    MainForm.addInput("bLoad",HTMLForm.INPUT_SUBMIT,"Load Data","Boton","");
    MainForm.addInput("bList",HTMLForm.INPUT_SUBMIT,"List Data","Boton","");
    MainForm.addInput("bDelt",HTMLForm.INPUT_SUBMIT,"Delete Data","Boton","");
    MainForm.addInput("bRstJ",HTMLForm.INPUT_SUBMIT,"JSP Home","Boton","");
    MainForm.addInput("bRstP",HTMLForm.INPUT_SUBMIT,"PHP Home","Boton","");
    
    MainForm.addFormEvent("bLoad","jsp","onClick",
        getNameScript()); //Owner,IntID(InternalID),Event,Action
    MainForm.addInputEvent("bLoad","jsp2","onClick2",
        "Pers2.jsp");  //Owner,IntID(InternalID),Event,Action
    MainForm.addFormEvent("bLoad","php","onClick",getStrictName()+".php");
    MainForm.addFormEvent("bList","jsp","onClick",getNameScript());
    MainForm.addFormEvent("bList","php","onClick",getStrictName()+".php");
    MainForm.addFormEvent("bDelt","jsp","onClick",getNameScript());
    MainForm.addFormEvent("bDelt","php","onClick",getStrictName()+".php");
    MainForm.addFormEvent("bRstJ","jsp","onClick",getNameScript());
    MainForm.addFormEvent("bRstP","php","onClick",getStrictName()+".php");
    
    HTMLTable MainTabl = new HTMLTable("MainTabl",2,4);  //Name,NumCols,NumRows
    MainTabl.setCSSObject(MainCSS);
    MainTabl.setHeadCol(0,"Data Records");
    MainTabl.mergeHeadCol(0,2);  //Col,Value(# TobeMerged)
    MainTabl.mergeHorzCell(0,0,2);
    MainTabl.setTextCell(0,0,MainForm.getLabelInp("First and Last Names:",
        "tName","Etiq")+MainForm.getInput("tName"));
    MainTabl.setTextCell(0,1,MainForm.getLabelInp("Salary Value:","tSalary",
        "Etiq")+MainForm.getInput("tSalary"));
    MainTabl.setTextCell(1,1,MainForm.getLabelInp("Join Date:","tJoinDate",
        "Etiq")+MainForm.getInput("tJoinDate"));
    MainTabl.mergeHorzCell(0,2,2);
    MainTabl.setTextCell(0,2,MainForm.getLabelInp("Recent photo:","fPhoto",
        "Etiq")+MainForm.getInput("fPhoto"));
    MainTabl.mergeHorzCell(0,3,2);
    MainTabl.setTextCell(0,3,MainForm.getLabelInp("Resume:","fResume",
        "Etiq")+MainForm.getInput("fResume"));
    
    HTMLTable ButtTabl = new HTMLTable("ButtTabl",4,2);
    ButtTabl.setCSSObject(MainCSS);
    ButtTabl.setHeadRow(0,getNameScript());
    ButtTabl.setHeadRow(1,getStrictName()+".php");
    
    ButtTabl.setTextCell(0,0,MainForm.getInput("bLoad","jsp",
        "jsp2"));  //Name,[...Events](2 Events)
    ButtTabl.setTextCell(1,0,MainForm.getInput("bList","jsp"));
    ButtTabl.setTextCell(2,0,MainForm.getInput("bDelt","jsp"));
    ButtTabl.setTextCell(3,0,MainForm.getInput("bRstJ","jsp"));
    
    ButtTabl.setTextCell(0,1,MainForm.getInput("bLoad","php"));
    ButtTabl.setTextCell(1,1,MainForm.getInput("bList","php"));
    ButtTabl.setTextCell(2,1,MainForm.getInput("bDelt","php"));
    ButtTabl.setTextCell(3,1,MainForm.getInput("bRstP","php"));
      
    MainForm.addElement(MainTabl.getTable());
    MainForm.addElement(ButtTabl.getTable());
    mFile.addElement(MainForm.getForm());
    mFile.closeFile();
    printSng(mFile.getFile());
    
    //MySQL Connection
    String host = "192.168.97.21";  //"192.168.97.21:3306";  //"localhost";
    String port = "3306";
    String OldUser = "dbUserf";
    String OldPass = "dbKeyf";
    String OldDB = "dbCompanyf";
    
    if (getSessionStr("newUser") != null) {
      OldUser = getSessionStr("newUser");
    }
    if (getSessionStr("newPass") != null) {
      OldPass = getSessionStr("newPass");
    }
    if (getSessionStr("newDB") != null) {
      OldDB = getSessionStr("newDB");
    }
    Connection newConn = null;
    ResultSet rsPE = null;
    PreparedStatement PE = null;
    newConn = newMySQLConn(host,OldUser,OldPass,OldDB,
        port); //Host,User,Password,[DataBase],[Port]
    setConnection(newConn);
    
    //Insertion
    if (getRequestStr("bLoad")!=null) {
      try {
        PE = newConn.prepareStatement("INSERT INTO tblRecords (FirsLastName,"
            +"Salary,JoinDate,Photo,Resume) VALUES(?,?,?,?,?)");
        String sName = getRequestStr("tName");
        String sSalary = getRequestStr("tSalary");
        String sJoinDate = getRequestStr("tJoinDate");
        InputStream isPhoto = getRequestFileStream("fPhoto");
        String sResume = getRequestFileString("fResume");
        
        PE.setString(1,sName);
        PE.setInt(2,Integer.parseInt(sSalary));
        PE.setString(3,sJoinDate);
        PE.setBinaryStream(4,isPhoto);
        PE.setString(5,sResume);
        PE.executeUpdate();
        printMsg("Successful insertion!");
      }
      catch (Exception e) { printErr(e.toString()); }
      finally {
        PE.close();
        newConn.close();
      }
    }
    
    //Extraction
    if (getRequestStr("bList")!=null) {
      String FileName = "Personal.JSP.RTF";
      String FullFileName = ScriptRoot+FileName;
      String WebFileName = WebRoot+FileName;
      String sPathJPG = ScriptRoot+"joseluisbz.jpg";
      String sPathPNG = ScriptRoot+"Empresa.png";
 
      try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(FullFileName));
        RTFFile FileRTF = new RTFFile();
        RTFImage imgJPG = new RTFImage(sPathJPG);
        if (imgJPG.getHexImage().equals("Error")) {
          throw new RuntimeException("Error: File \""+sPathJPG+"\" is not JPG or PNG");
        }
        
        /*
        //predefined Colors that do not need to be added
        //Name,Red,Green,Blue
        FileRTF.addColor("Negro",0,0,0);  //Black ->Index(0)
        FileRTF.addColor("Azul",0,0,255);  //Blue ->Index(1)
        FileRTF.addColor("Cian",0,255,255);  //Cyan ->Index(2)
        FileRTF.addColor("Verde",0,255,0);  //Green ->Index(3)
        FileRTF.addColor("Magenta",255,0,255);  //Magenta ->Index(4)
        FileRTF.addColor("Rojo",255,0,0);  //Red ->Index(5)
        FileRTF.addColor("Amarillo",255,255,0);  //Yellow ->Index(6)
        FileRTF.addColor("Blanco",255,255,255);  //White ->Index(7)
        
        //predefined Fonts that do not need to be added
        //Name,Family,FamilyName
        FileRTF.addFont("TlwgMono","fnil","TlwgMono");
        FileRTF.addFont("Arial","fswiss","Arial");
        FileRTF.addFont("TimesNewRoman","froman","Times New Roman");
        FileRTF.addFont("CourierNew","fmodern","Courier New");
        FileRTF.addFont("Edwardian","fscript","Edwardian Script ITC");
        */
        
        String InfImagenJPG = imgJPG.getRTFImage(imgJPG.getHexImage(),imgJPG.getFormat(),
            imgJPG.getHigh(),imgJPG.getWide());
        RTFImage imgPNG = new RTFImage(sPathPNG);
        if (imgPNG.getHexImage().equals("Error")) {
          throw new RuntimeException("Error: File \""+sPathPNG+"\" is not JPG or PNG");
        }
        String InfImagenPNG = imgPNG.getRTFImage(imgPNG.getHexImage(),imgPNG.getFormat(),
            imgPNG.getHigh(),imgPNG.getWide());
        RTFImage ImageRTFIMG;
        String InfImagenIMG;
        
        PE = newConn.prepareStatement("SELECT * FROM tblRecords");
        rsPE = PE.executeQuery();
        rsPE.last();
        int NumRecords = rsPE.getRow();rsPE.beforeFirst();
        RTFTable TblData = null;
        FileRTF.addList("Lst1",RTFFile.LIST_UPPERROMANS,"1");  //Name,Type,FamilyFont#
        FileRTF.addListItem("Lst1","Primero");
        FileRTF.addListItem("Lst1","Segundo");
        FileRTF.addList("Lst2",RTFFile.LIST_LOWERALPHABET,"2");
        FileRTF.addListItem("Lst2","First");
        FileRTF.addListItem("Lst2","Second");
        while(rsPE.next()) {
          FileRTF.offOtherFormatFile();
          FileRTF.setAlign(RTFFile.ALIGN_CENTERED);
          FileRTF.setColorFront("Blanco");
          FileRTF.setColorBack("Negro");
          FileRTF.setFont("Edwardian");
          FileRTF.setSizeFont(20);
          FileRTF.setUnderLine(RTFFile.ON);
          FileRTF.addText("Limited Company");
          FileRTF.addParg();
          
          FileRTF.setColorBack("Blanco");
          FileRTF.setColorFront("Negro");
          TblData = new RTFTable(4,4);  //4 Columns, 4 Rows
          TblData.setTableSpaceCellsRow(10);
          TblData.setTableLeftmostEdgePos(10);
          TblData.setTableHorzAlign(RTFTable.TABLE_LEFT);
          TblData.setTableBorderType(RTFTable.BORDER_SINGLETHICKNESS);
          TblData.setCellsVertAlign(RTFTable.CELLS_TOP);
          TblData.setCellsBorderType(RTFTable.BORDER_DOUBLETHICKNESS);
          TblData.setCellsThick(10);
          TblData.setCellsColor(FileRTF.getColorIndex("Negro"));
          TblData.setWideCols(1000);  //Width of 2000 to put all columns
          TblData.setWideCol(0,3000);  //Width of 3000 to Column 0
          TblData.setWideCol(3,3000);  //Width of 3000 to Column 3
          
          TblData.setAlignTable(RTFTable.ALIGN_CENTERED);
          TblData.setColorFrontTable(FileRTF.getColorIndex("Blanco"));
          TblData.setColorBackTable(FileRTF.getColorIndex("Negro"));
          TblData.setFontTable(FileRTF.getFontIndex("TlwgMono"));
          TblData.setSizeFontTable(12);
          
          TblData.setAlignCell(0,0,RTFTable.ALIGN_LEFT);  //Col,Row,Align
          TblData.setColorFrontCell(0,0,0);  //Col,Row,ColorIndex
          TblData.setColorBackCell(0,0,0);  //Col,Row,ColorIndex
          TblData.setFontCell(0,0,0);  //Col,Row,Font
          TblData.setSizeFontCell(0,0,12);  //Col,Row,Size
          
          TblData.setItemCell(0,1,InfImagenPNG);
          TblData.setItemCell(3,1,InfImagenJPG);
          TblData.mergeHorzCell(1,0,2);  //Col,Row,NumCellToBeMergedHorizontally
          TblData.setTextCell(1,0,"Celda 1,0 con Celda 2,0");
          TblData.mergeHorzCell(1,3,2);
          TblData.setTextCell(1,3,"Celda 1,3 con Celda 2,3");
          TblData.mergeVertCell(0,1,2);  //Col,Row,NumCellToBeMergedVerticaally
          TblData.mergeVertCell(3,1,2);
          
          FileRTF.addItem(TblData.getTable());
          FileRTF.addLine();
          
          FileRTF.setUnderLine(RTFFile.OFF);
          FileRTF.setSizeFont(11);
          FileRTF.setFont("CourierNew");
          FileRTF.setScript(RTFFile.SUB);
          FileRTF.addText("SUBSCRIPT");
          FileRTF.setScript(RTFFile.OFF);
          FileRTF.addText(" ");
          FileRTF.setStrike(RTFFile.ON);
          FileRTF.addText("STRIKE");
          FileRTF.setStrike(RTFFile.OFF);
          FileRTF.addText(" ");
          FileRTF.setScript(RTFFile.SUPER);
          FileRTF.addText("SUPERSCRIPT");
          FileRTF.setScript(RTFFile.OFF);
          FileRTF.addLine();
          
          FileRTF.setAlign(RTFFile.ALIGN_LEFT);
          FileRTF.setFont("CourierNew");
          FileRTF.setSizeFont(12);
          FileRTF.setUnderLine(RTFFile.ON);
          FileRTF.setBold(RTFFile.OFF);
          FileRTF.setItalic(RTFFile.OFF);
          FileRTF.setColorFront("Negro");
          FileRTF.addText("Nombre: ");
          FileRTF.setItalic(RTFFile.ON);
          FileRTF.setUnderLine(RTFFile.OFF);
          FileRTF.setColorFront("Rojo");
          FileRTF.addText(rsPE.getString(1));
          FileRTF.addLine();
          FileRTF.setItalic(RTFFile.OFF);
          FileRTF.setUnderLine(RTFFile.ON);
          FileRTF.setColorFront("Negro");
          FileRTF.addText("Salario: ");
          FileRTF.setItalic(RTFFile.ON);
          FileRTF.setUnderLine(RTFFile.OFF);
          FileRTF.setColorFront("Rojo");
          FileRTF.addText(String.valueOf(rsPE.getInt(2)));
          FileRTF.addLine();
          
          ImageRTFIMG = new RTFImage(rsPE.getBytes(4));
          
          /*
          //ImageRTFIMG.setCropLeft(0);// 0 cutted twips in Left Side
          //ImageRTFIMG.setCropRight(0);// 0 cutted twips in Right Side
          //ImageRTFIMG.setCropTop(0);// 0 cutted twips in Top Side
          //ImageRTFIMG.setCropBottom(0);// 0 cutted twips in Bootom Side
          //ImageRTFIMG.setScaleX(100);// 100% of X Image
          //ImageRTFIMG.setScaleY(100);// 100% of Y Image
          //*/
          
          ImageRTFIMG.setScaleX(50);
          ImageRTFIMG.setScaleY(25);
          InfImagenIMG = ImageRTFIMG.getRTFImage(ImageRTFIMG.getHexImage(),
              ImageRTFIMG.getFormat(),ImageRTFIMG.getHigh(),ImageRTFIMG.getWide());
          FileRTF.addItem(InfImagenIMG);
          FileRTF.addParg();  //Separe Image of Text
          FileRTF.setItalic(RTFFile.OFF);
          FileRTF.setUnderLine(RTFFile.ON);
          FileRTF.setColorFront("Negro");
          FileRTF.addText("Resumen: ");
          FileRTF.setItalic(RTFFile.ON);
          FileRTF.setUnderLine(RTFFile.OFF);
          FileRTF.setColorFront("Verde");
          FileRTF.addText(rsPE.getString(5));
          FileRTF.setColorFront("Azul");
          
          FileRTF.addLine();
          FileRTF.addText("Ini List");
          FileRTF.setFirstIndent(-360);
          FileRTF.setLeftIndent(720);
          FileRTF.setSpaceAfter(RTFFile.ON);
          FileRTF.setSpaceMultiple(RTFFile.ON);
          FileRTF.addItem(FileRTF.getList("Lst1"));
          FileRTF.offIndent();
          FileRTF.offSpacing();
          FileRTF.incIndent();
          FileRTF.incSpacing();
          
          FileRTF.addLine();
          FileRTF.addText("Mid List");
          FileRTF.setSpaceLine(RTFFile.SL_2_0); //Line Spacing 2.0
          FileRTF.setRightIndent(1040);
          FileRTF.setSpaceBefore(RTFFile.ON);
          FileRTF.setSpaceMultiple(RTFFile.ON);
          FileRTF.addItem(FileRTF.getList("Lst2"));
          FileRTF.offIndent();
          FileRTF.offSpacing();
          FileRTF.incIndent();
          FileRTF.incSpacing();
          
          FileRTF.setColorFront("Negro");
          FileRTF.addText("End List");
          FileRTF.addLine();
          FileRTF.addText("Record: "+NumRecords);
          FileRTF.addLine();
          FileRTF.addText("Last Text");
          NumRecords--;
          if (NumRecords>0) {
            FileRTF.addParg();
            FileRTF.addPage(); //New Page
          }
        }
        FileRTF.endFile();
        bw.write(FileRTF.getFile());
        bw.close();
        printLnk(WebFileName);
        printMsg("Successful generation of RTF file!");
      }
      catch (Exception e) { printErr(e.toString()); }
      finally {
        rsPE.close();
        PE.close();
        newConn.close();
      }
    }
    
    //Elimination
    if (getRequestStr("bDelt")!=null) {
      try {
        PE = newConn.prepareStatement("DELETE FROM tblRecords");
        PE.executeUpdate();
        printMsg("Successful elimination!");
      }
      catch (Exception e) { printErr(e.toString()); }
      finally {
        PE.close();
        newConn.close();
      }
    }
  }
  catch (Exception e) { printErr(e.toString()); }
%>

PersEng.php

<?php
  namespace bz\htmlcss2rtf;
  require_once("phar://bz-htmlcss2rtf.phar/HTMLFile.php");
  require_once("phar://bz-htmlcss2rtf.phar/HTMLTable.php");
  require_once("phar://bz-htmlcss2rtf.phar/HTMLForm.php");
  require_once("phar://bz-htmlcss2rtf.phar/RTFFile.php");
  require_once("phar://bz-htmlcss2rtf.phar/RTFTable.php");
  require_once("phar://bz-htmlcss2rtf.phar/RTFImage.php");
  require_once("phar://bz-htmlcss2rtf.phar/Ini.php");
  require_once("phar://bz-htmlcss2rtf.phar/CSS.php");
  require_once("error.php");
  use Exception;
  try {
    $WebPath = getPathScript();
    $WebRoot = getRootService().$WebPath;
    $FS = separatorFileDir();//Separador de Archivo o de Directorio
    $ScriptRoot = getPathService($WebPath);
    
    $MainCSS = new CSS("MainCSS");
    $mFile = new HTMLFile("mFile",getStrictName(),"0");  //Name,[Title],[Charset_#]
    $mFile->setShortCutIcon("BZ.ico");
    $mFile->setCSSObject($MainCSS);
    $mFile->addCSSFile("Pers.css");
    
    $MainForm = new HTMLForm("MainForm","Form",
        HTMLForm::FORM_POSTMULTIPART);  //Name,FormID,Method,[Action]
    $MainForm->setCSSObject($MainCSS);
    $MainForm->addInput("tName",HTMLForm::INPUT_TEXT,"","Texto",
        "30");  //Name,Type,Value(empty),Style,Argument0(size),[Argument1]
    $MainForm->addInput("tSalary",HTMLForm::INPUT_TEXT,"","Texto","11");
    $MainForm->addInput("tJoinDate",HTMLForm::INPUT_TEXT,"","Texto","10");
    $MainForm->addInput("fPhoto",HTMLForm::INPUT_FILE,"","File","60");
    $MainForm->addInput("fResume",HTMLForm::INPUT_FILE,"","File","60");
    
    $MainForm->addInput("bLoad",HTMLForm::INPUT_SUBMIT,"Load Data","Boton","");
    $MainForm->addInput("bList",HTMLForm::INPUT_SUBMIT,"List Data","Boton","");
    $MainForm->addInput("bDelt",HTMLForm::INPUT_SUBMIT,"Delete Data","Boton","");
    $MainForm->addInput("bRstP",HTMLForm::INPUT_SUBMIT,"PHP Home","Boton","");
    $MainForm->addInput("bRstJ",HTMLForm::INPUT_SUBMIT,"JSP Home","Boton","");
    
    $MainForm->addFormEvent("bLoad","php","onClick",
        getNameScript()); //Owner,IntID(InternalID),Event,Action
    $MainForm->addInputEvent("bLoad","php2","onClick2",
        "Pers2.php"); //Owner,IntID(InternalID),Event,Action
    $MainForm->addFormEvent("bLoad","jsp","onClick",getStrictName().".jsp");
    $MainForm->addFormEvent("bList","php","onClick",getNameScript());
    $MainForm->addFormEvent("bList","jsp","onClick",getStrictName().".jsp");
    $MainForm->addFormEvent("bDelt","php","onClick",getNameScript());
    $MainForm->addFormEvent("bDelt","jsp","onClick",getStrictName().".jsp");
    $MainForm->addFormEvent("bRstP","php","onClick",getNameScript());
    $MainForm->addFormEvent("bRstJ","jsp","onClick",getStrictName().".jsp");
    
    $MainTabl = new HTMLTable("MainTabl",2,4);  //Name,NumCols,NumRows
    $MainTabl->setCSSObject($MainCSS);
    $MainTabl->setHeadCol(0,"Data Records");
    $MainTabl->mergeHeadCol(0,2);  //Col,Value(# TobeMerged)
    $MainTabl->mergeHorzCell(0,0,2);
    $MainTabl->setTextCell(0,0,$MainForm->getLabelInp("First and Last Names:",
        "tName","Etiq").$MainForm->getInput("tName"));
    $MainTabl->setTextCell(0,1,$MainForm->getLabelInp("Salary Value:",
        "tSalary","Etiq").$MainForm->getInput("tSalary"));
    $MainTabl->setTextCell(1,1,$MainForm->getLabelInp("Join Date:","tJoinDate",
        "Etiq").$MainForm->getInput("tJoinDate"));
    $MainTabl->mergeHorzCell(0,2,2);
    $MainTabl->setTextCell(0,2,$MainForm->getLabelInp("Recent photo:","fPhoto",
        "Etiq").$MainForm->getInput("fPhoto"));
    $MainTabl->mergeHorzCell(0,3,2);
    $MainTabl->setTextCell(0,3,$MainForm->getLabelInp("Resume:","fResume",
        "Etiq").$MainForm->getInput("fResume"));
    
    $ButtTabl = new HTMLTable("ButtTabl",4,2);
    $ButtTabl->setCSSObject($MainCSS);
    $ButtTabl->setHeadRow(0,getNameScript());
    $ButtTabl->setHeadRow(1,getStrictName().".jsp");
    
    $ButtTabl->setTextCell(0,0,$MainForm->getInput("bLoad","php",
        "php2"));  //Name,[...Events](2 Events)
    $ButtTabl->setTextCell(1,0,$MainForm->getInput("bList","php"));
    $ButtTabl->setTextCell(2,0,$MainForm->getInput("bDelt","php"));
    $ButtTabl->setTextCell(3,0,$MainForm->getInput("bRstP","php"));
    
    $ButtTabl->setTextCell(0,1,$MainForm->getInput("bLoad","jsp"));
    $ButtTabl->setTextCell(1,1,$MainForm->getInput("bList","jsp"));
    $ButtTabl->setTextCell(2,1,$MainForm->getInput("bDelt","jsp"));
    $ButtTabl->setTextCell(3,1,$MainForm->getInput("bRstJ","jsp"));
    
    $MainForm->addElement($MainTabl->getTable());
    $MainForm->addElement($ButtTabl->getTable());
    $mFile->addElement($MainForm->getForm());
    $mFile->closeFile();
    printSng($mFile->getFile());
    
    //MySQL Connection
    $host = "192.168.97.21";  //"192.168.97.21:3306";  //"localhost";
    $port = "3306";
    $OldUser = "dbUserf";
    $OldPass = "dbKeyf";
    $OldDB = "dbCompanyf";
    session_start();
    if (getSessionObj("newUser") != NULL) {
      $OldUser = getSessionObj("newUser");
    }
    if (getSessionObj("newPass") != NULL) {
      $OldPass = getSessionObj("newPass");
    }
    if (getSessionObj("newDB") != NULL) {
      $OldDB = getSessionObj("newDB");
    }
    $newConn = NULL;
    $PE = NULL;
    $newConn = newMySQLConn($host,$OldUser,$OldPass,$OldDB,
        $port); //Host,User,Password,[DataBase],[Port]
    setConnection($newConn);
    
    //Insertion
    if (getRequestStr("bLoad")!= NULL) {
      try {
        $PE = $newConn->prepare("INSERT INTO tblRecords (FirsLastName,"
            ."Salary,JoinDate,Photo,Resume) VALUES(?,?,?,?,?)");
        if (!$PE) {
          throw new RuntimeException("Prepare SQL statement for creation failed!");
        }
        $sName = utf8_encode(getRequestStr("tName"));
        $sSalary = getRequestStr("tSalary");
        $sJoinDate = getRequestStr("tJoinDate");
        $isPhoto = getRequestFileString("fPhoto");
        $sResume = utf8_encode(getRequestFileString("fResume"));
        $PE->bind_param('sisbb',$sName,$sSalary,$sJoinDate,$isPhoto,$sResume);
        $PE->send_long_data(3,$isPhoto);
        $PE->send_long_data(4,$sResume);
        if (!$PE->execute()) {
          throw new RuntimeException("Prepare SQL statement for execution failed!");
        }
        printMsg("Successful insertion!");
      }
      catch (Exception $e) { printErr($e->getMessage()); }
      finally {
        $PE->close();
        $newConn->close();
      }
    }
    
    //Extraction
    if (getRequestStr("bList")!= NULL) {
      $FileName = "Personal.PHP.RTF";
      $FullFileName = $ScriptRoot.$FileName;
      $WebFileName = $WebRoot.$FileName;
      $sPathJPG = $ScriptRoot."joseluisbz.jpg";
      $sPathPNG = $ScriptRoot."Empresa.png";
      
      try {
        $fw = fopen($FullFileName,"wb");
        if (!$fw) {
          throw new RuntimeException("Could not open the file!");
        }
        $FileRTF = new RTFFile();
        $imgJPG = new RTFImage($sPathJPG);
        if ($imgJPG->getHexImage() == "Error") {
          throw new RuntimeException("Error: File \"".$sPathJPG."\" is not JPG or PNG");
        }
        
        /*
        //predefined Colors that do not need to be added
        //Name,Red,Green,Blue
        $FileRTF->addColor("Negro",0,0,0);  //Black ->Index(0)
        $FileRTF->addColor("Azul",0,0,255);  //Blue ->Index(1)
        $FileRTF->addColor("Cian",0,255,255);  //Cyan ->Index(2)
        $FileRTF->addColor("Verde",0,255,0);  //Green ->Index(3)
        $FileRTF->addColor("Magenta",255,0,255);  //Magenta ->Index(4)
        $FileRTF->addColor("Rojo",255,0,0);  //Red ->Index(5)
        $FileRTF->addColor("Amarillo",255,255,0);  //Yellow ->Index(6)
        $FileRTF->addColor("Blanco",255,255,255);  //White ->Index(7)
        
        //predefined Fonts that do not need to be added
        //Name,Family,FamilyName
        $FileRTF->addFont("TlwgMono","fnil","TlwgMono");
        $FileRTF->addFont("Arial","fswiss","Arial");
        $FileRTF->addFont("TimesNewRoman","froman","Times New Roman");
        $FileRTF->addFont("CourierNew","fmodern","Courier New");
        $FileRTF->addFont("Edwardian","fscript","Edwardian Script ITC");
        */
        
        $InfImagenJPG = $imgJPG->getRTFImage($imgJPG->getHexImage(),$imgJPG->getFormat(),
            $imgJPG->getHigh(),$imgJPG->getWide());
        $imgPNG = new RTFImage($sPathPNG);
        if ($imgPNG->getHexImage() == "Error") {
          throw new RuntimeException("Error: File \"".$sPathPNG."\" is not JPG or PNG");
        }
        $InfImagenPNG = $imgPNG->getRTFImage($imgPNG->getHexImage(),$imgPNG->getFormat(),
            $imgPNG->getHigh(),$imgPNG->getWide());
        $ImageRTFIMG = NULL;
        $InfImagenIMG = NULL;
        $PE = $newConn->prepare("SELECT * FROM tblRecords");
        if (!$PE) {
          throw new RuntimeException("Prepare SQL statement for creation failed!");
        }
        if (!$PE->execute()) {
          throw new RuntimeException("Prepare SQL statement for execution failed!");
        }
        $PE->bind_result($sName,$sSalary,$sJoinDate,$BytesFoto,$BytesResume);
        $PE->store_result();
        $NumRecords = $PE->num_rows;
        $TblData = NULL;
        $FileRTF->addList("Lst1",RTFFile::LIST_UPPERROMANS,"1");  //Name,Type,FamilyFont#
        $FileRTF->addListItem("Lst1","Primero");
        $FileRTF->addListItem("Lst1","Segundo");
        $FileRTF->addList("Lst2",RTFFile::LIST_LOWERALPHABET,"2");
        $FileRTF->addListItem("Lst2","First");
        $FileRTF->addListItem("Lst2","Second");
        while ($PE->fetch()) {
          $FileRTF->offOtherFormatFile();
          $FileRTF->setAlign(RTFFile::ALIGN_CENTERED);
          $FileRTF->setColorFront("Blanco");
          $FileRTF->setColorBack("Negro");
          $FileRTF->setFont("Edwardian");
          $FileRTF->setSizeFont(20);
          $FileRTF->setUnderLine(RTFFile::ON);
          $FileRTF->addText("Limited Company");
          $FileRTF->addParg();
          
          $FileRTF->setColorBack("Blanco");
          $FileRTF->setColorFront("Negro");
          $TblData = new RTFTable(4,4);  //4 Columns, 4 Rows
          $TblData->setTableSpaceCellsRow(10);
          $TblData->setTableLeftmostEdgePos(10);
          $TblData->setTableHorzAlign(RTFTable::TABLE_LEFT);
          $TblData->setTableBorderType(RTFTable::BORDER_SINGLETHICKNESS);
          $TblData->setCellsVertAlign(RTFTable::CELLS_TOP);
          $TblData->setCellsBorderType(RTFTable::BORDER_DOUBLETHICKNESS);
          $TblData->setCellsThick(10);
          $TblData->setCellsColor($FileRTF->getColorIndex("Negro"));
          $TblData->setWideCols(1000);  //Width of 2000 to put all columns
          $TblData->setWideCol(0,3000);  //Width of 3000 to Column 0
          $TblData->setWideCol(3,3000);  //Width of 3000 to Column 3
          
          $TblData->setAlignTable(RTFTable::ALIGN_CENTERED);
          $TblData->setColorFrontTable($FileRTF->getColorIndex("Blanco"));
          $TblData->setColorBackTable($FileRTF->getColorIndex("Negro"));
          $TblData->setFontTable($FileRTF->getFontIndex("TlwgMono"));
          $TblData->setSizeFontTable(12);
          
          $TblData->setAlignCell(0,0,RTFTable::ALIGN_LEFT);  //Col,Row,Align
          $TblData->setColorFrontCell(0,0,0);  //Col,Row,ColorIndex
          $TblData->setColorBackCell(0,0,0);  //Col,Row,ColorIndex
          $TblData->setFontCell(0,0,0);  //Col,Row,Font
          $TblData->setSizeFontCell(0,0,12);  //Col,Row,Size
          
          $TblData->setItemCell(0,1,$InfImagenPNG);
          $TblData->setItemCell(3,1,$InfImagenJPG);
          $TblData->mergeHorzCell(1,0,2);  //Col,Row,NumCellToBeMergedHorizontally
          $TblData->setTextCell(1,0,"Celda 1,0 con Celda 2,0");
          $TblData->mergeHorzCell(1,3,2);
          $TblData->setTextCell(1,3,"Celda 1,3 con Celda 2,3");
          $TblData->mergeVertCell(0,1,2);  //Col,Row,NumCellToBeMergedVerticaally
          $TblData->mergeVertCell(3,1,2);
          
          $FileRTF->addItem($TblData->getTable());
          $FileRTF->addLine();
          
          $FileRTF->setUnderLine(RTFFile::OFF);
          $FileRTF->setSizeFont(11);
          $FileRTF->setFont("CourierNew");
          $FileRTF->setScript(RTFFile::SUB);
          $FileRTF->addText("SUBSCRIPT");
          $FileRTF->setScript(RTFFile::OFF);
          $FileRTF->addText(" ");
          $FileRTF->setStrike(RTFFile::ON);
          $FileRTF->addText("STRIKE");
          $FileRTF->setStrike(RTFFile::OFF);
          $FileRTF->addText(" ");
          $FileRTF->setScript(RTFFile::SUPER);
          $FileRTF->addText("SUPERSCRIPT");
          $FileRTF->setScript(RTFFile::OFF);
          $FileRTF->addLine();
          
          $FileRTF->setAlign(RTFFile::ALIGN_LEFT);
          $FileRTF->setFont("CourierNew");
          $FileRTF->setSizeFont(12);
          $FileRTF->setUnderLine(RTFFile::ON);
          $FileRTF->setBold(RTFFile::OFF);
          $FileRTF->setItalic(RTFFile::OFF);
          $FileRTF->setColorFront("Negro");
          $FileRTF->addText("Nombre: ");
          $FileRTF->setItalic(RTFFile::ON);
          $FileRTF->setUnderLine(RTFFile::OFF);
          $FileRTF->setColorFront("Rojo");
          $FileRTF->addText(utf8_decode($sName));
          $FileRTF->addLine();
          $FileRTF->setItalic(RTFFile::OFF);
          $FileRTF->setUnderLine(RTFFile::ON);
          $FileRTF->setColorFront("Negro");
          $FileRTF->addText("Salario: ");
          $FileRTF->setItalic(RTFFile::ON);
          $FileRTF->setUnderLine(RTFFile::OFF);
          $FileRTF->setColorFront("Rojo");
          $FileRTF->addText($sSalary);
          $FileRTF->addLine();
          
          $ImageRTFIMG = new RTFImage($BytesFoto);
          
          /*
          //$ImageRTFIMG->setCropLeft(0);// 0 cutted twips in Left Side
          //$ImageRTFIMG->setCropRight(0);// 0 cutted twips in Right Side
          //$ImageRTFIMG->setCropTop(0);// 0 cutted twips in Top Side
          //$ImageRTFIMG->setCropBottom(0);// 0 cutted twips in Bootom Side
          //$ImageRTFIMG->setScaleX(100);// 100% of X Image
          //$ImageRTFIMG->setScaleY(100);// 100% of Y Image
          //*/
          
          $ImageRTFIMG->setScaleX(50);
          $ImageRTFIMG->setScaleY(25);
          $InfImagenIMG = $ImageRTFIMG->getRTFImage($ImageRTFIMG->getHexImage(),
              $ImageRTFIMG->getFormat(),$ImageRTFIMG->getHigh(),$ImageRTFIMG->getWide());
          $FileRTF->addItem($InfImagenIMG);
          $FileRTF->addParg();  //Separe Image of Text
          $FileRTF->setItalic(RTFFile::OFF);
          $FileRTF->setUnderLine(RTFFile::ON);
          $FileRTF->setColorFront("Negro");
          $FileRTF->addText("Resumen: ");
          $FileRTF->setItalic(RTFFile::ON);
          $FileRTF->setUnderLine(RTFFile::OFF);
          $FileRTF->setColorFront("Verde");
          $FileRTF->addText(utf8_decode($BytesResume));
          $FileRTF->setColorFront("Azul");
          
          $FileRTF->addLine();
          $FileRTF->addText("Ini List");
          $FileRTF->setFirstIndent(-360);
          $FileRTF->setLeftIndent(720);
          $FileRTF->setSpaceAfter(RTFFile::ON);
          $FileRTF->setSpaceMultiple(RTFFile::ON);
          $FileRTF->addItem($FileRTF->getList("Lst1"));
          $FileRTF->offIndent();
          $FileRTF->offSpacing();
          $FileRTF->incIndent();
          $FileRTF->incSpacing();
          
          $FileRTF->addLine();
          $FileRTF->addText("Mid List");
          $FileRTF->setSpaceLine(RTFFile::SL_2_0); //Line Spacing 2.0
          $FileRTF->setRightIndent(1040);
          $FileRTF->setSpaceBefore(RTFFile::ON);
          $FileRTF->setSpaceMultiple(RTFFile::ON);
          $FileRTF->addItem($FileRTF->getList("Lst2"));
          $FileRTF->offIndent();
          $FileRTF->offSpacing();
          $FileRTF->incIndent();
          $FileRTF->incSpacing();
          
          $FileRTF->setColorFront("Negro");
          $FileRTF->addText("End List");
          $FileRTF->addLine();
          $FileRTF->addText("Record: ".$NumRecords);
          $FileRTF->addLine();
          $FileRTF->addText("Last Text");
          $NumRecords--;
          if ($NumRecords>0) {
            $FileRTF->addParg();
            $FileRTF->addPage(); //New Page
          }
        }
        $FileRTF->endFile();
        fwrite($fw,$FileRTF->getFile());
        fclose($fw);
        printLnk($WebFileName);
        printMsg("Successful generation of RTF file!");
      }
      catch (Exception $e) { printErr($e->getMessage()); }
      finally {
        $PE->close();
        $newConn->close();
      }
    }
    
    //Elimination
    if (getRequestStr("bDelt")!= NULL) {
      try {
        $PE = $newConn->prepare("DELETE FROM tblRecords");
        if (!$PE) {
          throw new RuntimeException("Prepare SQL statement for creation failed!");
        }
        if (!$PE->execute()) {
          throw new RuntimeException("Prepare SQL statement for execution failed!");
        }
        printMsg("Successful elimination!");
      }
      catch (Exception $e) { printErr($e->getMessage()); }
      finally {
        $PE->close();
        $newConn->close();
      }
    }
  }
  catch (Exception $e) { printErr($e->getMessage()); }
?>

“dbUserf”, “dbKeyf” and “dbCompanyf” are values assigned incorrectly (on purpose) to test session functions instead of “dbUser”, “dbKey” and “dbCompany”.

PersEnd.jsp - Ini

PersEnd.php - Ini

PersEnd.jsp - Load

PersEnd.php - Load

PersEnd.jsp - List

PersEnd.php - List

PersEnd.jsp - Delete

PersEnd.php - Delete

The result of this test is the RTF file:
Personal.xxP.RTF

Comments:
If you have problem, comments or questions using this post, let me know.

Publicado en Classes, databases, Functions, Java, Java, Java Server Pages, JSP, JSP, Methods, OOP, PHP, PHP, Programming, RTF, Scripts, Tomcat | Etiquetado , , , , , , , | Deja un comentario

JSPINFO like PHPINFO, Changing Information of Tomcat Server


The jspinfo function.

PHP has a function, that allow us to view different information of our system. Like variable, configuration, etc.

I made a class that allow us to check information like phpinfo of PHP.

JLUtils.jar

The way to use this class is a bit different, you must include the package related to my class and use the fucntion jspinfo.

<%@page import="static Pckg.JC.*"%><%
  jspinfo(pageContext);
%>

Editing index-jsp jspinfo

Testing…
Testing jspinfo

Changing Information of Tomcat Server.
Only you need to create a file with the name ServerInfo.properties inside of multiple subdirectories that you will need to create too.
The complete path from Tomcat’s folder is:
lib\org\apache\catalina\util.
The content of ServerInfo.properties is:

server.info=Tomcat Version X

Editing   ServerInfo-Properties
Or the name that you want to use instead of “Tomcat Version X”.

Later, you will need to restart the Tomcat Server.

Testing jspinfo(Version X)

Publicado en Install, JSP, Server, Servidores Web, Tomcat, Uncategorized, Web Server, Windows | Etiquetado , , , , | Deja un comentario

Manually Installing Php, Tomcat and Httpd Lounge


This is my last post about installation of this products (Php, Tomcat and Httpd).
This tutorial was tested using Windows 7 of 32 bits.
The steps that we will describe are:

All instalation will be made in the folder:

C:\ServerWeb\

All commands through CLI (CMD console) were in Administrator mode.
In this post I will work using symbolic links with mklink command, in this manner if I need to change the version of some product, only I will need to redirect its link.


PHP


Preparations for the Php installation.

I will use the Php 5.5.8 for Win32.
The contents of the .zip file was uncompressed in the folder:

C:\ServerWeb\Php_5.5.8\

But with symbolic link all operations of PHP will be done under the folder:

C:\ServerWeb\Php\

To create the symbolic link for PHP, use the command:

mklink /J "C:\ServerWeb\Php" "C:\ServerWeb\Php_5.5.8"

Php_00_mklink for Php

If you want to remove this link, you can use:

rd "C:\ServerWeb\Php"

Php_01_rd for Php


Declaring to system the path of PHP.

Now, Is needed to access to variables system, with this manner or according to your preference:
Php_02_Sysdm.cpl

Later, the System Properties dialog box is shown.
Php_03_SystemProperties

Now, We select Advanced tab and press the Environment Variables button.
Php_04_SystemProperties (Advance)

Here we select the Path variable and press the Edit button.
Php_05_EnvironmentVariables_Edit

Modify the variable value adding at the end the path of PHP and press the OK button.

C:\ServerWeb\Php\

Php_06_EditSystemVariable_Path


Working with the PHP configuration file php.ini.

Inside of this folder there are two files containing templates of Php configuration:
php.ini-development and php.ini-production, the difference consist into if the errors will be shown, while the version for developing shows the errors and other information, the version for production does not.
As I’m testing I took php.ini-development and copied:
Php_07_Coying php.ini

To enable error tracking change the value of the variable error_log.

error_log = "C:\ServerWeb\Php\logs\php-errors.log"

Php_08_Editing_php_ini (error_log)

To limit the size of POST data change the value of the variable post_max_size.

post_max_size = 5M

Php_09_Editing_php_ini (post_max_size)

To indicate the folder of extensions change the variable extension_dir.

extension_dir = "C:\ServerWeb\Php\ext\"

Php_10_Editing_php_ini (extension_dir)

We indicate the maximum file size by changing the variable upload_max_filesize.

upload_max_filesize = 3M

Php_11_Editing_php_ini (upload_max_filesize)

To enable the use of mysqli, uncheck the respective library.

extension=php_mysqli.dll

Php_12_Editing_php_ini (Enabling php_mysqli.dll)


TOMCAT


Java previous changes.

Like other products, if necessary change the version of java, using symbolic link will be easy.

Also create a symbolic link to the directory jdk.

mklink /J "C:\Program Files\Java\jdk\" "C:\Program Files\Java\jdk1.7.0_45\"

Jdk_00_mklink for Jdk

To see as was definitively:

dir "C:\Program Files\Java"

Jdk_02_dir

If you want to remove this link, you can use:

rd "C:\Program Files\Java\jdk\"

Jdk_01_rd for Jdk


Preparations for the Tomcat installation.

Then this post will work with Tomcat 7.0.50 for Win32.
The contents of the .zip file was uncompressed in the folder:

C:\ServerWeb\Tomcat_7.0.50\

But with symbolic link all operations of TOMCAT will be done under the folder:

C:\ServerWeb\Tomcat\

To create the symbolic link for TOMCAT, use the command:

mklink /J "C:\ServerWeb\Tomcat" "C:\ServerWeb\Tomcat_7.0.50"

Tomcat_00_mklink for Tomcat

If you want to remove this link, you can use:

rd "C:\ServerWeb\Tomcat"

Tomcat_01_rd for Tomcat


Declaring to system the path of TOMCAT.

Now, Is needed to access to variables system, with this manner or according to your preference:
Tomcat_02_Sysdm-cpl

Later, the System Properties dialog box is shown.
Tomcat_03_SystemProperties

Now, We select Advanced tab and press the Environment Variables button.
Tomcat_04_SystemProperties (Advance)

Here we press the New button.
Tomcat_05_EnvironmentVariables_New

In the New System Variable dialog box, we write the name of the variable with JAVA_HOME and the variable value with the path of Java, in my case:

C:\Program Files\Java\jdk

Tomcat_06_SystemProperties_Adding_NewVariable

As you can see the new variable was added.
Tomcat_07_EnvironmentVariables_OK


Optional changes to the Tomcat’s configuration.

Now we will make some changes optional on some files in the bin subdirectory inside of Tomcat folder.

To start Tomcat silently (without console window popup), change in the file named setclasspath.bat, the line set _RUNJAVA.

set _RUNJAVA="%JRE_HOME%\bin\javaw"

Tomcat_08_Editing_setclasspath-bat (_RUNJAVA)

Now, lets go to mak changes in the file service.bat in the bin subdirectory.

To change the service name and name to be displayed (this not alters of functionality of Tomcat’s service), we make this:

set SERVICE_NAME=Tomcat7.0.50
set PR_DISPLAYNAME=Tomcat7.0.50

Tomcat_09_Editing_service-bat (SERVICE_NAME,PR_DISPLAYNAME)

Later let’s go to modify the description of this service:

set PR_DESCRIPTION=Tomcat 7.0.50 Server

Tomcat_10_Editing_service-bat (PR_DESCRIPTION)

To start TOMCAT when Windows does, we make the following change:

"%EXECUTABLE%" //IS//%SERVICE_NAME% --Startup auto

Tomcat_11_Editing_service-bat (EXECUTABLE)

You can also set the directory where all web applications will be deployed, for this demostration, I made a new folder named Webapps located inside of ServerWeb.

C:\ServerWeb\Webapps\

Inside of this folder, I made other folder named http, specifically a context that represents an application.

C:\ServerWeb\Webapps\http\

These changes in the file server.xml will be:

      <Host name="localhost" appBase="C:/ServerWeb/Webapps"
            unpackWARs="true" autoDeploy="true">
      <Context path="" docBase="http"
            reloadable="true" />

Tomcat_12_Editing_server-xml (Host name, Context path)
With this configuration is possible to deploy applications in other folder different to initially established by default configuration.


Enabling File Uploads.

You may need to upload files, need to make changes to the file web.xml

Insert the multipart-config element to enable permanently for all applications file uploads, you can use the optional attributes max-file-size and max-request-size like here among others.

        <multipart-config>
          <max-file-size>3145728</max-file-size>
          <max-request-size>5242880</max-request-size>
        </multipart-config>

Tomcat_13_Editing_web-xml (multipart-config,max-file-size,max-request-size)
max-file-size The maximum size allowed for uploaded files, in bytes:
3145728 = 3 * 1024 * 1024
max-request-size The maximum size allowed for a multipart/form-data request, in bytes:
5242880 = 5 * 1024 * 1024


Changing the Compilers of Tomcat.

Some times is needed to change the Compilers of Tomcat, to do this we will need to change the web.xml file, according if you need change compilerSourceVM or compilerSourceVM:

        <init-param>
          <param-name>compilerSourceVM</param-name>
          <param-value>1.7</param-value>
        </init-param>
        <init-param>
          <param-name>compilerTargetVM</param-name>
          <param-value>1.7</param-value>
        </init-param>

Tomcat_21_Editing_web-xml (compilerSourceVM,compilerTargetVM)


Connecting Tomcat with Httpd.

We will need mod_jk module, when a page request comes in, if the request should be handled by Tomcat, Httpd the request to Tomcat via the connector (mod_jk module).

We need to download JK connector, currently is Tomcat Connectors 1.2.37 for Win32, hence the mod_jk.so file is extracted and copied into the Tomcat’s folder.

Within the conf folder create a file called workers.properties where is defined the Tomcat workers whose content is:

worker.list=ajp13
worker.ajp13.port=8009
worker.ajp13.host=localhost
worker.ajp13.type=ajp13

Tomcat_14_Creating workers-properties

Inside the folder conf also create a file called mod_jk.conf with content:

<IfModule !mod_jk.c>
  LoadModule jk_module "C:/ServerWeb/Tomcat/mod_jk.so"
</IfModule>
JkWorkersFile "C:/ServerWeb/Tomcat/conf/workers.properties"
JkLogFile "C:/ServerWeb/Tomcat/logs/mod_jk.log"
JkLogLevel info
<VirtualHost *:*>
  JkMount /*.jsp ajp13
</VirtualHost>

Tomcat_15_Creating_mod_jk-conf


Enabling MySQL to Tomcat.

To use MySQL with Tomcat is necessary to include the package allows, this package is called Connector/J. I downloaded called Connector/J 5.1.28 – Platform Independent and extracted the file named mysql-connector-java-5.1.22-bin.jar pasting it into the lib subdirectory of the Tomcat installation folder:

C:\ServerWeb\Tomcat\lib\


Operating the Tomcat Service.

We can to make the installation:

service.bat install

Tomcat_16_Installing

You can to start this service:

startup.bat

Tomcat_17_Starting

To stop this service:

shutdown.bat

Tomcat_18_Stopping

And remove it:

service.bat remove

Tomcat_19_Removing


HTTPD


Preparations for the Httpd installation.

I will use the Httpd 2.4.7 for Win32.
The contents of the .zip file was uncompressed in the folder:

C:\ServerWeb\Httpd_2.4.7\

But with symbolic link all operations of Httpd will be done under the folder:

C:\ServerWeb\Httpd\

To create the symbolic link for Httpd, use the command:

mklink /J "C:\ServerWeb\Httpd" "C:\ServerWeb\Httpd_2.4.7"

Httpd_00_mklink for Httpd

If you want to remove this link, you can use:

rd "C:\ServerWeb\Httpd"

Httpd_01_rd for Httpd


Working with the HTTPD configuration file httpd.conf.

Inside of conf subdirectory of Httpd folder there is one file containing the configuration of httpd with the name httpd.conf, this file need to be edited according to our requirements.

Edit the ServerRoot parameter updating the actual installation path.

ServerRoot "C:/ServerWeb/Httpd"

Httpd_02_Editing_httpd_conf (ServerRoot)

Edit the ServerAdmin parameter to the email address of the server administrator.

ServerAdmin joseluisbz@gmail.com

Httpd_03_Editing_httpd_conf (ServerAdmin)

Change the ServerName parameter to the server name and port to use.

ServerName ServerWeb:80

Httpd_04_Editing_httpd_conf (ServerName)

We edit the DocumentRoot (To set the directory from which httpd will serve files) and Directory (to define policies that only apply to the directory and subdirectories) parameters.

DocumentRoot "C:/ServerWeb/Webapps/http"
<Directory "C:/ServerWeb/Webapps/http">

Httpd_05_Editing_httpd_conf (DocumentRoot, Directory )

To avoid the directory listing when there isn’t index file, we delete the Indexes option.

    Options FollowSymLinks

Httpd_06_Editing_httpd_conf (Options )

To establish the order of precedence of predefined file to be displayed, we modify the value of DirectoryIndex parameter.

    DirectoryIndex index.php index.jsp index.html

Httpd_07_Editing_httpd_conf (DirectoryIndex )

For future use of CGI establish the required parameters.

    ScriptAlias /cgi-bin/ "C:/ServerWeb/Httpd/cgi-bin/"

Httpd_08_Editing_httpd_conf (ScriptAlias )

<Directory "C:/ServerWeb/Httpd/cgi-bin">

Httpd_09_Editing_httpd_conf (cgi-bin)

As you can see, here are the proposed changes have been completed.
Httpd_CountLines_00 Httpd


Including handling PHP to Httpd.

PHPIniDir indicates the folder where php.ini is located.
LoadModule php5_module loads the module that allow to Httpd handle Php files.
AddType indicates the extension to be identified or related with Php.

PHPIniDir "C:/ServerWeb/Php/"
LoadModule php5_module "C:/ServerWeb/Php/php5apache2_4.dll"
AddType application/x-httpd-php .php

Httpd_CountLines_01 Php


Including the Tomcat Connector to Httpd.

Include indicates where is located the configuration of Tomcat Connector.

Include "C:/ServerWeb/Tomcat/conf/mod_jk.conf"

Httpd_CountLines_02 Tomcat


Operating the Httpd Service.

We can to make the installation:

httpd.exe -k install -n "Httpd2.4.7" -f "C:\ServerWeb\Httpd\conf\httpd.conf"

Httpd_10_Installing

You can to start this service:

httpd.exe -k start -n "Httpd2.4.7"

Httpd_11_Starting

You can to restart this service:

httpd.exe -k restart -n "Httpd2.4.7"

Httpd_12_Restarting

To stop this service:

httpd.exe -k stop -n "Httpd2.4.7"

Httpd_13_Stopping

And uninstall it:

httpd.exe -k uninstall -n "Httpd2.4.7"

Httpd_14_Removing


Testing the Httpd (Php, Jsp) Installation.

Once you have followed the steps can test your installation.

Testing jsp pages.
Testing Installation Index-jsp

Testing php pages.
Testing Installation Index-php


I’m native Spanish speaker, please tell me English Language corrections.

Publicado en Apache, Apache Lounge, databases, Httpd, Instalación, Install, Java, JSP, Manually Installation, MySQL, PHP, Servidores Web, Software, Tomcat, Web Server, Windows | Etiquetado , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , | Deja un comentario

Manually Installing PHP with Tomcat only


Maybe this post is rare for someone, but I will try to explain how to install PHP working with Tomcat.
This tutorial was tested using Windows 7 of 32 bits.

PHP can works with the library named PECL, the last library that help us to reach the goal is the version 5.2.5.
The PECL 5.2.5 library contains .dll and .jar files that allow us to configure some (not all) PHP version with Tomcat.

All instalation will be made in the folder:

C:\ServerWeb\

PHP

The last version of PHP that works with that PECL version was the 5.2.16. Then I will use the PHP 5.2.16 for Win32.

The contents of the .zip file was uncompressed in the folder:

C:\ServerWeb\Php_5.2.16\

Inside of this folder there are two files containing templates of configuration of php:
php.ini-dist (for developing) and php.ini-recommended (for production), the difference consist into if the errors will be shown, while the version for developing shows the errors and other information, the version for production does not.
As I’m testing I took php.ini-dist and copied:

copy php.ini-dist php.ini

Coying php.ini

Now lets go to declare to system the path of the PHP.

Now, Is needed to access to variables system, with this manner or according to your preference:
sysdm.cpl

Later, the System Properties dialog box is shown.
SystemProperties2

Now, We select Advanced tab and press the Environment Variables button.
SystemProperties3

Here we select the PATH variable and press the Edit button.
SystemProperties4b

Finally modify the variable value adding at the end the path of PHP and press the OK button.
SystemProperties_EditingPath

Tomcat

The version of Tomcat tested that worked well was the 7.0.41, because 7.0.42 version had problems with starting and stopping in Windows. Then this post will work with Tomcat 7.0.41 for Win32.

The contents of the .zip file was uncompressed in the folder:

C:\ServerWeb\Tomcat_7.0.41\

Indicating to Tomcat the path of Java, using Environment Variables

In order to do this, we need to create a new variable with name JAVA_HOME, this variable is checked by Tomcat.
Similarly to declare to path of PHP, but we need to access to Environment Variables, pressing the New button.

SystemProperties5b

In the New System Variable dialog box, we write the name of the variable with JAVA_HOME and the variable value with the path of Java, in my case
C:\Program Files\Java\jdk1.7.0_45\
SystemProperties_Adding_NewVariable

As you can see the new variable was added.
SystemProperties6b

Now we will make some changes optional on some files in the subdirectory named bin inside the folder of Tomcat.

To start Tomcat silently (without console window popup), change in the file named setclasspath.bat, the line set _RUNJAVA

set _RUNJAVA="%JRE_HOME%\bin\javaw"

Editing_setclasspath_bat

Now, lets go to mak changes in the file service.bat in the subdirectory named bin.
To change the service name and name to be displayed (this not alters of functionality of Tomcat’s service), we make this:

set SERVICE_NAME=Tomcat7.0.41
set PR_DISPLAYNAME=Tomcat7.0.41

Editing_service_bat

Later let’s go to modify the description of this service:

set PR_DESCRIPTION=Tomcat 7.0.41 Server

Editing_service_bat2

To start Tomcat when Windows does, we make the following change:

"%EXECUTABLE%" //IS//%SERVICE_NAME% --Startup auto

Editing_service_bat3

We can modify our web server port, which is initially set to 8080, change it to 80, in this case we need to make changes in the file server.xml in the subdirectory named conf inside the folder of Tomcat.
Editing Server_xml1

You can also set the directory where all web applications will be deployed, for this demostration, I made a new folder named Webapps located inside of ServerWeb.

C:\ServerWeb\Webapps\

Inside of this folder, I made other folder named http, specifically a context that represents an application.

C:\ServerWeb\Webapps\http\

These changes in the file server.xml will be:

      <Host name="localhost" appBase="C:/ServerWeb/Webapps"
            unpackWARs="true" autoDeploy="true">
      <Context path="" docBase="http"
            reloadable="true" />

Editing Server_xml2b
With this configuration is possible to deploy applications in other folder different to initially established by default configuration.

We can to make the installation:

service.bat install

Installing service_bat
This service can be verified in Windows.
Services
You can to start this service:

startup.bat

Starting service_bat
To stop this service:

shutdown.bat

Stoping service_bat
And remove:

service.bat remove

Removing service_bat

Integrating Tomcat with PHP

This changes are in order to use PHP with Tomcat.

Download the PHP Extension Community Library version 5.2.5 for Win32.

For this example, I will unpack the contents to (although this is not necessary):

C:\ServerWeb\Pecl_5.2.5\

Copy the file php5servlet.dll from the pecl-5.2.5-Win32.zip to the folder C:\ServerWeb\Php_5.2.16\

Copy the file php_java.dll from the pecl-5.2.5-Win32.zip to the folder C:\ServerWeb\Php_5.2.16\ext\

In order to make use of php_java.dll we need to make changes in the configuration file of PHP, php.ini, adding a new line like is shown below.

extension=php_java.dll

Editing_php_ini
So far everything is ready as far as PHP is concerned.

Copy the file php_java.jar from the pecl-5.2.5-Win32.zip to the folder C:\ServerWeb\Tomcat_7.0.41\lib\

Now, we need to make changes in the file named phpsrvlt.jar and create a new file named php5srvlt.jar
First, we need to uncompress the file with (in my case):

"C:\Program Files\Java\jdk1.7.0_45\bin\jar.exe" xfv phpsrvlt.jar

Extracting File from phpsrvlt_jar
Second, as can be seen, two folders are decompressed one call net, inside which there is another folder named php. In this folder php there are multifle files, including one called reflect.properties and another called servlet.properties. The contents of both files must be:

library=php5servlet

Editing Reflect_Properties_b
Editing Servlet_Propertiesb
As you can see, without spaces.
Third, let’s go to create the needed file:

"C:\Program Files\Java\jdk1.7.0_45\bin\jar.exe" cvf php5srvlt.jar net/php/

Adding File to php5srvlt_jar
Fourth, include the php5srvlt.jar file to be used by applications in Tomcat, copying this file into subdirectory lib of Tomcat Directory C:\ServerWeb\Tomcat_7.0.41\lib\ in this case will be available for all applications of Tomcat.

Now, We need to modify the file web.xml (Deployment Descriptor) in the subdirectory named conf inside of Tomcat installation folder.

First change: declaring the name of servlet and its classes.

    <servlet>
      <servlet-name>php</servlet-name>
      <servlet-class>net.php.servlet</servlet-class>
    </servlet>
    <servlet>
      <servlet-name>php-formatter</servlet-name>
      <servlet-class>net.php.formatter</servlet-class>
    </servlet>

Editing Web_xml1

Second change: including the mapping of the servlets and classes declared before.

    <!-- The mappings for the PHP servlet -->
    <servlet-mapping>
      <servlet-name>php</servlet-name>
      <url-pattern>*.php</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
      <servlet-name>php-formatter</servlet-name>
      <url-pattern>*.phps</url-pattern>
    </servlet-mapping>

Editing Web_xml2

Third change: including and establishing the files and its order in which the default servlet looks for the "welcome file".

        <welcome-file>index.php</welcome-file>

Editing Web_xml3

Last we will test the integration, creating a file named test.php inside of
C:\ServerWeb\Webapps\http\, the content is:

<?
  phpinfo();
?>

Creating test_php
Testing test_php

Publicado en Instalación, Instalación, Install, Java, JSP, Manually Installation, PHP, Server, Servidores Web, Software, Tomcat, Web Server, Windows | Etiquetado , , , , , , , , , , , , , , ,

Obtaining Size or Dimension of Images


This Post will help you to obtain the Height or Width of one Image if the type correspond to (BMP, PNG, GIF, JPG, TIF or WMF).

Now, I made a resume of code (Java, PHP) with this porpouse.

Obtaining of the Image’s Bytes

ImageFileName: is the path of file of the image.
BF: is an array of bytes containing the image’s information.

Java

byte[] BF = new byte[(int)(new File(ImageFileName).length())];
FileInputStream fis;
try {
  fis = new FileInputStream(ImageFileName);
  fis.read(BF);
  fis.close();
}
catch (FileNotFoundException fnfe) { }
catch (EOFException eofe) { }

PHP

$fis = fopen($ImageFileName, "rb");
if ($fis!=false) {
  $BF = NULL;
  while (!feof($fis)) {
    $BF .= fread($fis, 8192);
  }
  fclose($fis);
}

Reading With Scripts

JSP

byte[] BF = null;
int Height = 0;
int Width = 0;
String Type = null;
if(ServletFileUpload.isMultipartContent(request)) {
  ServletFileUpload SFU = new ServletFileUpload(new DiskFileItemFactory());
  try {
    List mylist = SFU.parseRequest(request);
    for (int i = 0; i < mylist.size(); i++) {
      FileItem FItem = (FileItem)mylist.get(i);
      if (FItem.getFieldName().equals("SelectFile")) {
        if (FItem.getName().length() > 0) {
          out.println("<br>"+"The Name of Image is: "+FItem.getName()+"<br>");
          BF = FItem.get();
        }
        break;
      }
    }
  }
  catch(FileUploadException e) { out.println(e.toString()); }
}

PHP

$BF = NULL;
$Height = 0;
$Width = 0;
$Type = NULL;
if (is_uploaded_file($_FILES["SelectFile"]["tmp_name"])) {
  print("<br>"."The Name of Image is: ".$_FILES["SelectFile"]["name"]."<br>");
  $fis = fopen($_FILES["SelectFile"]["tmp_name"], "rb");
  if ($fis!=false) {
    while (!feof($fis)) {
      $BF .= fread($fis, 8192);
    }
    fclose($fis);
  }
}

Bytes to Integer – Big Endianness

Java

int Byte2IntBig(byte Byte08, byte Byte00) {
  return (
      ((Byte08) << 8)|
      ((Byte00 & 0xFF) << 0));
}
int Byte2IntBig(byte Byte24, byte Byte16, byte Byte08, byte Byte00) {
  return (
      ((Byte24) << 24)|
      ((Byte16 & 0xFF) << 16)|
      ((Byte08 & 0xFF) << 8)|
      ((Byte00 & 0xFF) << 0));
}

PHP

function Byte2IntBig($Byte08, $Byte00) {
  if (func_num_args() == 4) {
    $argv = func_get_args();
    $Byte24 = $argv[0];
    $Byte16 = $argv[1];
    $Byte08 = $argv[2];
    $Byte00 = $argv[3];
    return (
        ($Byte24 << 24)|
        (($Byte16 & 0xFF) << 16)|
        (($Byte08 & 0xFF) << 8)|
        (($Byte00 & 0xFF) << 0));
  } else {
    if ($Byte08 > 127) {
      return (Byte2IntBig(255, 255, $Byte08, $Byte00));
    } else {
      return (
          ($Byte08 << 8)|
          (($Byte00 & 0xFF) << 0));
    }
  }
}

Bytes to Integer – Little Endianness

Java

int Byte2IntLit(byte Byte00, byte Byte08) {
  return (
      ((Byte08) << 8)|
      ((Byte00 & 0xFF) << 0));
}
int Byte2IntLit(byte Byte00, byte Byte08, byte Byte16, byte Byte24) {
  return (
      ((Byte24) << 24)|
      ((Byte16 & 0xFF) << 16)|
      ((Byte08 & 0xFF) << 8)|
      ((Byte00 & 0xFF) << 0));
}

PHP

function Byte2IntLit($Byte00, $Byte08) {
  if (func_num_args() == 4) {
    $argv = func_get_args();
    $Byte00 = $argv[0];
    $Byte08 = $argv[1];
    $Byte16 = $argv[2];
    $Byte24 = $argv[3];
    return (
        ($Byte24 << 24)|
        (($Byte16 & 0xFF) << 16)|
        (($Byte08 & 0xFF) << 8)|
        (($Byte00 & 0xFF) << 0));
  } else {
    if ($Byte08 > 127) {
      return (Byte2IntLit($Byte00, $Byte08, 255, 255));
    } else {
      return (
          ($Byte08 << 8)|
          (($Byte00 & 0xFF) << 0));
    }
  }
}

Integer to Bytes – Big Endianness

Java

byte[] Int2ByteBig(Integer int0) {
  byte[] ArregloByte = new byte[4];
  ArregloByte[0] = (byte)((int0 >> 0) & 0xFF);
  ArregloByte[1] = (byte)((int0 >> 8) & 0xFF);
  ArregloByte[2] = (byte)((int0 >> 16) & 0xFF);
  ArregloByte[3] = (byte)((int0 >> 24) & 0xFF);
  return ArregloByte;
}

PHP

function Int2ByteBig($int0) {
  $ArregloByte = array();
  $ArregloByte[] = (($int0 >> 0) & 0xFF);
  $ArregloByte[] = (($int0 >> 8) & 0xFF);
  $ArregloByte[] = (($int0 >> 16) & 0xFF);
  $ArregloByte[] = (($int0 >> 24) & 0xFF);
  return $ArregloByte;
}

Integer to Bytes – Little Endianness

Java

byte[] Int2ByteLit(Integer int0) {
  byte[] ArregloByte = new byte[4];
  ArregloByte[0] = (byte)((int0 >> 24) & 0xFF);
  ArregloByte[1] = (byte)((int0 >> 16) & 0xFF);
  ArregloByte[2] = (byte)((int0 >> 8) & 0xFF);
  ArregloByte[3] = (byte)((int0 >> 0) & 0xFF);
  return ArregloByte;
}

PHP

function Int2ByteLit($int0) {
  $ArregloByte = array();
  $ArregloByte[] = (($int0 >> 24) & 0xFF);
  $ArregloByte[] = (($int0 >> 16) & 0xFF);
  $ArregloByte[] = (($int0 >> 8) & 0xFF);
  $ArregloByte[] = (($int0 >> 0) & 0xFF);
  return $ArregloByte;
}

BMP

Java

if (BF[0]==(byte)66 && BF[1]==(byte)77) {
  Type = "BMP";
  Height = Byte2IntLit(BF[22],BF[23]);
  Width = Byte2IntLit(BF[18],BF[19]);
}

PHP

if ($BF[0]==chr(66) && $BF[1]==chr(77)) {
  $Type = "BMP";
  $Height = Byte2IntLit(ord($BF[22]),ord($BF[23]));
  $Width = Byte2IntLit(ord($BF[18]),ord($BF[19]));
}

PNG

Java

if (BF[0]==(byte)137 && BF[1]==(byte)80 && BF[2]==(byte)78) {
  Type = "PNG";
  Height = Byte2IntBig(BF[22],BF[23]);
  Width = Byte2IntBig(BF[18],BF[19]);
}

PHP

if ($BF[0]==chr(137) && $BF[1]==chr(80) && $BF[2]==chr(78)) {
  $Type = "PNG";
  $Height = Byte2IntBig(ord($BF[22]),ord($BF[23]));
  $Width = Byte2IntBig(ord($BF[18]),ord($BF[19]));
}

GIF

Java

if (BF[0]==(byte)71 && BF[1]==(byte)73 && BF[2]==(byte)70) {
  Type = "GIF";
  Height = Byte2IntLit(BF[8],BF[9]);
  Width = Byte2IntLit(BF[6],BF[7]);
}

PHP

if ($BF[0]==chr(71) && $BF[1]==chr(73) && $BF[2]==chr(70)) {
  $Type = "GIF";
  $Height = Byte2IntLit(ord($BF[8]),ord($BF[9]));
  $Width = Byte2IntLit(ord($BF[6]),ord($BF[7]));
}

JPG

Java

if (BF[0]==(byte)255 && BF[1]==(byte)216 && BF[2]==(byte)255 && BF[3]==(byte)224) {
  int PJPG = 2;
  while (PJPG < BF.length) {
    String M = String.format("%02X%02X", BF[PJPG+0],BF[PJPG+1]);
    if (M.equals("FFC0") || M.equals("FFC1") || M.equals("FFC2") ||         M.equals("FFC3")) {
      Type = "JPG";
      Height = Byte2IntBig(BF[PJPG+5],BF[PJPG+6]);
      Width = Byte2IntBig(BF[PJPG+7],BF[PJPG+8]);
    }
    if (M.equals("FFDA")) {
      break;
    }
    PJPG = PJPG+2+Byte2IntBig(BF[PJPG+2],BF[PJPG+3]);
  }
}

PHP

if ($BF[0]==chr(255) && $BF[1]==chr(216) && $BF[2]==chr(255) && $BF[3]==chr(224)) {
  $PJPG = 2;
  while ($PJPG < strlen($BF)) {
    $M = sprintf("%02X%02X", ord($BF[$PJPG+0]),ord($BF[$PJPG+1]));
    if ($M=="FFC0" || $M=="FFC1" || $M=="FFC2" || $M=="FFC3") {
      $Type = "JPG";
      $Height = Byte2IntBig(ord($BF[$PJPG+5]),ord($BF[$PJPG+6]));
      $Width = Byte2IntBig(ord($BF[$PJPG+7]),ord($BF[$PJPG+8]));
    }
    if ($M=="FFDA") {
      break;
    }
    $PJPG = $PJPG+2+Byte2IntBig(ord($BF[$PJPG+2]),ord($BF[$PJPG+3]));
  }
}

TIF – Little Endianness

Java

if (BF[0]==(byte)73 && BF[1]==(byte)73 && BF[2]==(byte)42 && BF[3]==(byte)0) {
  int PTIF = Byte2IntLit(BF[4],BF[5],BF[6],BF[7]);
  Type = "TIF";
  int NumDirEntries = Byte2IntLit(BF[PTIF+0],BF[PTIF+1]);
  PTIF += 2;
  for (int i = 0; i < NumDirEntries;i++) {
    if (String.format("%02X%02X", BF[PTIF+0],BF[PTIF+1]).equals("0101")) {
      Height = Byte2IntLit(BF[PTIF+8],BF[PTIF+9]);
    }
    if (String.format("%02X%02X", BF[PTIF+0],BF[PTIF+1]).equals("0001")) {
      Width = Byte2IntLit(BF[PTIF+8],BF[PTIF+9]);
    }
    PTIF += 12;
  }
}

PHP

if ($BF[0]==chr(73) && $BF[1]==chr(73) && $BF[2]==chr(42) && $BF[3]==chr(0)) {
  $PTIF = Byte2IntLit(ord($BF[4]),ord($BF[5]),ord($BF[6]),ord($BF[7]));
  $Type = "TIF";
  $NumDirEntries = Byte2IntLit(ord($BF[$PTIF+0]),ord($BF[$PTIF+1]));
  $PTIF += 2;
  for ($i = 0; $i < $NumDirEntries;$i++) {
    if (sprintf("%02X%02X", ord($BF[$PTIF+0]),ord($BF[$PTIF+1]))=="0101") {
      $Height = Byte2IntLit(ord($BF[$PTIF+8]),ord($BF[$PTIF+9]));
    }
    if (sprintf("%02X%02X", ord($BF[$PTIF+0]),ord($BF[$PTIF+1]))=="0001") {
      $Width = Byte2IntLit(ord($BF[$PTIF+8]),ord($BF[$PTIF+9]));
    }
    $PTIF += 12;
  }
}

TIF – Big Endianness

Java

if (BF[0]==(byte)77 && BF[1]==(byte)77 && BF[2]==(byte)0 && BF[3]==(byte)42) {
  int PTIF = Byte2IntBig(BF[4],BF[5],BF[6],BF[7]);
  Type = "TIF";
  int NumDirEntries = Byte2IntBig(BF[PTIF+0],BF[PTIF+1]);
  PTIF += 2;
  for (int i = 0; i < NumDirEntries;i++) {
    if (String.format("%02X%02X", BF[PTIF+0],BF[PTIF+1]).equals("0101")) {
      Height = Byte2IntBig(BF[PTIF+8],BF[PTIF+9]);
    }
    if (String.format("%02X%02X", BF[PTIF+0],BF[PTIF+1]).equals("0100")) {
      Width = Byte2IntBig(BF[PTIF+8],BF[PTIF+9]);
    }
    PTIF += 12;
  }
}

PHP

if ($BF[0]==chr(77) && $BF[1]==chr(77) && $BF[2]==chr(0) && $BF[3]==chr(42)) {
  $PTIF = Byte2IntBig(ord($BF[4]),ord($BF[5]),ord($BF[6]),ord($BF[7]));
  $Type = "TIF";
  $NumDirEntries = Byte2IntBig(ord($BF[$PTIF+0]),ord($BF[$PTIF+1]));
  $PTIF += 2;
  for ($i = 0; $i < $NumDirEntries;$i++) {
    if (sprintf("%02X%02X", ord($BF[$PTIF+0]),ord($BF[$PTIF+1]))=="0101") {
      $Height = Byte2IntBig(ord($BF[$PTIF+8]),ord($BF[$PTIF+9]));
    }
    if (sprintf("%02X%02X", ord($BF[$PTIF+0]),ord($BF[$PTIF+1]))=="0100") {
      $Width = Byte2IntBig(ord($BF[$PTIF+8]),ord($BF[$PTIF+9]));
    }
    $PTIF += 12;
  }
}

WMF – D7CDC69A

Java

if (BF[0]==(byte)215 && BF[1]==(byte)205 && BF[2]==(byte)198 && BF[3]==(byte)154) {
  Type = "WMF";
  int L = Byte2IntLit(BF[6],BF[7]);
  int T = Byte2IntLit(BF[8],BF[9]);
  int R = Byte2IntLit(BF[10],BF[11]);
  int B = Byte2IntLit(BF[12],BF[13]);
  Height = B-T;
  Width = R-L;
}

PHP

if ($BF[0]==chr(215) && $BF[1]==chr(205) && $BF[2]==chr(198) && $BF[3]==chr(154)) {
  $Type = "WMF";
  $L = Byte2IntLit(ord($BF[6]),ord($BF[7]));
  $T = Byte2IntLit(ord($BF[8]),ord($BF[9]));
  $R = Byte2IntLit(ord($BF[10]),ord($BF[11]));
  $B = Byte2IntLit(ord($BF[12]),ord($BF[13]));
  $Height = $B-$T;
  $Width = $R-$L;
}

WMF – 01000900, 02000900

Java

if ((BF[0]==(byte)1 || BF[0]==(byte)2) && BF[1]==(byte)0 && BF[2]==(byte)9 &&     BF[3]==(byte)0) {
  int PWMF = 18;
  int SizeR;
  while(PWMF < BF.length) {
    SizeR = Byte2IntLit(BF[PWMF+0],BF[PWMF+1],BF[PWMF+2],BF[PWMF+3]);
    if (String.format("%02X%02X", BF[PWMF+5],BF[PWMF+4]).equals("020C")) {
      Type = "WMF";
      Height = Byte2IntLit(BF[PWMF+6],BF[PWMF+7]);
      Width = Byte2IntLit(BF[PWMF+8],BF[PWMF+9]);
    }
    PWMF += (2*SizeR);
  }
}

PHP

if (($BF[0]==chr(1) || $BF[0]==chr(2)) && $BF[1]==chr(0) && $BF[2]==chr(9) &&     $BF[3]==chr(0)) {
  $PWMF = 18;
  $SizeR;
  while($PWMF < strlen($BF)) {
    $SizeR = Byte2IntLit(ord($BF[$PWMF+0]),ord($BF[$PWMF+1]),         ord($BF[$PWMF+2]),ord($BF[$PWMF+3]));
    if (sprintf("%02X%02X", ord($BF[$PWMF+5]),ord($BF[$PWMF+4]))=="020C") {
      $Type = "WMF";
      $Height = Byte2IntLit(ord($BF[$PWMF+6]),ord($BF[$PWMF+7]));
      $Width = Byte2IntLit(ord($BF[$PWMF+8]),ord($BF[$PWMF+9]));
    }
    $PWMF += (2*$SizeR);
  }
}

Publicado en Dimension, Image, Size | Etiquetado , , , , , , , , , , , , , , , , , | Deja un comentario

Exploring a WMF File, (0X000900)


Porpouse

Maybe, you are looking for to understand how is stored the Image in formation in WMF File according to explanation of this Format, Microsoft has this file WindowsMetafileFormat(wmf)Specification.pdf

Limitations

This post is centered in the file that starts with 01 00 09 00 (01000900), this article can be used too with files WMF starting with 02 00 09 00 (02000900).

Obtaining One Sample of this File Type

In order to obtain this file I made one .BMP File SquareColor.bmp

SquareColor.BMP

Using Wordpad of Microsoft Windows 7 the file was inserted in one .RTF File SquareColor.rtf

SquareColor.RTF

The image is converted from the original format and stored (using text of hexadecimal representation) between this code:

{\rtf1\ansi\ansicpg1252\deff0\deflang9226{\fonttbl{\f0\fnil\fcharset0 Calibri;}}
{\*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\sa200\sl240\slmult1\lang10\f0\fs22{\pict\wmetafile8\picw6773\pich6773\picwgoal3840\pichgoal3840

}\par
\pard\sa200\sl276\slmult1\par
}

SquareColor.RTF_NotepadThe File is obtained, converting the text representation of each byte in one byte and all bytes are stored in new file with .WMF extension. Here is the final .WMF file SquareColor.wmf

Now You can see this image:
SquareColor.WMFNow you can see the comparation between .WMF and .BMP

SquareColor_Comparation

Inside of 0X000900 WMF File

The file can be find in two versions in 01000900 or 02000900.

The File uses Little Endianness representation.

In Hexadecimal 01 00 represents 1 in Decimal
In Hexadecimal 00 01 represents 256 in Decimal

First Control Record: META_HEADER

The first control record contains fields detailed in the Page 116 of File Specificacion, the fields are:

Type

HexRepresentation_SquareColor_aType
The first two bytes 1(01) and 2(00) describes the type of file, in this case 00 01 that means the type is MEMORYMETAFILE, the page 40 describe the two types.

HeaderSize

HexRepresentation_SquareColor_aHeaderSize
The bytes 3(09) and 4(00) represents the size of this Control Record, in this case 00 09, 9 Words, equivalent to 18 bytes.

Version of MetaFile

The Bytes 5(00) and 6(03), are describing the version of MetaFile, for our WMF File Example the version is: 03 00 corresponding to METAVERSION300 according to Page 40 of Specification File.

HexRepresentation_SquareColorVersion

Size of File

The Bytes 7(6A), 8(40), 9(00) and 10(00) Stores the file size expressed in Words (two byte), in hexadecimal 00 00 40 6A represents 16490 Words in decimal; Expressed in bytes 2×16490 this is 32980 bytes.

HexRepresentation_SquareColorFileSize

Objects Number

The Bytes 11(00) and 12(00) Indicates the number of objects contained in the file. According to this there is not objects in the file.

HexRepresentation_SquareColor_ObjectsNumber

Largest Record

The Bytes 13(41), 14(40), 15(00) and 16(00) Says us that the largest record of contained in the file is in hexadecimal 00 00 40 41 and in bytes 32898.

HexRepresentation_SquareColor_MaxRecord

Members Number

The Bytes 17(00) and 18(00) Are not used.

HexRepresentation_SquareColor_NotUsed

Other Records

The records are stored in serial mode (one after another).
The first four bytes (two words) indicate the size of record, the following two bytes (one word) indicate the operation or function. The remaining bytes (Size in bytes less six bytes) are the function argument.

In this file we have several records, I made in Java an extraction of this information (Only is applicable to this file .wmf).

Table_FunctionsThe position of this application starts from 0, but the position of this post starts from 1; Thus, The byte 19th of this post is stored in the position 18th of this picture; and so on for the remainder.

Record 2

HexRepresentation_SquareColor_META_SETMAPMODE The bytes 19(04), 20(00), 21(00) and 22(00) tell us the size of this record is 8 bytes (4 words); the record is stored in the bytes from 19 until 26, according to byte 23(03) and byte 24(01) the  function code is 0103 that correspond to META_SETMAPMODE, and the argument is stored in the remaining 2 bytes 25(08) and 26(00) with code 0008 that correspond to MM_ANISOTROPIC.

Record 3

HexRepresentation_SquareColor_META_SETWINDOWORGThe bytes 27(05), 28(00), 29(00) and 30(00) tell us the size of this record is 10 bytes (5 words); the record is stored in the bytes from 27 until 36, according to byte 31(0B) and byte 32(02) the function code is 020B that correspond to META_SETWINDOWORG, and the argument is stored in the remaining 4 bytes 33(00), 34(00), 35(00) and 36(00) . According to this function the first two bytes represents horizontal position (0 in this case) and the last two bytes represents the vertical position (0 in this case), in this manner the position is 0,0.

Record 4

HexRepresentation_SquareColor_META_SETWINDOWEXTThe bytes 37(05), 38(00), 39(00) and 40(00) represents the size of this record is 10 bytes (5 words); the record is stored in the bytes from 37 until 46, according to byte 41(0C) and byte 42(02) the function code is 020C that correspond to META_SETWINDOWEXT, and the argument is stored in the remaining 4 bytes 43(00), 44(01), 45(00) and 46(01) . According to this function the first two bytes represents horizontal size (256 in this case) and the last two bytes represents the vertical size (256 in this case), in this manner the dimension is 256×256.

Record 5

HexRepresentation_SquareColor_META_SAVEDCNow we have a record that only contains, the size 6 bytes (3 words) represented by the bytes 47(03), 48(00), 49(00) and 50(00) and the function code 001E stored in the bytes 51(1E) and 52(00) that is META_SAVEDC.

Record 6

HexRepresentation_SquareColor_META_SETSTRETCHBLTMODEThe Record 6 has a size 8 bytes, stored from the byte 53 until the byte 60, the function code is 0107 representing META_SETSTRETCHBLTMODE and the argument is 0004 equivalent HALFTONE.

Record 7

HexRepresentation_SquareColor_META_SETSTRETCHBLTMODE_2

The record 7 is similar to the record 6, with the difference that is stored from the bytes 61 until the byte 68.

Record 8

HexRepresentation_SquareColor_META_DIBSTRETCHBLT

Maybe is the record most important of this file.

The size is 32898 bytes according to the bytes 69(41), 70(40), 71(00) and 72(00).
The function code from byte 73(41) and byte 74(0B) is 0B41 that means META_DIBSTRETCHBLT following the page 109 of Specification File we have more arguments like this:
HexRepresentation_SquareColor_META_DIBSTRETCHBLT_SRCCOPY
Raster Operation is stored in bytes 75(20), 76(00), 77(CC) and 78(00) is 00CC0020 equivalent to SRCCOPY can be verified in the page 71.
SrcHeight is stored in the bytes 79(00) and 80(01) is 0100 equivalent to 256.
SrcWidth is stored in the bytes 81(00) and 82(01) is 0100 equivalent to 256.
YSrc is stored in the bytes 83(00) and 84(00) is 0000 equivalent to 0.
XSrc is stored in the bytes 85(00) and 86(00) is 0000 equivalent to 0.
DestHeight is stored in the bytes 87(00) and 88(01) is 0100 equivalent to 256.
DestWidth is stored in the bytes 89(00) and 90(01) is 0100 equivalent to 256.
YDest is stored in the bytes 91(00) and 92(00) is 0000 equivalent to 0.
XDest is stored in the bytes 93(00) and 94(00) is 0000 equivalent to 0.

The Record contains a DIB (Device Independent Bitmap) described in the page 92 with BitmapInfoHeader described in the page 80, like:

HexRepresentation_SquareColor_META_DIBSTRETCHBLT_DIB
HeaderSize is stored in the bytes 95(28), 96(00), 97(00) and 98(00) is 00000028 equivalent to 40 bytes.
Width is stored in the bytes 99(00), 100(01), 101(00) and 102(00) is 00000100 equivalent to 256.
Height is stored in the bytes 103(00), 104(01), 105(00) and 106(00) is 00000100 equivalent to 256.
Planes is stored in the bytes 107(01) and 108(00) 0001 equivalent to 1, Page 81.
BitCount is stored in the bytes 109(04) and 110(00) 0004 equivalent to BI_BITCOUNT_2, Page 25.
Compression is stored in the bytes 111(00), 112(01), 113(00) and 114(00) is 00000000 equivalent to BI_RGB, Page 29.
ImageSize is stored in the bytes 115(00), 116(01), 117(00) and 118(00) is 00000000 This may be set to 0 for BI_RGB, Page 81.
XPelsPerMeter is stored in the bytes 119(00), 120(01), 121(00) and 122(00) is 00000000.
YPelsPerMeter is stored in the bytes 123(00), 124(01), 125(00) and 126(00) is 00000000.
ColorUsed is stored in the bytes 127(00), 128(01), 129(00) and 130(00) is 00000000, the bitmap uses the maximum number of colors.
ColorImportant is stored in the bytes 131(00), 132(01), 133(00) and 134(00) is 00000000, where all colors are required.
You can see that this example contains a field named ColorUsage stored in the bytes 135(00), 136(00), 137(00) and 138(00), equivalent to DIB_RGB_COLORS, Page 29.
The aData Is the last field of this record, consist in array of bytes(with variable size) defining the actual bitmap bits.

Record 9

HexRepresentation_SquareColor_META_RESTOREDC

In this case, the record 9 is located just before the last record, this penultimate record has a size of 8 bytes (4 words), the funcion code is 0127 refering to META_RESTOREDC and like the value of its argument named nSavedDC is FF FF equivalent to negative number, nSavedDC represents an instance relative to the current state.

Last Control Record: META_EOF

HexRepresentation_SquareColor_META_EOF

The last record is incated with a record of the last 6 bytes (3 words), as you can see the function code in this case is stored in the last two bytes with penultimate byte (00) and last byte (00) this is 0000 belongs to META_EOF.

Modifications

Now, I post a file example with some modifications that allow us, to view the behaviour with this changes.
The size of the original image is 256x256, now the product of the vertical size with the horizontal size is the total image size equal to 65536, this size was stablished because changing original vertical and horizontal symmetrically this total image size can be preserved with the same value. Example of this is 128x512 or 512x128, the changes can be made following the Height and Width dimension stored in the original file and detailed in this post.

Just like that we was reviewing the post the 256 number is represented in hexadecimal like 100, if 2 bytes are used with Little Endianness representation will be 1(00) and the 2(01): 00 01; if 4 bytes are used in this case the representation will be 1(00), 2(01), 3(00) and 4(00): 00 01 00 00.
The decimal number 128 is represented in hexadecimal like 80, if 2 bytes are used with Little Endianness representation will be 1(80) and the 2(00): 80 00; if 4 bytes are used in this case the representation will be 1(80), 2(00), 3(00) and 4(00): 80 00 00 00.
The decimal number 512 is represented in hexadecimal like 200, if 2 bytes are used with Little Endianness representation will be 1(00) and the 2(02): 00 02; if 4 bytes are used in this case the representation will be 1(00), 2(02), 3(00) and 4(00): 00 02 00 00.

Now just we need change one 256 by 128 y the other 256 by 512, according to which dimension we want to establish.

Comparation_SquareColor

The result for Height 512, Width 128 is:

SquareColorH
SquareColorH.WMF

The result for Height 128, Width 512 is:

SquareColorV
SquareColorV.WMF

Now if you have comments, please let me know.

Publicado en Dimension, Image, Size | Etiquetado , , , , , , , , , , , , | Deja un comentario