Generate Large XLSX USING Spring Framework & Apache POI

Para este ejemplo use la librería Apache POI que permite generar documentos de Office, el problema principal de la solución fue bajar los datos de una consulta a una BD que podia regresar muchos registros, por lo que no podíamos dejar esperando al usuario a que se generara completo el archivo Excel para que pudiera ser descargado.
 La solución fue generar un archivo excel vacío con la cabecera necesaria para enviar el setContentType y el navegador queda esperando a que el ServletOutputStream termine de enviar datos Bytes x Bytes.


mvc-dispatcher-servlet.xml


    
        
        
        
    
    
    
    
    
    
    
    

    
    
    

    
    
        
    


    
    
    
    
        
        
        
        
        
        
        
        
            
                unchecked
            
        
    

    
    
        
        
            
                classpath:message
            
        
        
    

    
        
    

    
        
    
    

    
  
    
        
            
            
                
                
                
                
                
     
            
            
        
    
     



Encabezado de archivos XLSX, como se puede ver en la imagen todo archivo XLS tiene como Header los Byte: {0x50, 0x4b, 0x03, 0x04, 0x14, 0x00}; 



Metodo que Baja el archivo Bytes x Bytes
 
 private void doDownload(String accion, String fecha, String fechainicio, String fechafinal, String compania, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ftemporal = fecha;
        //XLS
        SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk
        String mensaje = accion.equals("B") == true ? "Bloqueo" : "Desbloqueo";
        String[] ftempo = ftemporal.split("/"); //{DD,MM,YYYY}

        Sheet sheet = wb.createSheet("ReporteMora_" + mensaje + "_" + ftempo[2] + ftempo[1] + ftempo[0]);
        OutputStream out = response.getOutputStream();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=\"" + sheet.getSheetName() + ".xlsx\"");
        final byte headerBytes[] = new byte[]{0x50, 0x4b, 0x03, 0x04, 0x14, 0x00};
        out.write(headerBytes);
        response.flushBuffer();
        //encabezado
        //data
        Row encabezado = sheet.createRow(0);
        sheet.autoSizeColumn(0);
        Cell cell = encabezado.createCell(0);
        cell.setCellValue((String) "IMEI");
        cell = encabezado.createCell(1);
        cell.setCellValue((String) "MARCA");
        cell = encabezado.createCell(2);
        cell.setCellValue((String) "MODELO");
        cell = encabezado.createCell(3);
        cell.setCellValue((String) "FECHA_INGRESO");
        cell = encabezado.createCell(4);
        cell.setCellValue((String) "ACCION");
        cell = encabezado.createCell(5);
        cell.setCellValue((String) "TIPO_TECNOLOGIA");
        cell = encabezado.createCell(6);
        cell.setCellValue((String) "USUARIO");

        ReportesDelegate reporteEstados = new ReportesDelegate();
        int rownum = 1;
        out.flush();
        try {
            /*
             Metodo que recibe la fecha en formato dd/mm/YYYY
             finicio en formato dd/mm/yy hh24:mi:ss
             ffin en fomrato dd/mm/yy hh24:mi:ss
             accion B o D //bloqueo desbloqueo
             compania en codigo_compania x ej 219 claro
             retorna una lista del reporte cobranza en detalle.
             */
           
            List resultadoEstado = reporteEstados.getDetalleCobranza(fecha, fechainicio + " 00:00:00", fechafinal + "23:59:59", accion, compania);
            int tamaniolista=resultadoEstado.size();
            for (ReporteCobranza r : resultadoEstado) {
 
                Row row = sheet.createRow(rownum++);

                Cell cellda = row.createCell(0);
                cellda.setCellValue(r.getImei().toString());
                cellda = row.createCell(1);
                cellda.setCellValue((String) r.getMarca());
                cellda = row.createCell(2);
                cellda.setCellValue((String) r.getModelo());
                cellda = row.createCell(3);
                cellda.setCellValue((String) r.getFechaIngreso());
                cellda = row.createCell(4);
                cellda.setCellValue((String) r.getAccion());
                cellda = row.createCell(5);
                cellda.setCellValue((String) r.getTipoTecnologia());
                cellda = row.createCell(6);
                cellda.setCellValue((String) r.getUsuario());

            }
            for (int i = 0; i < tamaniolista; i++) {
                sheet.autoSizeColumn(i);
            }
        } catch (Exception e) {
            System.out.println("Error reporte:" + e);
        }

        CustomOutputStream out2 = new CustomOutputStream(out, headerBytes.length);
        wb.write(out2);
        out.flush();
        out.close();
        wb.dispose();
    }



