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.

Publicado en Scripts, Server, Software, Tomcat, Web Server, Windows | Etiquetado , , , | 2 comentarios

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 , , , , , , , , , , , , , , , | Comentarios desactivados en Manually Installing PHP with Tomcat only

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 , , , , , , , , , , , , , , , , , | 1 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

Instalando manualmente MySQL


Objetivo

Esta entrada de MySQL es para completar la instalación manual que en la entrada anterior había tratado.

Al igual que la entrada anterior la instalación se realizó en una máquina con sistema operativo Windows 7 de 32 bits. Y la carpeta de trabajo es:

C:\ServerWeb\

Para este ejemplo descargué MySQL 5.5.28 versión Community Server (mysql-5.5.28-win32.zip) y esta carpeta la descomprimí en:

C:\ServerWeb\Mysql_5.5.28\

de igual manera sin espacios.

Arrancamos la consola CMD en modo administrador

y nos vamos a la siguiente ubicación o carpeta.

C:\ServerWeb\Mysql_5.5.28\

Verificamos los diferentes archivos de preconfiguración disponible en esta carpeta y copiamos el más apropiado a nuestros requerimientos, en este caso, seleccioné la versión mediana para copiarla y conservar los archivos originales:

copy my-medium.ini my.ini

Ahora procederemos a cambiar el archivo nuevo my.ini según la configuración que requiramos:

#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/ServerWeb/Mysql_5.5.28/"
#Path to the database root
datadir="C:/ServerWeb/Mysql_5.5.28/Data/"


Indicamos en la variable basedir la carpeta de instalación de MySQL y en la variable datadir la carpeta donde se almacenarán los datos de MySQL.

# The default character set that will be used when a new schema or table is
# created and no character set is defined
character-set-server=utf8


En la variable character-set-server indicamos el conjunto de caracteres usados cuando se cree un anueva base de datos o tablas predefinidamente si no se indica de manera explícita en la creación de las mismas.

# When you create a new table, you can specify which storage engine to use by
# adding an ENGINE table option to the CREATE TABLE statement
# If you omit the ENGINE option, the default storage engine is used.
default-storage-engine=INNODB
# The MySQL server can operate in different SQL modes, and can apply these modes
# differently for different clients. This capability enables each application to
# tailor the server’s operating mode to its own requirements.
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"


También se puede establecer de manera predefinida el tipo de storage engine usado cuando no se indique de manera explícita, al crear una nueva tabla con la variable default-sotrage-engine; también con la variable sql-mode se puede especificar el modo en que debe operar MySQL Server.

max_connections=50
query_cache_size=0
table_cache=256
tmp_table_size=13M
thread_cache_size=8


Algunos otros valores son establecidos para que el servidor se comporten, por ejemplo que puedan acceder múltiples conexiones y los recursos que se dispondrán para ello.

max_allowed_packet = 2M


Al modificar la variable max_allowed_packet indicamos el tamaño máximo de paquete almacenado.

#Use default-character-set as the default character set for the client and connection.
default-character-set=utf8


Por último en la variable default-character-set establecemos el conjunto de caracteres usados por los clientes y las conexiones.

Ahora vamos a registrar la ruta de ubicación de MySQL ante windows, para ello vamos a cambiar las variable de entorno llamada Path.

Se abrirá la caja de diálogo propiedades del sistema, aunque se pueden usar los pasos habituales según la versión de Windows que se tenga en uso.

Elegimos opciones avanzadas


En variables del sistema seleccionamos la variable Path.


Al final del valor de la variable Path, agregamos ; (punto y coma) y luego la ruta de ubicación de MySQL.

Ahora procederemos a instalar a MySQL como un servicio el cual he llamado MySQL5.5.28 y con la configuración que he copiado y editado según los ajustes requeridos en el archivo c:\ServerWeb\Mysql_5.5.28\my.ini.

mysqld.exe –install MySQL5.5.28 –defaults-file=c:\ServerWeb\Mysql_5.5.28\my.ini

Después de instalado el servicio se puede iniciar con la setencia en la consola de comandos de windows.

NET START MySQL5.5.28

Podemos ver que se ha podido acceder al sistema sin password alguno, inclusive para el usuario root.

SELECT host, user, password FROM mysql.user;

Verificando los usuarios ninguno tiene password.

Al salir de MySQL y cambiar el password desde la herramienta de administración de MySQL tenemos:

mysqladmin.exe -u root password "admin"

No es necesario usar la extensión .exe.

Ahora para acceder a MySQL en modo root solicitará el password de acceso, que para este ejemplo fue admin obviamente para un sistema real ha de elegirse un password más seguro.

Al verificar el estado de los password para root se puede ver que solo ha cambiado un password de los diferentes posibles…

Una manera más segura es aplicar el cambio de password a todas las posibles maneras de acceder al usuario root.

UPDATE mysql.user SET Password = PASSWORD("admin") WHERE user = 'root';
FLUSH PRIVILEGES;
SELECT host, user, password FROM mysql.user;


Al usar esta sentencia se cambian todos los passwords del usuario root.

Para evitar el acceso de manera anónima debemos eliminar el perfil.

DROP USER »@’localhost’;

Sin embargo, esta manera podría dejar algún perfil sin borrar si se hubiese creado anteriormente.

Otra manera de eliminar el perfil de anónimo es:

DELETE FROM mysql.user WHERE user = »;
FLUSH PRIVILEGES;

Desinstalando

Para desinstalar detenemos el servicio.

NET STOP MySQL5.5.28

Después de detenido, aplicamos la sentencia en la consola de comandos de Windows que desinstalará el servicio.

mysqld.exe –remove MySQL5.5.28

Integrando Conector Tomcat

En la entrada anterior se detalló la instalación de Tomcat manualmente.
Para poder hacer uso de MySQL con Tomcat es necesario incluir el paquete que lo permite, este paquete se llama Connector/J. Descargué el llamado mysql-connector-java-5.1.22.zip y extraje el archivo llamado mysql-connector-java-5.1.22-bin.jar pegándolo en la carpeta \lib del directorio de instalación de Tomcat, es decir en:

C:\ServerWeb\Tomcat_7.0.27\lib\

Publicado en MySQL, Server, Servidores Web | Etiquetado , , , , , , , | 2 comentarios

Instalando manualmente Tomcat, PHP y Httpd Lounge


Objetivo

Ya he tratado este tema anteriormente usando los instaladores basados en asistentes; ahora vamos a instalar estas mismas herramientas de manera manual.
Como el PHP para el Apache httpd no está produciendo nuevas versiones, ha surgido la alternativa de Httpd Lounge que es compatible, además de poder trabajar con Tomcat.

Las herramientas que vamos a utilizar son:

La instalación la realicé en una máquina con sistema operativo Windows 7 de 32 bits.
Al igual que la entrada anterior se va a realizar la instalación en:

C:\ServerWeb\

Httpd Lounge

Para instalar Httpd Lounge previamente debemos instalar las librerías adecuadas Microsoft Visual C++ 2010 SP1 Redistributable Package que en mi caso es x86.

Yo descargué la versión de Httpd 2.4.2 (httpd-2.4.2-win32.zip) y esta carpeta la descomprimí en:

C:\ServerWeb\Httpd_2.4.2\

como puede verse sin espacios.

Arrancamos la consola CMD en modo administrador como lo indica la siguiente imagen…

Nos vamos a la ruta

C:\ServerWeb\Httpd_2.4.2\conf\

En esta carpeta buscamos el archivo llamado httpd.conf y procedemos a editarlo según nuestros requerimientos.

Editamos el parámetro ServerRoot actualizándolo a la ruta real de instalación.

ServerRoot "c:/ServerWeb/Httpd_2.4.2"

Editamos el parámetro ServerAdmin con la dirección de correo electrónico del administrador del servidor.

ServerAdmin joseluisbz@gmail.com

Cambiamos el parámetro ServerName con el nombre del servidor y el puerto a usar.

ServerName ServerWeb:80

Editamos los parámetros DocumentRoot y Directory.

DocumentRoot "C:/ServerWeb/Httpd_2.4.2/htdocs"
<Directory "C:/ServerWeb/Httpd_2.4.2/htdocs/">

Ahora procederemos con la instalación del servidor como un servicio de Windows, para ellos nos ubicamos en la carpeta donde se encuentran los ejecutables.

C:\ServerWeb\Httpd_2.4.2\bin\

Procedemos a iniciar la instalación, modificando el nombre del servicio e indicando la ubicación del archivo del cual debe tomar la configuración.

httpd.exe -k install -n "Httpd2.4.2" -f "c:\ServerWeb\Httpd_2.4.2\conf\httpd.conf"

no es necesario incluir la extensión «.exe»
Vemos que no presentó errores, ahora vamos a iniciar el servicio.

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

Podemos verificar que el servidor está en funcionamiento:

Desinstalando
Si por algún motivo deseamos desinstalar el servidor Httpd, procedemos a detenerlo:

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


y luego damos la instrucción para desinstalarlo:

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

PHP

Para que PHP trabaje con Httpd Lounge debe bajarse la versión VC9 x86 Thread Safe, debemos tener cuidado de no confundir con la versión VC9 x86 Non Thread Safe; para este proceso descargué la versión de PHP 5.4.0 (php-5.4.0-Win32-VC9-x86.zip) y esta carpeta la descomprimí en:

C:\ServerWeb\Php_5.4.0\

como puede verse sin espacios.

Accedemos a las variables del sistema ejecutando sysdm.cpl:

Al abrirse propiedades del sistema seleccionamos opciones avanzadas


Vamos a variables de entorno: En variables de entorno, en la parte inferior en la caja Variables del sistema, seleccionando la variable Path presionamos el botón Editar:
Editamos la variable path y agregamos al final la nueva ruta en donde se encuentra la carpeta de PHP: Podemos ver que la carpeta de PHP trae unos archivos de configuración preestablecidos, copiamos uno de ellos para editar y preservar los originales:

copy php.ini-production php.ini


Editamos el nuevo archivo copiado php.ini modificando el parámetro extension_dir

extension_dir = "C:\ServerWeb\Php_5.4.0\ext"

Para habilitar el rastreo de errores cambiamos el valor de la variable error_log

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

Dependiendo de como querramos usar las etiquetas de PHP debemos habilitar o no la opción short_open_tag

short_open_tag = On

Descargamos la librería adecuada para nuestra versión de PHP y Httpd php5apache2_4.dll-php-5.4-win32.zip y la extraemos en el directorio raiz de PHP.
Editamos nuevamente el archivo de configuración httpd.conf de Httpd agregando las líneas que permiten arrancarlo con PHP.

#BEGIN PHP INSTALLER EDITS – REMOVE ONLY ON UNINSTALL
PHPIniDir "C:/ServerWeb/Php_5.4.0/"
LoadModule php5_module "C:/ServerWeb/Php_5.4.0/php5apache2_4.dll"
AddType application/x-httpd-php .php
#END PHP INSTALLER EDITS – REMOVE ONLY ON UNINSTALL

Ahora reiniciamos Httpd para que se pueda usar PHP.

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


Para probar que PHP está funcionando correctamente creamos dentro de la carpeta htdocs de Httpd un archivo llamado index.php.

<?php phpinfo(); ?>

Se puede probar que PHP está en funcionamiento:

Tomcat

Yo descargué la versión de Tomcat 7.0.27 (apache-tomcat-7.0.27-windows-x86.zip) y esta carpeta la descomprimí en:

C:\ServerWeb\Tomcat_7.0.27\

como puede verse sin espacios.

Tal como se hizo para llegar a Variables del sistema en Variables de entorno, se realizará la adición de una nueva variable llamada JAVA_HOME presionamos el botón Nueva.

A esta variable le asignamos la dirección de la carpeta de instalación del JDK: Una vez hayamos agregado la nueva variable, presionamos el botón aceptar.

Ahora realizaremos unos pequeños cambios opcionales algunos en algunos archivos ubicados en el subdirectorio llamado bin dentro de la carpeta de Tomcat.

Con el fin de que Tomcat arranque de manera silenciosa (sin ventana de consola emergente), cambiamos en el archivo llamado setclasspath.bat la línea set _RUNJAVA

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

Para eliminar los espacios en el nombre del servicio (podrá generar conflictos), editamos el archivo service.bat, también editamos el nombre a mostrar del mismo.

set SERVICE_NAME=Tomcat7.0.27
set PR_DISPLAYNAME=Tomcat7.0.27


También se puede modificar la descripción relacionada con el servicio Tomcat:

set PR_DESCRIPTION=Apache Tomcat 7.0.27 Server

Para que el servicio inicie cuando Windows lo hace, modificamos la línea:

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


Una vez almacenados los cambios procedemos a realizar el proceso de instalación:

service.bat install

no es necesario incluir la extensión «.bat»
Podemos ver que el servicio efectivamente quedó instalado:
Una manera de arrancarlo por consola CMD es con:

startup.bat

De igual manera se hace necesario el permiso aprobatorio de ejecución:

Ya Tomcat está instalado, ahora vamos a realizar unos cambios que le permita Httpd entender o manejar un archivo con extensión .jsp.

Se debe descargar el connector JK, para Windows 32 se tiene que descargar tomcat-connectors-1.2.37-windows-i386-httpd-2.4.x.zip, de allí se extrae el archivo llamado mod_jk.so y se copia dentro de la carpeta modules de la carpeta de instalación de Httpd.