Considere el uso de la versión Streaming de POI. Esto cargará un subconjunto del archivo en la memoria según sea necesario. Es el método recomendado cuando se trata de archivos de gran tamaño:
SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk




Al ecribir el encabezado uso el "sheet.autoSizeColumn", pero solo lo hago en el encabezado, ya que si se integra en el ciclo de creacion este reduce considerablemente la rapidez con que se genera el archivo EXCEL. Consultar Documentacion relacionada del metodo
En las siguientes lineas creo un OutputStream que ocupare para enviar solo el encabezado del archivo y despues cuando empieze a llegar las ROW las enviare al navegador, la velocidad de descarga dependera de la conexion entre el servidor de Aplicaciones y la aplicacion y el tiempo de la Base de datos, considerando la cantidad de informacion que manejaba se pueden estimar en archivos de 150 MB promedio. Generar un archivo asi en una aplicaciones WEB es un tiempo considerable que se le debe hacer esperar al usuario, la mejor solucion fue el CustomOutputStream.
Por ultimo el " response.flushBuffer" con esto se vacia el buffer y se envia al response la informacion. En la primera vuelco de buffer es solo el HEADER generico de un archivo EXCEL XLSX.

        OutputStream out = response.getOutputStream();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=utf8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=\"" + sheet.getSheetName() + ".xlsx\"");
        final byte headerBytes[] = new byte[]{0x50, 0x4b, 0x03, 0x04, 0x14, 0x00};
        out.write(headerBytes);
        response.flushBuffer();

Controlador de SPRING que activa la Descarga

import cl.claro.aplicaciones.webberr.modelo.CobranzaModel;
import cl.clarochile.aplicaciones.berr.configuracion.dao.entities.Compania;
import cl.clarochile.aplicaciones.berr.configuracion.dao.entities.Estado;
import cl.clarochile.aplicaciones.berr.configuracion.delegate.ConfiguracionDelegate;
import cl.clarochile.aplicaciones.berr.consultas.to.HistoricoVistaTO;
import cl.clarochile.aplicaciones.berr.reportes.to.CobranzaResumen;
import cl.clarochile.aplicaciones.berr.reportes.to.DatoBitacoraProceso;
import cl.clarochile.aplicaciones.berr.reportes.to.ReporteCobranza;
import cl.clarochile.aplicaciones.berr.service.delegate.ReportesDelegate;
import cl.clarochile.infraestructura.exceptions.BussinesFault;
import cl.clarochile.infraestructura.exceptions.TechnicalFault;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

     @RequestMapping(value = "/descargaDetalleCobranza")
    public void descargaDetalleCobranza(@RequestParam(value = "compania") String compania,
            @RequestParam(value = "fecha") String fecha,
            @RequestParam(value = "fechainicio") String fechainicio,
            @RequestParam(value = "fechafinal") String fechafinal,
            @RequestParam(value = "accion") String accion,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        doDownload(accion, fecha, fechainicio, fechafinal, compania, request, response);

    }


Clase que extiende ServletOutputStream para evitar volver a enviar el Header del archivo XLSX
class CustomOutputStream extends ServletOutputStream {

        OutputStream os;
        int skip = 0;
        int n = 0;