Dentro de la carpeta conf de la carpeta de instalación de Tomcat creamos una carpeta llamada jk y otra carpeta llamada auto.
Dentro de la carpeta jk creamos un archivo llamado workers.properties cuyo contenido será:

# BEGIN workers.properties
# Definition for Ajp13 worker
worker.list=ajp13
worker.ajp13.port=8009
worker.ajp13.host=localhost
worker.ajp13.type=ajp13
# END workers.properties


Dentro de la carpeta auto creamos un archivo llamado mod_jk.conf con el contenido:

<IfModule !mod_jk.c>
  LoadModule jk_module "C:/ServerWeb/Httpd_2.4.2/modules/mod_jk.so"
</IfModule>
JkWorkersFile "C:/ServerWeb/Tomcat_7.0.27/conf/jk/workers.properties"
JkLogFile "C:/ServerWeb/Tomcat_7.0.27/logs/mod_jk.log"
JkLogLevel emerg
<VirtualHost *:80>
  ServerName localhost
  JkMount /*.jsp ajp13
</VirtualHost>

Tomcat16_mod_jk_AllRemoteIP.conf
De esta manera algún script .jsp podrá ser ejecutado inclusive remotamente, evitándose el inconveniente de mostrar el contenido de dicho script en vez de ejecutarse, como sucede algunas veces aún en el mismo servidor donde se ha instalado Tomcat cuando se accede através de su dirección IP.

Ahora estos cambios se los notificamos a Httpd agregando una línea al final del archivo httpd.conf:

Include "C:/ServerWeb/Tomcat_7.0.27/conf/auto/mod_jk.conf"

Ahora vamos a cambiar predefinida de Tomcat para la publicación .jsp para que sea la misma de Httpd:

<Host name="localhost" appBase="C:/ServerWeb/Httpd_2.4.2"
      unpackWARs="true" autoDeploy="true"
      xmlValidation="false" xmlNamespaceAware="false">
<Context path="" docBase="C:/ServerWeb/Httpd_2.4.2/htdocs"
      reloadable="true" />

Ahora reiniciamos Httpd para que se pueda usar con Tomcat.

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


y ahora lo arrancamos nuevamente

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


Si no hubo problemas en la elección del módulo mod_jk.so no deberían mostrar mensajes de error.

Para probar que Tomcat está funcionando correctamente creamos dentro de la carpeta htdocs de Httpd un archivo llamado index.jsp.

<html>
<body>
<% out.println("Hola Mundo"); %>
</body>
</html>


Se puede probar que Tomcat está en funcionamiento:

Deteniendo
Para detener Tomcat, procedemos con la instrucción:

shutdown.bat

Desinstalando
Si lol que queremos es desinstalar Tomcat lo hacemos con la instrucción:

service.bat uninstall

Por último podemos hacer unos cambios que permita que se pueda cargar de manera prioritaria los archivos index respectivos, estos cambios se realizan en el archivo httpd.conf a la variable DirectoryIndex

DirectoryIndex index.jsp index.php index.html index.htm


Lo anterior quiere decir que primero intente cargar el archivo «index.jsp», si no lo encuentra intentará con «index.php» y así en adelante.

Publicado en Apache, Httpd, JSP, PHP, Server, Servidores Web | Etiquetado , , , , , , , , | 3 comentarios

Subiendo Imágenes (PNG y JPG) y Archivos a MySQL con PHP y JSP y mostrarlos en RTF usando clases


Este tutorial explica usando clases como subir fotos o imágenes tipo PNG o JPG a una base de datos de MySQL, desplegarlos en un arvhivo de tipo RTF, bien sea directamente desde el sistema de archivos del Sistema Operativo o desde una base de datos de MySQL. Además establece dinámicamente la disposición de archivos para lectura de las imágenes que se van a subir y la escritura de archivos RTF generados.
Como hemos venido trabajando con PHP y JSP esta entrada no será la excepción.

Primero que todo comentaré unos cambios con respecto a la publicación anterior de este mismo tema.
Incluí un archivo llamado Personal.html, mejoré la presentación del formulario usando css en un archivo llamado Personal.css.

Código CSS (Personal.css)
Este archivo de tipo Cascading Style Sheets detalla los elementos que se utilizan en los scripts JSP y PHP en lo referente al código HTML y también en el archivo llamado Personal.html.
No se explicará el código css pues no es la intención de esta publicación.

Table {
  border-width:2px;
  border-color:rgb(200,0,0);
  border-style:groove;
  padding:3px;
  margin:3px;
  width:690px;
}

FieldSet {
  border-color:rgb(0,0,0);
  border-style:ridge;
  border-width:2px;
  padding:3px;
  width:630px;
}

Th {
  height:32px;
  background-color:rgb(127,127,127);
  color:rgb(255,255,255);
  border-style:solid;
  border-width:2px;
  border-color:rgb(0,200,0);
  padding:3px;
  margin:3px;
  font-weight:bold;
}

Td {
  height:30px;
  text-align:left;
  vertical-align:bottom;
  border-width:2px;
  border-color:rgb(0,0,200);
  border-style:ridge;
  padding:3px;
  margin:3px;
}

Label {
  display: block;
  width: 180px;
  float: left;
  clear: both;
  text-shadow: rgb(196,196,196) 2px 2px;
}
Label:hover {
  text-decoration:blink;
  font-style:oblique;
  font-weight:bold;
}

Input.Texto {
  border-width:2px;
  border-color:rgb(127,127,127);
  border-style:inset;
}
Input.Texto:hover {
  background-color:rgb(240,240,240);
  border-style:outset;
}

Input.Boton {
  background-color:rgb(255,255,255);
  color:rgb(0,0,0);
  cursor:pointer;
  width:130px;
  padding:2px;
  border-width:5px;
  border-color:rgb(127,127,127);
  border-style:double;
  margin:1px;
  font-size: 8pt; 
  font-family: Courier;
}
Input.Boton:hover {
  background-color:rgb(0,0,0);
  color:rgb(255,255,255);
  font-weight:bold;
}

Input.File {
  border-width:2px;
  border-color:rgb(127,127,127);
  border-style:inset;
  cursor:pointer;
}
Input.File:hover {
  background-color:rgb(240,240,240);
  border-style:outset;
}

DIV.map {
  padding-top: 2px;
  padding-bottom: 2px;
  margin-top: 2px;
  margin-right: 0px;
  margin-bottom: 2px;
  margin-left: 2px;
  clear: both;
  text-shadow: rgb(196,196,196) 2px 2px;
}

#p1 {
  display: block; 
  white-space: nowrap; 
  text-indent: 0
}
#p1 A {
  text-decoration:underline;
}
#p1, #p1 A {
  color:rgb(32,32,255);
  font-size:16px;
  font-family: "Lucida Console", Monospace;
}

#p1 {
  text-align: left;
  margin: 2px 2px 2px 2px;
}

P.Mensaje {
  color:rgb(32,32,32);
  font-size:15px;
  font-family: "Courier New", Monospace;
  text-shadow: rgb(196,196,196) 2px 2px;
}

Código HTML (Personal.html)
Este archivo refleja en html «puro» nuestro formulario, también incluye «Cascading Style Sheets» según el archivo Personal.css anteriormente detallado. No explicaré el código html porque no es la intención de esta publicación.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>Registros - Personal.html</title>
    <!--
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    -->
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <link rel="stylesheet" href="Personal.css" type="text/css" />
    <link rel="shortcut icon" href="BZ.ico" type="image/x-icon" />
  </head>
  <body>
    <form method="post" name="FormOperar" enctype="multipart/form-data">
      <TABLE>
        <TR>
          <TH colspan="2">Datos Registros</TH>
        <TR>
          <TD colspan="2"><label for="Nombre">Nombres y Apellidos:</label><input type="text" id ="Nombre" name="tNombre" value="" size="30" class="Texto" />
        <TR>
          <TD><label for="Salario">Valor Salario:</label><input type="text" id="Salario" name="tSalario" value="" size="11" class="Texto" />
          <TD><label for="Ingreso">Fecha Ingreso:</label><input type="text" id="Ingreso" name="tIngreso" value="" size="10" class="Texto" />
        <TR>
          <TD colspan="2"><label for="Foto">Foto Reciente:</label><input type="file" id="Foto" name="fFoto" size="60" class="File" />
        <TR>
          <TD colspan="2"><label for="Resumen">Resumen:</label><input type="file" id="Resumen" name="fResumen" size="60" class="File" />
      </TABLE>
      <TABLE>
        <TR>
          <TH>Personal.jsp</TH>
          <TD><input type="submit" name="bCargar" value="Cargar Datos" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
          <TD><input type="submit" name="bListar" value="Listar Datos" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
          <TD><input type="submit" name="bBorrar" value="Borrar Datos" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
          <TD><input type="submit" name="bReset" value="Inicio JSP" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
        </TR>
        <TR>
          <TH>Personal.php</TH>
          <TD><input type="submit" name="bCargar" value="Cargar Datos" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
          <TD><input type="submit" name="bListar" value="Listar Datos" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
          <TD><input type="submit" name="bBorrar" value="Borrar Datos" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
          <TD><input type="submit" name="bReset" value="Inicio PHP" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
      </TABLE>
    </form>
  </body>
</html>

Script JSP (Personal.jsp)
Tal como hicimos en la entrada anterior usamos las mismo código para la importación de librerías:

<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ include file="RTF.jsp" %>

Ahora vamos a describir unas funciones en JSP que nos ayudan a entender mejor nuestro código:

<%!
  javax.servlet.jsp.JspWriter Out;
  String GetNameScript(String Script){
    return Script.substring(Script.lastIndexOf("/")+1,Script.length());
  }
  String GetPathScript(String Script){
    return Script.substring(0,Script.lastIndexOf("/")+1);
  }
  String GetStringProtocol(String Protocol){
    if (Protocol.equals("HTTP/1.1")) return "http://";
    return Protocol;
  }
  String GetStringPort(int Port){
    if (Port == 80) return "";
    return ":"+String.valueOf(Port);
  }
  void PrintMsg(String Msg){
    try {
      Out.print("<P class=\"Mensaje\">"+Msg+"</P>");
    }
    catch (Exception e) {}
  }
  void PrintErr(String Err){
    try {
      Out.print("<P style=\"color:rgb(255,0,0)\">"+Err+"</P>");
    }
    catch (Exception e) {}
  }
  void PrintLnk(String Lnk){
    try {
      Out.println("<div class=\"map\">");
      Out.println("<p id=\"p1\"><a href=\""+Lnk+"\">"+Lnk+"</a>");
      Out.println("</div>");
    }
    catch (Exception e) {}
  }
%>

Out es una variable que es útil solo para el script JSP no para el script PHP, no confundir con out. Out Nos sirve para imprimir desde un método externo al script JSP en uso.
La función GetNameScript nos permite obtener solo el nombre de nuestro Script (el que se está ejecutando).
La función GetPathScript permite obtener la ruta de la ubicación de nuestro Script, sin incluir el nombre del servidor, ni el nombre del Script.
GetStringProtocol es una función que permite saber el protocolo, en este caso http, que usamos al desplegar nuestro script.
GetStringPort Nos retorna como una cadena el puerto usado, en caso de que no sea 80, no sería necesario cambiar nuestro script.
PrintMsg Imprime la cadena de texto según el formato asignado a los mensajes, según CSS.
PrintErr Imprime la cadena de texto según el formato para los mensajes de error.
PrintLnk Imprime un vínculo, con formato de presentación definido en CSS.

Script PHP (Personal.php)
De igual manera se hizo para el respectivo script en PHP, recordemos además que es solo necesario importar el archivo RTF.php.

<?php require("RTF.php"); ?>

Y las mismas funciones descritas anteriormente.

<?php
  function GetNameScript($Script){
    return substr($Script,strripos($Script,"/")+1,strlen($Script));
  }
  function GetPathScript($Script){
    return substr($Script,0,strripos($Script,"/")+1);
  }
  function GetStringProtocol($Protocol){
    if ($Protocol=="HTTP/1.1") return "http://";
    return $Protocol;
  }
  function GetStringPort($Port){
    if ($Port == 80) return "";
    return ":".$Port;
  }
  function PrintMsg($Msg){
    print("<P class=\"Mensaje\">".$Msg."</P>");
  }
  function PrintErr($Err){
    print("<P style=\"color:rgb(255,0,0)\">".$Err."</P>");
  }
  function PrintLnk($Lnk){
    print("<div class=\"map\">");
    print("<p id=\"p1\"><a href=\"".$Lnk."\">".$Lnk."</a>");
    print("</div>");
  }
?>

Con estas definiciones de funciones se harán unos pequeños cambios en lo que respecta al código HTML de la entrada anterior referente a este tema que hemos incluido en dos archivos para separar el código HTML de los respectivos scripts JSP y PHP. Para el script Personal.php el contenido referente al Tag Head HTML lo hemos incluido en un archivo llamado TagHead.php cuyo contenido es:

  <head>
    <title>Registros - <?php print(GetNameScript($_SERVER['SCRIPT_NAME'])); ?></title>
    <!--
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    -->
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <link rel="stylesheet" href="Personal.css" type="text/css" />
    <link rel="shortcut icon" href="BZ.ico" type="image/x-icon" />
  </head>

Script JSP
Para el script Personal.jsp el contenido referente al Tag Head HTML se incluyó en el script TagHead.jsp cuyo contenido es:

  <head>
    <title>Registros - <%=GetNameScript(request.getServletPath())%></title>
    <!--
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    -->
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <link rel="stylesheet" href="Personal.css" type="text/css" />
    <link rel="shortcut icon" href="BZ.ico" type="image/x-icon" />
  </head>

También el código HTML referente al formulario se incluyó en un archivo llamado TagForm.jsp, podemos ver que se puede intercambiar de script en ejecución, para lo cual se ha incluido los botones que lo permiten, el código es el siguiente:

    <form method="post" name="FormOperar" enctype="multipart/form-data">
      <TABLE>
        <TR>
          <TH colspan="2">Datos Registros</TH>
        <TR>
          <TD colspan="2"><label for="Nombre">Nombres y Apellidos:</label><input type="text" id ="Nombre" name="tNombre" value="" size="30" class="Texto" />
        <TR>
          <TD><label for="Salario">Valor Salario:</label><input type="text" id="Salario" name="tSalario" value="" size="11" class="Texto" />
          <TD><label for="Ingreso">Fecha Ingreso:</label><input type="text" id="Ingreso" name="tIngreso" value="" size="10" class="Texto" />
        <TR>
          <TD colspan="2"><label for="Foto">Foto Reciente:</label><input type="file" id="Foto" name="fFoto" size="60" class="File" />
        <TR>
          <TD colspan="2"><label for="Resumen">Resumen:</label><input type="file" id="Resumen" name="fResumen" size="60" class="File" />
      </TABLE>
      <TABLE>
        <TR>
          <TH>Personal.jsp</TH>
          <TD><input type="submit" name="bCargar" value="Cargar Datos" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
          <TD><input type="submit" name="bListar" value="Listar Datos" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
          <TD><input type="submit" name="bBorrar" value="Borrar Datos" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
          <TD><input type="submit" name="bReset" value="Inicio HTML" onClick="document.FormOperar.action='Personal.html'" class="Boton" />
        </TR>
        <TR>
          <TH>Personal.php</TH>
          <TD><input type="submit" name="bCargar" value="Cargar Datos" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
          <TD><input type="submit" name="bListar" value="Listar Datos" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
          <TD><input type="submit" name="bBorrar" value="Borrar Datos" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
          <TD><input type="submit" name="bReset" value="Inicio PHP" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
      </TABLE>
    </form>

Script PHP
El código HTML referente al formulario se incluyó en un archivo llamado TagForm.php con código:

    <form method="post" name="FormOperar" enctype="multipart/form-data">
      <TABLE>
        <TR>
          <TH colspan="2">Datos Registros</TH>
        <TR>
          <TD colspan="2"><label for="Nombre">Nombres y Apellidos:</label><input type="text" id ="Nombre" name="tNombre" value="" size="30" class="Texto" />
        <TR>
          <TD><label for="Salario">Valor Salario:</label><input type="text" id="Salario" name="tSalario" value="" size="11" class="Texto" />
          <TD><label for="Ingreso">Fecha Ingreso:</label><input type="text" id="Ingreso" name="tIngreso" value="" size="10" class="Texto" />
        <TR>
          <TD colspan="2"><label for="Foto">Foto Reciente:</label><input type="file" id="Foto" name="fFoto" size="60" class="File" />
        <TR>
          <TD colspan="2"><label for="Resumen">Resumen:</label><input type="file" id="Resumen" name="fResumen" size="60" class="File" />
      </TABLE>
      <TABLE>
        <TR>
          <TH>Personal.jsp</TH>
          <TD><input type="submit" name="bCargar" value="Cargar Datos" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
          <TD><input type="submit" name="bListar" value="Listar Datos" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
          <TD><input type="submit" name="bBorrar" value="Borrar Datos" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
          <TD><input type="submit" name="bReset" value="Inicio JSP" onClick="document.FormOperar.action='Personal.jsp'" class="Boton" />
        </TR>
        <TR>
          <TH>Personal.php</TH>
          <TD><input type="submit" name="bCargar" value="Cargar Datos" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
          <TD><input type="submit" name="bListar" value="Listar Datos" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
          <TD><input type="submit" name="bBorrar" value="Borrar Datos" onClick="document.FormOperar.action='Personal.php'" class="Boton" />
          <TD><input type="submit" name="bReset" value="Inicio HTML" onClick="document.FormOperar.action='Personal.html'" class="Boton" />
      </TABLE>
    </form>

Los archivos TagHead.php y TagForm.jsp se incluyeron en un solo archivo llamado HTMLHead.php quedando así:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
  <?php include("TagHead.php"); ?>
  <body>
    <?php include("TagForm.php"); ?>

Este archivo se usa en conjunto con el archivo HTMLFoot.php cuyo contenido es:

  </body>
</html>

Script JSP
De igual manera se creó un archivo llamado HTMLHead.jsp que incluye los archivos TagHead.jsp y TagForm.jsp y su código es:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html>
  <%@ include file="TagHead.jsp" %>
  <body>
    <%@ include file="TagForm.jsp" %>

Similarmente como sucede con el código php este archivo se usa en conjunto con HTMLFoot.jsp y su código es:

  </body>
</html>

Script JSP (Personal.jsp)
Como podemos ver el código HTML se ha reducido a una línea en comparación a la manera anterior.
Ahora explicaré las variables encargadas de determinar la ruta de lectura de archivos y escritura de los mismos, adicionalmente construir su url para que se puedan descargar.

<%@ include file="HTMLHead.jsp" %>
    <%
      Out = out;

      String WebPath = GetPathScript(request.getServletPath());
      String WebRoot = GetStringProtocol(request.getProtocol())+request.getServerName()+GetStringPort(request.getServerPort())+WebPath;
      String FS = System.getProperty("file.separator");//Separador de Archivo o de Directorio
      //Buscar ruta del Script
      String ScriptRoot = application.getRealPath("")+WebPath;
      ScriptRoot = ScriptRoot.replace("\\",FS);//Reemplaza \ por FS
      ScriptRoot = ScriptRoot.replace("/",FS);//Reemplaza / por FS

Out Inicializamos la variable para poder usar el método de impresión (válido solo para JSP).
WebPath Almacena la ruta del script, sin incluir el nombre mismo del Script.
WebRoot Variable que crea una URL base teniendo en cuenta protocolo, nombre del servidor, puerto y la ruta donde se almacena el Script.
FS Almacena el separador de Archivo o de Directorio.
ScriptRoot Almacena la ruta de nuestro Script según el sistema de archivo del sistema operativo, éste se actualiza según la variable FS, para garantizar que nuestro script sea compatible con nuestro sistema operativo (Linux o Windows).

Script PHP (Personal.php)

<?php include("HTMLHead.php"); ?>
    <?php

      $WebPath = GetPathScript($_SERVER['SCRIPT_NAME']);
      $WebRoot = GetStringProtocol($_SERVER['SERVER_PROTOCOL']).$_SERVER['SERVER_NAME'].GetStringPort($_SERVER['SERVER_PORT']).$WebPath;
      $FS = DIRECTORY_SEPARATOR;//Separador de Archivo o de Directorio
      //Buscar ruta del Script
      $ScriptRoot = getenv("DOCUMENT_ROOT").$WebPath;
      $ScriptRoot = str_replace("/",$FS,$ScriptRoot);//Reemplaza / por $FS
      $ScriptRoot = str_replace("\\",$FS,$ScriptRoot);//Reemplaza \ por $FS

La conexión a MySQL se hace de la misma manera en que se explicó en la entrada anterior. Solo que para imprimir mensajes de resultado, mensajes de error se usan los métodos respectivos anteriormente explicados.

      //Conexión MySQL
      $host = "localhost";
      $User = "elusuario";
      $Pass = "laclave";
      $DB = "Empresa";
      $Enlace = new mysqli($host,$User,$Pass,$DB);
      if ($Enlace->connect_error) {
        PrintErr(sprintf("Connect Error: (%d) %s",$Enlace->connect_errno,$Enlace->connect_error));
        exit();
      }

      //Inserción
      if (isset($_POST['bCargar'])){
        $Enunciado = $Enlace->prepare("INSERT INTO Registros (Nombre,Salario,Ingreso,Foto,Resumen) VALUES(?,?,?,?,?)");
        $sNombre = utf8_encode ($_POST['tNombre']);
        $sSalario = $_POST['tSalario'];
        $sIngreso = $_POST['tIngreso'];
        $BytesFoto = NULL;
        $BytesResumen = NULL;

        $Enunciado->bind_param('sisbb',$sNombre,$sSalario,$sIngreso,$BytesFoto,$BytesResumen);
        if (is_uploaded_file($_FILES['fFoto']['tmp_name'])){
          $fiFoto = fopen($_FILES['fFoto']['tmp_name'], "rb");
          if ($fiFoto!=false){
            while (!feof($fiFoto)){
              $Enunciado->send_long_data(3, fread($fiFoto, 8192));
            }
            fclose($fiFoto);
          }
        } else {
          PrintErr(sprintf("Error Upload File: (%d) %s",$HTTP_POST_FILES['fFoto']['error'],$Enlace->error));
          exit();
        }

        if (is_uploaded_file($_FILES['fResumen']['tmp_name'])){
          $fiResumen = fopen($_FILES['fResumen']['tmp_name'], "rb");
          if ($fiResumen!=false){
            while (!feof($fiResumen)){
              $Enunciado->send_long_data(4, utf8_encode (fread($fiResumen, 8192)));
            }
            fclose($fiResumen);
          }
        } else {
          PrintErr(sprintf("Error Upload File: (%d) %s",$HTTP_POST_FILES['fResumen']['error'],$Enlace->error));
          exit();
        }

        if ($Enunciado->execute()) {
          PrintMsg("Inserción Exitosa!<br/>");
        }else {
          PrintErr(sprintf("Error: (%d) %s",$Enlace->errno,$Enlace->error));
          exit();
        }
        $Enunciado->close();
        $Enlace->close();
      }

Script JSP (Personal.jsp)
De igual manera no hay cambios para el código JSP, solo los ya indicados en cuanto a los mensajes.

      if(ServletFileUpload.isMultipartContent(request)) {
        //Cargar Parámetros del Script
        ServletFileUpload SFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        Iterator iter = null;
        Hashtable Parameters = new Hashtable();
        try{
          iter = SFileUpload.parseRequest(request).iterator();
          FileItem FItem = null;
          while(iter.hasNext()){
            FItem = (FileItem)iter.next();
            if (FItem.isFormField() ){
              Parameters.put(FItem.getFieldName(), FItem.getString());
            } else {
              if (FItem.getFieldName().equals("fFoto")){
                Parameters.put(FItem.getFieldName(), FItem.getInputStream());
              }
              if (FItem.getFieldName().equals("fResumen")){
                Parameters.put(FItem.getFieldName(), FItem.getString("ISO-8859-1"));
              }
            }
          }
        }
        catch(FileUploadException e){ PrintErr(e.toString()); }

        //Conexión MySQL
        String host = "localhost";
        String User = "elusuario";
        String Pass = "laclave";
        String DB = "Empresa";
        try { Class.forName("com.mysql.jdbc.Driver"); }
        catch (ClassNotFoundException e) { PrintErr(e.toString()); }
        Connection Conexion = null;
        Statement Enunciado = null;
        ResultSet Resultado = null;
        PreparedStatement PE = null;
        try{ Conexion = DriverManager.getConnection("jdbc:mysql://"+host+"/"+DB,User,Pass); }
        catch (SQLException e) { PrintErr(e.toString()); }

        //Inserción
        if((String)Parameters.get("bCargar")!=null){
          try{
            PE = Conexion.prepareStatement("INSERT INTO Registros (Nombre,Salario,Ingreso,Foto,Resumen) VALUES(?,?,?,?,?)");
            String sNombre = (String)Parameters.get("tNombre");
            String sSalario = (String)Parameters.get("tSalario");
            String sIngreso = (String)Parameters.get("tIngreso");
            InputStream isFoto = (InputStream)Parameters.get("fFoto");
            String sResumen = (String)Parameters.get("fResumen");
            PE.setString(1,sNombre);
            PE.setInt(2,Integer.parseInt(sSalario));
            PE.setString(3,sIngreso);
            PE.setBinaryStream(4,isFoto);
            PE.setString(5,sResumen);
            PE.executeUpdate();
            PrintMsg("Inserción Exitosa!<br/>");
          }
          catch (SQLException e) { PrintErr(e.toString()); }
          catch (Exception e) { PrintErr(e.toString()); }
          finally {
            PE.close();
            Conexion.close();
          }
        }

Script PHP (Personal.php)

      //Extracción
      if (isset($_POST['bListar'])){
        $FileName = "PHP.Personal.RTF";
        $FullFileName = $ScriptRoot.$FileName;
        $WebFileName = $WebRoot.$FileName;
        $ImageJPG = $ScriptRoot.$FS."joseluisbz.jpg";
        $ImagePNG = $ScriptRoot.$FS."Empresa.png";
        $fw = fopen($FullFileName, "wb");
        if($fw){
          $FileRTF = new RTFFile();
          $iFormato = NULL;
          $iAlto = NULL;
          $iAncho = NULL;
          $ImageRTFJPG = new RTFImage($ImageJPG,$iFormato,$iAlto,$iAncho);
          if (strcmp($ImageRTFJPG->GetHexImage(),"Error")==0){
            PrintErr("Error: el Archivo ".$ImageJPG." no es PNG o JPG");
            exit();
          }
          $InfImagenJPG = $ImageRTFJPG->GetImage($ImageRTFJPG->GetHexImage(),$iFormato,$iAlto,$iAncho,100,100,$iAlto*10,$iAncho*10,0,0,0,0);

          $ImageRTFPNG = new RTFImage($ImagePNG,$iFormato,$iAlto,$iAncho);
          if (strcmp($ImageRTFPNG->GetHexImage(),"Error")==0){
            PrintErr("Error: el Archivo ".$ImagePNG." no es PNG o JPG");
            exit();
          }
          $InfImagenPNG = $ImageRTFPNG->GetImage($ImageRTFPNG->GetHexImage(),$iFormato,$iAlto,$iAncho,100,100,$iAlto*10,$iAncho*10,0,0,0,0);
          $ImageRTFIMG = NULL;
          $InfImagenIMG = NULL;
          if ($Enunciado = $Enlace->prepare("SELECT * FROM Registros")) {
            $Enunciado->execute();
            $Enunciado->bind_result($sNombre,$sSalario,$sIngreso,$BytesFoto,$BytesResumen);
            $Enunciado->store_result();
            $NumRegistros = $Enunciado->num_rows;
            $TablaDatos = NULL;
            while ($Enunciado->fetch()) {
              $FileRTF->SetBasicFormatTextFile(1,3,2,5,20);
              $FileRTF->SetOtherFormatTextFile(0,0,1);
              $FileRTF->AddText("Empresa Limitada");
              $FileRTF->InsertParg();
              $TablaDatos = new RTFTable(4,4);//4 Columnas, 4 Filas
              $TablaDatos->SetFormatTable(10,10,1,1,10,2);
              $TablaDatos->SetFormatCellsTable(0,2,10,2);
              $TablaDatos->SetWideColsTable(2000);//Columnas ancho 2000
              $TablaDatos->SetWideColTable(1,3000);//Columna 1 ancho 3000
              $TablaDatos->SetBasicFormatTextTable(1,0,0,0,12);//Formato de Texto Tabla
              $TablaDatos->SetBasicFormatTextCell(0,0,1,0,0,0,12);//Formato Texto Celda 0,0
              $TablaDatos->SetTextCell(0,1,$InfImagenPNG);
              $TablaDatos->SetTextCell(3,1,$InfImagenJPG);
              $TablaDatos->SetMergeHorzCell(1,0,1);//Mezclar Celda 1,0 Inicio = 1
              $TablaDatos->SetMergeHorzCell(2,0,2);//Mezclar Celda 2,0 Continua = 2
              $TablaDatos->SetTextCell(1,0,"Celda 1,0 con Celda 2,0");
              $TablaDatos->SetMergeHorzCell(1,3,1);//Mezclar Celda 1,3 Inicio = 1
              $TablaDatos->SetMergeHorzCell(2,3,2);//Mezclar Celda 2,3 Continua = 2
              $TablaDatos->SetTextCell(1,3,"Celda 1,3 con Celda 2,3");
              $TablaDatos->SetMergeVertCell(0,1,1);//Mezclar Celda 0,1 Inicio = 1
              $TablaDatos->SetMergeVertCell(0,2,2);//Mezclar Celda 0,2 Continua = 2
              $TablaDatos->SetMergeVertCell(3,1,1);//Mezclar Celda 3,1 Inicio = 1
              $TablaDatos->SetMergeVertCell(3,2,2);//Mezclar Celda 3,2 Continua = 2
              $FileRTF->AddElement($TablaDatos->GetTable());
              $FileRTF->InsertLine();
              $FileRTF->InsertLine();
              $FileRTF->SetBasicFormatTextFile(2,4,2,4,12);
              $FileRTF->SetOtherFormatTextFile(0,0,1);
              $FileRTF->AddText("Nombre: ");
              $FileRTF->SetOtherFormatTextFile(0,1,0);
              $FileRTF->AddText(utf8_decode($sNombre));
              $FileRTF->InsertLine();
              $FileRTF->SetOtherFormatTextFile(0,0,1);
              $FileRTF->AddText("Salario: ");
              $FileRTF->SetOtherFormatTextFile(0,1,0);
              $FileRTF->AddText($sSalario);
              $FileRTF->InsertLine();
              $ImageRTFIMG = new RTFImage($BytesFoto,$iFormato,$iAlto,$iAncho);
              $InfImagenIMG = $ImageRTFIMG->GetImage($ImageRTFIMG->GetHexImage(),$iFormato,$iAlto,$iAncho,100,100,$iAlto*10,$iAncho*10,0,0,0,0);
              $FileRTF->AddElement($InfImagenIMG);
              $FileRTF->InsertParg();//Separe Image of Text
              $FileRTF->SetOtherFormatTextFile(0,0,1);
              $FileRTF->AddText("Resumen: ");
              $FileRTF->SetOtherFormatTextFile(0,1,0);
              $FileRTF->AddText(utf8_decode($BytesResumen));
              $NumRegistros--;
              if($NumRegistros>0){
                $FileRTF->InsertPage();//Nueva Página
              }
            }
            $Enunciado->close();
          }
          $FileRTF->CloseFile();
          fwrite($fw,$FileRTF->GetFile());
          fclose($fw);
          PrintLnk($WebFileName);
          PrintMsg("Generación de Archivo RTF Exitoso!<br/>");
        } else {
          PrintErr($FullFileName." (El sistema no puede encontrar la ruta especificada)");
          exit();
        }
      }

Script JSP (Personal.jsp)

        //Extracción
        if((String)Parameters.get("bListar")!=null){
          String FileName = "JSP.Personal.RTF";
          String FullFileName = ScriptRoot+FileName;
          String WebFileName = WebRoot+FileName;
          String ImageJPG = ScriptRoot+FS+"joseluisbz.jpg";
          String ImagePNG = ScriptRoot+FS+"Empresa.png";
          try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(FullFileName));
            RTFFile FileRTF = new RTFFile();
            int[] iFormato = new int[1];
            int[] iAlto = new int[1];
            int[] iAncho = new int[1];
            RTFImage ImageRTFJPG = new RTFImage(ImageJPG,iFormato,iAlto,iAncho);
            if (ImageRTFJPG.GetHexImage().equals("Error")){
              PrintErr("Error: el Archivo "+ImageJPG+" no es PNG o JPG");
              System.exit(0);
            }
            String InfImagenJPG = ImageRTFJPG.GetImage(ImageRTFJPG.GetHexImage(),iFormato[0],iAlto[0],iAncho[0],100,100,iAlto[0]*10,iAncho[0]*10,0,0,0,0);

            RTFImage ImageRTFPNG = new RTFImage(ImagePNG,iFormato,iAlto,iAncho);
            if (ImageRTFPNG.GetHexImage().equals("Error")){
              PrintErr("Error: el Archivo "+ImagePNG+" no es PNG o JPG");
              System.exit(0);
            }
            String InfImagenPNG = ImageRTFPNG.GetImage(ImageRTFPNG.GetHexImage(),iFormato[0],iAlto[0],iAncho[0],100,100,iAlto[0]*10,iAncho[0]*10,0,0,0,0);
            RTFImage ImageRTFIMG;
            String InfImagenIMG;
            PE = Conexion.prepareStatement("SELECT * FROM Registros");
            Resultado = PE.executeQuery();
            Resultado.last();
            int NumRegistros = Resultado.getRow();Resultado.beforeFirst();
            RTFTable TablaDatos;
            while(Resultado.next()){
              FileRTF.SetBasicFormatTextFile(1,3,2,5,20);
              FileRTF.SetOtherFormatTextFile(0,0,1);
              FileRTF.AddText("Empresa Limitada");
              FileRTF.InsertParg();
              TablaDatos = new RTFTable(4,4);//4 Columnas, 4 Filas
              TablaDatos.SetFormatTable(10,10,1,1,10,2);
              TablaDatos.SetFormatCellsTable(0,2,10,2);
              TablaDatos.SetWideColsTable(2000);//Columnas ancho 2000
              TablaDatos.SetWideColTable(1,3000);//Columna 1 ancho 3000
              TablaDatos.SetBasicFormatTextTable(1,0,0,0,12);//Formato de Texto Tabla
              TablaDatos.SetBasicFormatTextCell(0,0,1,0,0,0,12);//Formato Texto Celda 0,0
              TablaDatos.SetTextCell(0,1,InfImagenPNG);
              TablaDatos.SetTextCell(3,1,InfImagenJPG);
              TablaDatos.SetMergeHorzCell(1,0,1);//Mezclar Celda 1,0 Inicio = 1
              TablaDatos.SetMergeHorzCell(2,0,2);//Mezclar Celda 2,0 Continua = 2
              TablaDatos.SetTextCell(1,0,"Celda 1,0 con Celda 2,0");
              TablaDatos.SetMergeHorzCell(1,3,1);//Mezclar Celda 1,3 Inicio = 1
              TablaDatos.SetMergeHorzCell(2,3,2);//Mezclar Celda 2,3 Continua = 2
              TablaDatos.SetTextCell(1,3,"Celda 1,3 con Celda 2,3");
              TablaDatos.SetMergeVertCell(0,1,1);//Mezclar Celda 0,1 Inicio = 1
              TablaDatos.SetMergeVertCell(0,2,2);//Mezclar Celda 0,2 Continua = 2
              TablaDatos.SetMergeVertCell(3,1,1);//Mezclar Celda 3,1 Inicio = 1
              TablaDatos.SetMergeVertCell(3,2,2);//Mezclar Celda 3,2 Continua = 2
              FileRTF.AddElement(TablaDatos.GetTable());
              FileRTF.InsertLine();
              FileRTF.InsertLine();
              FileRTF.SetBasicFormatTextFile(2,4,2,4,12);
              FileRTF.SetOtherFormatTextFile(0,0,1);
              FileRTF.AddText("Nombre: ");
              FileRTF.SetOtherFormatTextFile(0,1,0);
              FileRTF.AddText(Resultado.getString(1));
              FileRTF.InsertLine();
              FileRTF.SetOtherFormatTextFile(0,0,1);
              FileRTF.AddText("Salario: ");
              FileRTF.SetOtherFormatTextFile(0,1,0);
              FileRTF.AddText(String.valueOf(Resultado.getInt(2)));
              FileRTF.InsertLine();
              ImageRTFIMG = new RTFImage(Resultado.getBytes(4),iFormato,iAlto,iAncho);
              InfImagenIMG = ImageRTFIMG.GetImage(ImageRTFIMG.GetHexImage(),iFormato[0],iAlto[0],iAncho[0],100,100,iAlto[0]*10,iAncho[0]*10,0,0,0,0);
              FileRTF.AddElement(InfImagenIMG);
              FileRTF.InsertParg();//Separe Image of Text
              FileRTF.SetOtherFormatTextFile(0,0,1);
              FileRTF.AddText("Resumen: ");
              FileRTF.SetOtherFormatTextFile(0,1,0);
              FileRTF.AddText(Resultado.getString(5));
              NumRegistros--;
              if (NumRegistros>0){
                FileRTF.InsertPage();//Nueva Página
              }
            }
            FileRTF.CloseFile();
            bw.write(FileRTF.GetFile());
            bw.close();
            PrintLnk(WebFileName);
            PrintMsg("Generación de Archivo RTF Exitoso!<br/>");
          }
          catch (Exception e) { PrintErr(e.toString()); }
        }

Script PHP (Personal.php)

      //Eliminación
      if (isset($_POST['bBorrar'])){
        $Consulta = "DELETE FROM Registros";
        $Resultado = $Enlace->query($Consulta);
        if (!$Resultado) {
          PrintErr(sprintf("Error: (%d) %s",$Enlace->errno,$Enlace->error));
          exit();
        }
        PrintMsg("Eliminación Exitosa!<br/>");
      }

Finalizamos el script PHP con:

    ?>
<?php include("HTMLFoot.php"); ?>

Script JSP (Personal.jsp)

        //Eliminación
        if((String)Parameters.get("bBorrar")!=null){
          try {
            Enunciado = Conexion.createStatement();
            Enunciado.executeUpdate("DELETE FROM Registros");
            PrintMsg("Eliminación Exitosa!<br/>");
          }
          catch (SQLException e) { PrintErr(e.toString()); }
        }

Finalizamos el script JSP el siguiente código:

      }
    %>
<%@ include file="HTMLFoot.jsp" %>

La llave de cierre coincide con la llave de apertura de la sentencia if del objeto ServletFileUpload.

Resultados
Veamos algunos resultados:
Previamente se había cargado un registro de prueba con caracteres especiales y al presionar el botón «Listar Datos» en ambos scripts se obtienen los siguientes pantallazos.


Podemos ver el pantallazo del archivo RTF generado por los dos scripts, si se compara de manera binaria el contenido del JSP.Personal.RTF y del archivo PHP.Personal.RTF son exactamente iguales.

Para ver como se muestran los errores se presióno el botón «Cargar Datos» con el formulario vacío:

Por último se presionó el botón «Borrar Datos» y se obtuvieron los siguientes pantallazos.

Para obtener los códigos y probar estos ejemplos dejo los enlaces: Personal.zip

Publicado en JSP, MySQL, PHP, Server | Etiquetado , , , , , , , , | 6 comentarios