        public CustomOutputStream(OutputStream out, int skip) {
            this.os = out;
            this.skip = skip;
        }

        @Override
        public void write(int b) throws IOException {
            if (n < skip) {
                n++;
                return;
            }

            os.write(b);
        }
    }


ReporteCobranza.jsp

 Excel
                                                                            

Resumen de lo aprendido en la ONT Day 2014

Bruno Borjes – Building Java EE 7 Applications with WebLogic 12c


Optimizer Master Class with Tom Kyte

Turbo Mobile Development with Oracle …presentin David Peake BLOG David Peake

Dana Singleterry – HOL – Developing a Web Dashboard & ADF WEB Y MOVILE

Blog Dana Singleterry

[BASH] ERROR line 1: #!/bin/bash: No existe el fichero o el directorio

Este error aparece cuando se editar el archivo agregando el extra fin de carro es decir "\r\n" o el byte (BOM) en la primera linea del archivo, para descubrir que pasa debemos ejecutar el siguiente comando:
$ head -1 yourscript | od -c

and see how it ends: This is wrong

0000000   ï   »   ¿   #   !   /   b   i   n   /   b   a   s   h  \n
0000017

This is correct:
0000000   #   !   /   b   i   n   /   b   a   s   h  \n

Use dos2unix to fix your script if this is the issue. Esto ocurre por editar los archivos con un editor de texto gráfico como el Kate con la opción activa de Herramientas-> "Añadir marca de orden de byte(BOM)"

[SOA] Oracle JDeveloper install soporte para OSB

Instalando soporte para SOA al Jdeveloper:

Primero descargar la version 11g de :


chmod 775 jdevstudio11116install.bin 
luxo@luxo-Vostro-3460:~/Descargas$ ./jdevstudio11116install.bin 
Extracting 0%....................................................................................................100%

Jdeveloper Downloads

Ir a HELP-> Check for Updates-> next->  next-> Instalar las siguientes versiones extensiones:

  • Oracle SOA Composite Editor
  • Oracle BPM Studio
  • Spring & Oracle Weblogic SCA 


Reiniciar IDE,luego:

Steps in JDeveloper 1. Create DB Connection in JDeveloper. 2. Create a Generic Project. 3. Create Project as SOA project and use Empty Composite.

Steps to create DB Adaptor

Go to Composite Palette and choose AD Adaptor. Drag and drop the DB Adaptor in the External Reference section (right side of Composite view). It will open a wizard for selecting the connection and Other DB related process. Give name to service that you want to create Choose the DB Connection you have created already. Move one with selecting your desired choice of Stored Procedure or Table (insert/Select) functionality that you want your web service to perform. If you choose Table insert/Select then you can also choose the relation between tables as optional step. Try to keep all steps default if you do not want any special features. Once you finish all steps in wizard, then it will generate whole lot of files under your Project. Look for 4 main files .jca, xsd/.xsd, *.mapping.xml, *.wsdl If you see all these files generated well in your project then you are all set and we can move ahead. If not then look for the issue.

Steps in WLS Console Create Data Source

1.Go to Left panel and choose Data Source. 2. Select New -- Generic Data Source 3. Give Name as you wish but for JNDI Name you have to use the connection name from the *.JCA file that you already have. Open the jca file and search for the ‘UIConnectionName’. This value will be used as JNDI name in data source creation. 4. Choose Driver as oracle.jdbc.xa.client.OracleXADataSource 5. Use the host and Port and other details that you had selected during DB Connection (in JDeveloper). This is obvious step. 6. Choose target AdminServer. 7. If you finish everything correctly. You are all set here and you can choose to test the connection and should be Test Success.

Configure the DB Adaptor

Go to Deployment on left hand panel. In Deployed services. Search for DbAdaptor. Click on the name DbAdaptor. Select Configuration tab. And under it choose Outbound Connection Pool. Here you will see (javax.resource.cci.ConnectionFactory) Click on new.

Choose javax.resource.cci.ConnectionFactory Next page will ask for JNDI Name. For this, you have to go to your *.jca file and choose the value which is already there for Connection-factory as Location (like connection-factory location=?). Use the value of Location as JNDI Name. Transaction will be No Transaction. Choose this for now. This is need basis selection. Leave other selection as is and then Finish.

Note : Once you finish. Go to Properties Tab again and look for a property name : xADataSourceName. Its value should be the same as UIConnectionName that you have in *.jca file. It should be populated. If not then you can set now as well. You have to double click on the value section and then write the name and press enter. Then Save it. With above all steps we have set the DbAdaptor to point to same DB where we have our table/store procedure.

[XML]Apache Commons XMLConfiguration fetch Object list?

Como se puede cargar un archivo de texto plano a XML, la libreria org.apache.commons.configuration, pero que pasa con los XML que tienen varios niveles dentro del Tag raíz?
EJ:
  
      
 VOZ
 servicio de voz
 OBO,4:OBI,2:OICK,0:OBSSM,0:OSB1,0
 OBO,1:OBI,2:OICK,0:OBSSM,1:OSB1,1
 1
      
      
 Llamadas a Moviles
 Servicio de llamadas a móviles
 OBO,0
 OBO,2
 1
      
      
 700
 Servicio de llamada a 700
 OBOPRE,0
 OBOPRE,1
 1
      
      
   LDI
   Larga distancia Internacional
   OBOPRI,0
   OBOPRI,1
   1
      
      
   300
   Servicio llamadas a 300
   OSB3,0
   OSB3,1
   1
      
  

Para recórrelas solo vasta:

List listaServicios = arch.config.getList("servicios.servicio.codigo");

int nunRowPcsFile = listaServicios.size();
        log.info("Cantidad de servicios Leidos del archivo de configuracion:"+nunRowPcsFile);
        int i = 0;

        registrosTbl = new RequestConsulta[nunRowPcsFile];

        if (nunRowPcsFile != 0) {

            for (String rs : listaServicios) {

                RequestConsulta datosObj = new RequestConsulta();
                String codigo=arch.config.getString("servicios.servicio(" + i + ").codigo");
                datosObj.setCodigo(codigo);
                String on=arch.config.getString("servicios.servicio(" + i + ").servicio_on");
                datosObj.setActivacion(on);
                String off=arch.config.getString("servicios.servicio(" + i + ").servicio_off");
                datosObj.setDesactivacion(off);               
                registrosTbl[i] = datosObj;
                i++;

            }

        }

PD: código funciona para java >= 1.6

INFO:INFO API

Instalar Decompiler Java Ubuntu 14.10


Al ejecutar el decompiler de java JD-GUI da este error:
./jd-gui: error while loading shared libraries: libgtk-x11-2.0.so.0: cannot open shared object file: No such file or directory

Solucion instalar las liberias X11 del GTK:
sudo apt-get install libgtk2.0-0:i386 libxxf86vm1:i386 libsm6:i386 lib32stdc++6

[Weblogic] Respaldar un dominio weblogic

$MW_HOME/wlserver_[version]/common/bin pack -domain =path_of_domain -template=path_of_jara_file_to_create -template_name=”template_name” [-template_author="author"][-template_desc="description"] [-managed=true|false][-log=log_file] [-log_priority=log_priority]






Syntax of the Pack Command
Default value for -managed is false
En el caso de claro estan usando un dominio con un manager de nodos por lo que la opcion managed debe ser true.

Bug Disable Menu Compile en NETBEANS 8.0 en LInux


Product Version: NetBeans IDE 8.0 (Build 201403101706)
Updates: NetBeans IDE is updated to version NetBeans 8.0 Patch 1.1
Java: 1.7.0_51; OpenJDK 64-Bit Server VM 24.45-b08
Runtime: OpenJDK Runtime Environment 1.7.0_51-b00
System: Linux version 3.11.0-19-generic running on amd64; UTF-8; es_CL (nb)
User directory: /home/luxo/.netbeans/8.0
Cache directory: /home/luxo/.cache/netbeans/8.0



The cache is located in /home/luxo/.cache/netbeans/8.0/var/cache. Deleting this directory should clear the cache for you.

how to reset weblogic password

http://www.oracle-base.com/articles/11g/reset-the-adminserver-password-in-weblogic-11g-and-12c.php
En mi caso:
export MW_HOME=/home/luxo/Oracle/Middleware

export DOMAIN_HOME=$MW_HOME/user_projects/domains/berr

$DOMAIN_HOME/bin/stopWebLogic.sh

mv $DOMAIN_HOME/servers/AdminServer/data $DOMAIN_HOME/servers/AdminServer/data-old .

$DOMAIN_HOME/bin/setDomainEnv.sh

cd $DOMAIN_HOME/security

java weblogic.security.utils.AdminAccount weblogic allware123 .

ERROR Readline Java File UTF8

Este error ocurre cuando se lee un archivo de texto guardado en sistemas operativos UNIX/LINUX en donde se guardan ciertos byte que le dan la codificación UTF-8, lo cual entorpece la comparación del método a byte[] incluya estos caracteres haciendo que una simple comparación de String sea distinta a lo esperado.

    /**
 * 
 * 
 * @param s string a remover caracter UTF8
 * @return 
 */
    private static String removeUTF8BOM(String s) {
        if (s.startsWith("\uFEFF")) {
            s = s.substring(1);
        }
        return s;
    } 

por ejemplo una aplicacion seria:
BufferedReader reader = new BufferedReader(new FileReader(files[i]));
                String header = readLine(reader);
                reader.close();

                String fileRegistroDebloqueo;
                String fileDesbloqueoDebloqueo;
                header = removeUTF8BOM(header);
                header = header.toUpperCase();
                if (header.equals("CUENTA")) {
                    compania = "CLARO";
                } else {
                    compania = extractCompany(files[i]);
                }
 


Oracle Linux BETA

OracleLinux-R7-U0-BETA-Everything-x86_64-dvd.iso (4,785,700,864 bytes)

The early development builds of Oracle Linux 7 are provided for testing purpose only.  The build includes two kernels: 
  • The Unbreakable Enterprise Kernel Release 3 Update 2 (beta release)
  • Red Hat compatible kernel. 
This beta release should not be used in production environments.

Linux Container packages for Unbreakable Enterprise Kernel Release 3 

Download  lxc-1.0.3-2.0.2.el7.x86_64.rpm (200,632 bytes)
Download  lxc-devel-1.0.3-2.0.2.el7.x86_64.rpm (17,452 bytes)
Download  lxc-libs-1.0.3-2.0.2.el7.x86_64.rpm(181,952 bytes)

CVE-2014-0160:  Security Update for openSSL (Heartbleed)

Oracle Linux is an open source operating system available under the GNU General Public License (GPL).  Oracle Linux is optimized for Oracle hardware and software and offers zero-downtime kernel updates with Ksplice and enterprise tracing and diagnostic capabilities with DTrace.  Oracle Linux is free to download, free to distribute and free to use.  All errata is freely available on public-yum.oracle.com


Please review Oracle Linux 7 Beta Release Notes for known issues prior to installation.  To learn more about Oracle Linux, visit www.oracle.com/linux

Documentation

Support

  • Please work with your Oracle team If you have any questions; or send us email at: oraclelinux-beta-info_ww@oracle.com
  • Oracle Bugzilla will be used to file bugs. You will need to request an Oracle Bugzilla account at http://bugzilla.oracle.com. When filing bugs, please choose the release Oracle Linux 7, and select the appropriate components to proceed.

 


nuevo Netbeans 8.0

Nuevo netbeans

Estoy probar las nuevas funcionalidades, en cuanto al soporte de plugins solo probe el plugins de YII, Maven, falta mucho por probar.

https://netbeans.org/downloads/

Error Apache 2 Invalid command '\xef\xbb\xbf

Starting Apache Web Server...
Exit code: 8
Stdout:
apache config test fails, aborting
Stderr:
AH00526: Syntax error on line 1 of /opt/lampp/apache2/conf/httpd.conf:
Invalid command '\xef\xbb\xbfAlias', perhaps misspelled or defined by a module not included in the server configuration

Este error surge porque la codificación utf8 agregar caracteres adicionales que el apache interpreta como parte del comando.

Solución:

Gardar el archivo de texto como: En el menú Herramientas elegimos Codificación y luego ISO 8859-1


[YII] Netbeans 7.4 integracion Yii Framework


Yii plugin adds useful enhancements to NetBeans IDE including the following:
  • Code completion in views (including variables passed to view and $this).
  • Go To Action, Go To View.
  • Go to view via clicking on render or renderPartial argument.
  • Go to file via clicking on path alias (Yii::importwidgetbeginWidget,createWidgetbeginCache).
  • New project wizard.

BAJAR PLUGIN

AGREGAR EL TEMPLATE AL EDITOR DEL NETBEANS O AGREGARLOS MANUALMENTE AL EDITOR:

http://www.cheatography.com/hoplayann/cheat-sheets/yii-code-templates-for-netbeans/

You can create code templates for commonly used/overridden function in Yii. For example, if you want to add an beforeSave() function in your model, by typing a shortcut you can automatically have the function template in place. There are additional shortcuts for common stuff like Yii::app(), Yii::t(), Yii::app()->user->checkAccess(), and more!
  • Download this template set to get started: http://fbe.am/hly (version 2). View all available commands in this printable cheat sheet.
  • Go to "Tools > Options > Editor > Code Templates"
  • Hit "Import", select the file, and choose "Code Templates"
    • You might get an error message "invalid zip file" if you are importing to a older/newer version of NetBeans. Open up the zip file, edit build.info, and set the correct path to Userdir.

Usage:


o BAJAR Y INSTALAR EN EL DIRECTORIO DEL NETBEANS:

TEMPLATE

Navigation

hyperlink navigation
navigation for i18n file

Run Command

run command

Code Completion

code completion for the path

Usage

Install Plugin

Download a nbm file or create it by yourself. And please, install it.

How to enable

  • Use default directory structure (don't delete yiic* files)
  • project properties > Framework > Yii, check enabled (You don't have to check this if you use plugin with default app)

Existing Source

Source directory : Please, specify the webroot directory
Webroot directory : Please, keep default (Source directory)
e.g.
testdrive (webroot directory)
├── assets
├── css
├── images
├── index-test.php
├── index.php
├── nbproject
├── protected
└── themes

Existing Source (Source Directory has other directories)

Please set webroot directory(yii path alias named "webroot" i.e. webroot is testdrive on the below tree) to webroot of project properties.
Right-click project > properties > Source > Webroot
e.g.
my_source (source directory)
├── testdrive (webroot directory)
│   ├── assets
│   ├── css
│   ├── images
│   ├── index-test.php
│   ├── index.php
│   ├── protected
│   └── themes
│ 
├── ...
├── foo
└── bar

Path settings

You can set the some paths(e.g. path alias) to project properties. If you use defferent path from default, please set relative path there from source directory.

I have added path settings to project properties.
nb-yii-plugin-path-settings-support

Usage

Please set relative path from source directory.
e.g.
Please set protected/myext to ext: if extensions directory is the following:
myproject
├─protected
│  └─myext (extensions directory)
├─...
If you want to use default directory, please set empty.
e.g.
application: myprotected
controllers: (empty)
views: (empty)
controllers directory means myprotected/controllers. views directory means myprotected/views.

Features

  • Badge icon
  • Go To Action
  • Go To View
  • Code Completion on the view file
  • Code Completion for the path
  • Init Action
  • PHPUnit Test Init Action
  • New Yii Project Wizard
  • Run Action Action
  • Navigation for path alias (Hyperlink to file)
  • Run Command Action

Go To Action

You can open the controller file and move action method.
e.g. WebRoot/protected/views/site/index.php -> WebRoot/protected/controllers/SiteController.php::actionIndex()
  1. open a view file
  2. Right-click on Editor
  3. Navigate > Go To Action

Go to View

You can open the view file for action method of the controller.(similar to Go To Action)
  1. open a controller file
  2. move the caret to action method
  3. Right-click on Editor
  4. Navigate > Go To View
If you set the keymap for this action, it's more useful.(Please, search with "php")
If you set the theme on main.php, you will go to there.
// protected/main.php
// e.g. set themes/basic
array(
    // something...
    'theme' => 'basic',
);

Hyper link to view file

You can open the view file from parameter of render and renderPartial methods. This is available on the Controller or View files.
e.g.
public actionIndex() {
    // something ...

    $this->render('foo', array('bar' => $bar));
    $this->renderPartial('bar');
}
When you use the render method like above, if foo.php exists, you do the following.

fallback to default views

You can fallback to default views if view file for your theme doesn't exist when you use the theme. If you would like to this feature, please, check "Fallback to ..." on project properties for Yii.
  1. Hold down Ctrl key on the first parameter (foo)
  2. Wait to be changed string color to blue
  3. Click (foo)
It will go to theme file if you use theme.

Navigation for path alias (Hyperlink to file)

Usage is the same as hyperlink to view file.
This feature is available for the followings:
  • Yii::import()
  • Yii::t()
  • CBaseController::widget()
  • CBaseController::beginWidget()
  • CBaseController::endWidget()
  • CBaseController::createWidget()
  • CBaseController::beginCache()
  • CBaseController::beginContent()
  1. Hold down Ctrl on target path
  2. string color is changed to blue if file exists(file path is displeyed as tooltip)
  3. Click > open file
e.g.
$this->widget('application.components.MyComponent', array());
// Hold down Ctrl on application.components.MyComponent

// support for the path that starts with '/' and '//'
$this->beginContent('//layouts/main');
$this->renderPartial('/users/foo');

// support for the class name
$this->widget('MyWidget');
Furthermore... Class name is also valid at the other places.
e.g.
return array(
    'some'=>array(
        // Hold-down Ctrl key on 'ClassName'
        'class'=>'SomeAction',
    ),
);
i18n
Yii::t('Xyz.categoryName', 'message to be translated');
// on the first parameter : open the message file for LanguageID
// on the second parameter :  open the message file for LanguageID, and caret position is moved to specified message

Notice

  • This feature works with default path alias name.
  • Automatically file creation is valid with only render and renderPartial methods.

Code Completion on the view file

Provide support for code completion on the View file.
e.g. webapp/protected/controllers/SiteController.php
class SiteController extends Controller {
    // something...

    public function actionIndex(){
        // ...
        $this->render('foo', array(
            'var1' => $var,
            'var2' => 'bar',
        ));
    }
}
e.g. webapp/protected/views/site/index.php
$ // [Ctrl + Space] popup $var1, $var2, $this, ...
$this-> // [Ctrl + Space] popup SiteController methods and fields

Code Completion for the path

This is available the following methods:
  • render
  • renderPartial
  • beginContent
  • beginCache
  • import
  • *widget
e.g.
// type character or [Ctrl + Space]
$this->render('i');

// class or path alias
$this->widget('application.[Ctrl + Space]');

Init Action

Run the followings:
  • Set framework directory path to Project Properties.
  • Create a file for code completion.
Project right-click > Yii > Init

 Testing 

To run functional tests and unit tests in Yii, recommended is installing PHPUnit and SeleniumRC.
  • Install PHPUnit
  • Install SeleniumRC by getting the NetBeans plugin
    • Open "Tools > Plugins > Available Plugins"
    • Install "Selenium Module for PHP"
  • Configure project options
    • Open "File > Project properties > Sources" and set "Test Folder" to [PROJECT ROOT]/protected/tests (If the whole project testing doesn't work, try [PROJECT ROOT]/protected/tests/unit)
    • Open "File > Project properties > PHPUnit" and set "Use Bootstrap" to [PROJECT ROOT]/protected/tests/bootstrap.php, and "Use XML Configuration" to [PROJECT ROOT]/protected/tests/phpunit.xml

Usage:

  • Test whole project: Alt+F6
  • Test single file: Shift-F6
  • Check code coverage (right click project > Code Coverage)

4. Debugging 

  • Install Xdebug (usually already available in your installation):
  • Include the Xdebug extension for PHP:
    • In php.ini enable (by removing ; prefix) these settings:
      zend_extension = "C:\xampp\php\ext\php_xdebug.dll"
      xdebug.remote_enable = 1
      xdebug.remote_handler = "dbgp"
      xdebug.remote_host = "localhost"
      xdebug.remote_port = 9000

Usage:

  • Debug project: Ctrl-F5
  • Use breakpoints, walk through running code, and watch variables and objects in real-time. :)
  • If you want to stop the debugger from pausing on the first line for every request, simply turn that "feature" off by clicking: Tools > Options > PHP > Debugging > Stop at First Line (uncheck)

[SHELL]Ver las variables de entorno de Linux/Unix

El compando export, sirve para agregar variables de sistema para distintas aplicaciones por ej: para el caso de java JAVA_HOME, si tenemos shell corriendo etc.
Por ejemplo:

usuario@acura:~$ export
declare -x HOME="/home/usuario"
declare -x LANG="en_GB.UTF-8"
declare -x LANGUAGE="en_GB:en"
declare -x LC_ADDRESS="en_US.UTF-8"
declare -x LC_IDENTIFICATION="en_US.UTF-8"
declare -x LC_MEASUREMENT="en_US.UTF-8"
declare -x LC_MONETARY="en_US.UTF-8"
declare -x LC_NAME="en_US.UTF-8"
declare -x LC_NUMERIC="en_US.UTF-8"
declare -x LC_PAPER="en_US.UTF-8"
declare -x LC_TELEPHONE="en_US.UTF-8"
declare -x LC_TIME="en_US.UTF-8"
declare -x LESSCLOSE="/usr/bin/lesspipe %s %s"
declare -x LESSOPEN="| /usr/bin/lesspipe %s"
declare -x LOGNAME="usuario"
declare -x LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.axa=00;36:*.oga=00;36:*.spx=00;36:*.xspf=00;36:"
declare -x MAIL="/var/mail/usuario"
declare -x OLDPWD
declare -x ORACLE_HOME="/Oracle/app/product/11.2.0/dbhome_1"
declare -x ORACLE_SID="BERR"
declare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/Oracle/app/product/11.2.0/dbhome_1/bin"
declare -x PWD="/home/usuario"
declare -x SHELL="/bin/bash"
declare -x SHLVL="1"
declare -x SSH_CLIENT="10.10.30.9 50309 22"
declare -x SSH_CONNECTION="10.10.30.9 50309 192.168.40.21 22"
declare -x SSH_TTY="/dev/pts/6"
declare -x TERM="xterm"
declare -x USER="usuario"
declare -x XDG_SESSION_COOKIE="8c19c58df429568648ecf60c00000638-1394136889.281238-1263694637"

Problemas de activación WIFI6 en LG_OLED55CXPSA

  Mi experiencia con este TV  ah sido impecable hasta ahora, llevaba un uso normal y no tenia que usar la conexión por wifi ya que tengo una...