rpg IV - Redsis
Transcripción
rpg IV - Redsis
APPLICATION DEVELOPMENT Novedades IBM i 7.1 Octubre 2014 Más que un proveedor de tecnología, su aliado estratégico 1 www.redsis.com / [email protected] Application development enhancements IBM i 6.1 • “IBM Developer Kit for Java” • “IBM Toolbox for Java” • “Websphere Development Studio” • “Application Development ToolSet” • “Debugger” • “Portable Application Solutions Environment” • “Qshell and utilities” • “XML toolkit” • “Control language” • “Structure Query Language” • “Application programming interfaces” • “Globalization” • “Multithreaded applications” IBM i 7.1 • “High-level programming languages” • “Control language CL” • “PHP”, ”Ruby” • “Lotus products for IBM i” HIGH-LEVEL PROGRAMMING LANGUAGES ILE BASICS ILE –Integrated Language Environment 20 años de Flexibilidad y Eficiencia 1988 1994 2014 OPM – Original Program Model ILE – Integrated Language Environment OPM Concepts • Subrutines • Programs ILE Concepts • • • • • • • Activation Groups Subprocedures Module Programs Service Programs Binding Directories Binder Language ILE –Integrated Language Environment • Activation Groups • Subprocedures • Module • Programs • Service Programs • Binding Directories • Binder Language – Grupo de Programas que pueden compartir recursos entre si y pueden ser desactivados juntos. – Subrutinas con Parametros y variables locales. Como si fuesen pequeños programas dentro de un programa Módulo. – Lista de ‘subprocedures’ agrupados en un objeto. – Modulos con un PEP (Program Entry Point) y que puede ser ejecutado con un commando CALL. – Modulos con o sin PEP que pueden ser llamados desde Programas ILE. – Una Lista, similar al concepto de *LIBL , que se usa cuando se busca un ‘subprocedure’. – Un pequeño grupo de comandos no ejecutables que define la Lista de ‘subprocedures’ en un ‘Service Program’ que pueden ser llamados externamente. Programs, Modules, Service Programs, Subprocedures, Binder Directory FAONL_OP *PGM Main exsr SRpago If (a>b) exsr SRint exsr SRdesp SRpago SRint SRdesp SV_FACTU *SRVPGM Fac_Int MD_FAONL *MOD Fac_Pago Main Fac_Pago() If (a>b) Fac_Int() Fac_Promo() exsr SRdesp Fac_Desc Fac_Promo Fac_Combo SRdesp SV_CLIEN *SRVPGM Cli_validadir FAONL_IL *PGM Cli_valcredit MD_FACT Main SV_FACTU FABCH_IL *PGM MD_FACL MD_FABCH BD_COMER Cli_calcupo MD_FACL *MOD MD_FABCH *MOD PGM Cli_calcupo() Fac_Pago() If (a>b) Fac_Int() Fac_Promo() Cli_despa() CALLPRC ENDPGM Cli_fideliz Cli_despa BD_COMER *BNDDIR SV_CLIEN SV_FACTU Módulos C SOURCE COBOL SOURCE CL SOURCE RPG SOURCE CRTCMOD CRTCBLMOD CRTCLMOD CRTRPGMOD CRTPGM MOD(A,B,C,D) Binder Language El lenguaje de encadenamiento “Binder language” le permite a un programa de servicio ser actualizado fácilmente sin tener que recrear los programas que lo utilizan. El comando Retrieve Binder Source (RTVBNDSRC) puede ser usado para ayudar a generar el código fuente basado en exports de uno o mas módulos o programas de servicio. No se requiere el uso de lenguaje de encadenamiento si se da alguna de las siguientes condiciones: • EL programa de servicio NUNCA cambia • Los usuarios de los programas de servicio NO tienen inconveniente en CAMBIAR sus programas cuand cambia la firma digital. Dado que esta situación no es la mejor para la mayoría de aplicaciones, CONSIDERE el uso de lenguaje de encadenamietno en TODOS los programas de servicio. STRPGMEXP PGMLVL(*CURRENT) EXPORT SYMBOL(’Fac_pago') EXPORT SYMBOL(’Fac_int') EXPORT SYMBOL(’Fac_desc') EXPORT SYMBOL(’Fac_promo') EXPORT SYMBOL(’Fac_combo') ENDPGMEXP CRTSRVPGM SRVPGM(MYLIB/SV_FACTU) MODULE(MYLIB/FINANC MYLIB/MARKET) EXPORT(*SRCFILE) SRCFILE(MYLIB/QSRVSRC) SRCMBR(*SRVPGM) STRPGMEXP PGMLVL(*CURRENT) EXPORT SYMBOL(’Fac_pago') EXPORT SYMBOL(’Fac_int’) EXPORT SYMBOL(’Fac_desc') EXPORT SYMBOL(’Fac_promo') EXPORT SYMBOL(’Fac_combo') EXPORT SYMBOL(’Fac_glosa') ENDPGMEXP STRPGMEXP PGMLVL(*PRV) EXPORT SYMBOL(’Fac_pago') EXPORT SYMBOL(’Fac_int') EXPORT SYMBOL(’Fac_desc') EXPORT SYMBOL(’Fac_promo') EXPORT SYMBOL(’Fac_combo') ENDPGMEXP Activation Groups ACTGRP *INLR=*on RCLRSC JOB SIGNOFF QUIZ Cual de los siguientes lenguajes de programación es Nativo en IBM i ? a. b. c. d. RPG II RPG III RPG/400 RPG IV d. -S/36 (1983 – 2000) -S/38 (1979 – 1988) -AS/400 OPM (1988 - 1993) -iSeries, System i, Power (IBM i) ILE 101 Tips & Técnicas de RPG IV TIP #1. “ Intentar utilizar el tipo de datos mas eficiente, SIEMPRE o CASI siempre “ ZONED, PACKED, INT, FLOAT, REAL, DOUBLE, DECFLOAT, CHAR, VARCHAR, GRAPHIC, VARGRAPHIC, BLOB, CLOB Datos Numéricos QUIZ En cuales de los siguientes tipos de datos se realizan las operaciones matemáticas de manera mas eficiente en los procesadores IBM POWER ? a. b. c. d. e. Decimal con Zona Decimal Empaquetado Entero Punto Flotante Binario Punto Flotante Decimal c. d. c. d. e. Tipos de Datos Numéricos DB2 – RPG IV * BINARY DsmallestBIN DlargestBIN Digitos S S 1B 0 9B 0 DOneByteINT S 3i 0 DTwoByteINT S 5i 0 DFourByteINT DEigthByteINT S S 10i 0 20i 0 DOneByteUNS S 3u 0 DTwoByteUNS S 5u 0 DFourByteUNS DEigthByteUNS S S 10u 0 20u 0 * INTEGER X * UNSIGNED F * PACKED DECIMAL F F DsmallestPACKED DlargestPACKED S S 1P 0 63P 0 * ZONED DECIMAL DsmallestZONED DlargestZONED i10 i20 1S 0 63S 0 * BINARY FLOATING POINT BIU i3 i5 S S P S DFourByteFLOAT S 4F DEigthByteFLOAT S 8F BYTES Datos Numéricos óptimos RPG • • • • • • • Binario (DDS) Decimal con Zona (SQL ó DDS) Decimal Empaquetado (PAR) (SQL ó DDS) Decimal Empaquetado (IMPAR) (SQL ó DDS) Entero (con/sin Signo) (SQL) Punto Flotante (SQL) Punto Flotante Decimal (SQL & C/C++ /java) Binario en RPG <> Binario en DDS <> Binario en SQL 9 dígitos 18 dígitos /String 32,768 String 32,768 Definición de Datos SQL, DDS, RPG *...+....1....+....2....+....3....+....4....+....5....+... 00001■■■■■■■■■■■■■■■■■■0■■■■■■■Ø■■■0■■■■■■■■■■■■■■■■■■■■■■ FFFFF001000000000000003F00000038003F0000002000000000000000 0000100F00010100000001F0000000F000F00000002800000000000001 Field NUMERIC_FLD DECIMAL_FLD INTEGER_FLD SMALLINT_FLD BIGINT_FLD FLOAT_FLD REAL_FLD DOUBLE_FLD DECFLOAT_FLD File DATATYPE DATATYPE DATATYPE DATATYPE DATATYPE DATATYPE DATATYPE DATATYPE DATATYPE Type NUMERIC DECIMAL INTEGER SMALLINT BIGINT FLOAT FLOAT FLOAT DECFLOAT *...+....1....+....2....+....3 ■■■■■■■■■■■■■■■■■■■Ø■■■0■■■■■■ 01010000000000000038003F000000 0F0F01000100000001F000F0000000 Length 5 5 9 4 18 16 8 16 34 Scale 15 7 15 Historia de la Computación IBM card format, designed in 1928 &-0123456789ABCDEFGHIJKLMNOPQR/STUVWXYZ 12Y| 11X| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9| x x xxxxxxxxx xxxxxxxxx x xxxxxxxxx x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x ZONA DIGITO 1928, Tarjeta perforada de 80 columnas y 12 posiciones de perforación. Era posible adicionar signo con una perforación adicional en la zona del digito menos significativo de una cifra, Zona 12 para + y Zona 11 para – 1931, IBM introdujo perforaciones múltiples para MAYUSCULAS y caracteres especiales. (Dos perforaciones en zona (12,11,0) + digito [1–9]) 1964, con la introducción de EBCDIC se permitían columnas con hasta 6 perforaciones (Zonas [12,11,0,8,9] + digito [1–7]). 1969, American National Standard definio perforaciones estandarizadas para 128 caracteres EBCDIC ZONA 12 ZONA 11 ZONA 0 ZONA 12,11 ZONA 12,0 ZONA 11,0 Decimal con Zona RPG( 5S 0) -99,999 … +99,999 32.5% Decimal Empaquetado RPG( 9P 0) -999,999,999 … +999,999,999 63.7% Entero RPG( 3i ) 1Byte -127 … +128 RPG( 5i ) 2Byte -32768 … 32767 RPG( 10i ) 4Byte -2147483648 … 2147483647 RPG( 20i ) 8Byte - 9223372036854775808 … 9223372036854775807 120% Punto Flotante Binario (BFP) -127 0 128 <-- Exponente binario real +-------+-------+-------+-------+ 0 127 255 <-- Representación en Punto flotante del exponente (8 Bits) 4 6 0100 0001 1 C 1010 0000 4 0 0100 0000 0 0 0000 0000 *...+....1....+....2....+....3....+....4....+....5....+... 00001■■■■■■■■■■■■■■■■■■0■■■■■■■Ø■■■0■■■■■■■■■■■■■■■■■■■■■■ FFFFF001000000000000003F00000041403F0000002000000000000000 0000100F00010100000001F00000006C00F00000002800000000000001 Punto Flotante Decimal - DFP IEEE 754-2008 Type Name Size Precision decimal32 32 Bits 4 Bytes 7 Digitos Single decimal64 64 Bits 8 Bytes 16 Digitos Double -398 a +369 decimal128 128 Bits 16 Bytes 34 Digitos Quad -6176 a +6111 Signo Campo de Combinación Continuación de Exponente Rango de Exponente -101 a +90 Continuación de Dígitos del coeficiente Bit de Signo Codifica los primeros 2 bits del Exponente y el digito mas Significante del coeficiente (MSD) Codifica los bits restantes del exponente + BIAS Codifica los dígitos restantes en bloques de 3 bits por dígito DPD (Densely Packed Decimal) Porque usar DFP ? Decimal Floating Point Generalizado • La aritmética Decimal es prácticamente de uso universal a excepción de los computadores. Precisión • Mas preciso para números decimales vs BFP (Punto Flotante Binario) • Puede representar números “importantes” en forma exacta. Tendencia de Programación • Estándares IEEE 754, IEEE 854, IEEE 754R, IEEE 754-2008 • DB2, SAP, Java 6 … Rendimiento • Conversión mas sencilla desde/hacia cadenas de caracteres. • Excelente para trabajar con bases de datos. Porque evitar el uso de DFP ? Decimal Floating Point Cambio • Es nuevo y diferente Popularidad • No todos los lenguajes soportan DFP • • • Java 6 C/C++ SQL • Soporte limitado por parte de fabricantes e ISVs Rendimiento • NO todos los procesadores soportan DFP • IBM Power6, IBM Power7, IBM Power7+, z10 • Las implementaciones de Software pueden ser lentas • Intel Complejidad • Formatos Incompatibles (DPD y BID) Densely Packed Decimal Parte de IEEE-754r (abcd) (efgh) (ijkm) (pqr)(stu)(v)(wxy) ? ? ? Punto Flotante Decimal - DFP IEEE 754-2008 2 2 3 8 0 0 0 0 0 1 2 7 1 7 7 8 0010 0010 0011 1000 0000 0000 0000 0000 0000 0001 0010 0111 0001 0111 0111 1000 *...+....1....+....2....+....3.. ■■■■■áű■■■■■■■Ì■■■■■■■■■■■■■■■Ì 00002468230002172000000000000217 0001357F280017782800000000001778 QUIZ Para mis variables de trabajo (contadores, indices, etc.) que tipo de datos debo usar ? a. b. c. d. e. Decimal con Zona Decimal Empaquetado Entero Punto Flotante Binario Punto Flotante Decimal c. Datos Alfanumericos Tipos de Datos Alfanuméricos DB2 – RPG IV * SQLTYPE(ROWID) T Z * * D * SQLTYPE(XML_CLOB) SQLTYPE(XML_DBCLOB) SQLTYPE(XML_BLOB) * SQLTYPE(BINARY) SQLTYPE(VARBINARY) SQLTYPE(BLOB) ANC AC * * * G G * * * SQLTYPE(CLOB) SQLTYPE(DBCLOB) Datos Alfanuméricos óptimos • • • • • DATETIME • • • TIME DATETIME DATE • • • • • • • • • CHAR VARCHAR CLOB BINARY VARBINARY BLOB GRAPHIC VARGRAPHIC DBCLOB • ROWID • XML • DATALINK STRING ROWID XML DATALINK Datos Alfanuméricos óptimos DATE & TIME & DATETIME La falta de manejo de fechas hace que RPG/400 tenga dificultades para atender algunas necesidades básicas de aplicaciones de negocios, como determinar el numero de días transcurridos entre dos fechas o adicionar cierto numero de días/meses/años a una fecha para obtener una nueva fecha. NumberOfDays = %Diff(%Date(MMDDYY: *MDY0): %Date(): *D); C C C C C C C C C*** C C C C C C C C C C C C C C C C C C C C C C C C DAYSNC DATE2 DATCLC MM YY REM YY YY YY TEMP DAYS BEGSR EXSR DATCLC MOVE ABSDAT MOVE UDATE EXSR DATCLC MOVE ABSDAT SUB DATE1 ENDSR BEGSR Z-ADDMTH,MM ADD DD IFGT 2 DIV 4 MVR IFEQ 0 ADD 1 ENDIF ENDIF IFGT 39 SUB 40 ELSE ADD 60 ENDIF MULT 365 DIV 4 MVR IFGT 0 ADD 1 ENDIF ADD YD ADD LYA ENDSR DATE1 MMDDYY 50 DATE2 NODAYS 50 DAYS DAYS 30 TEMP REM 30 10 DAYS YY YY YD LYA TEMP 50 30 LYA ABSDAT ABSDAT 50 RPG Built-in Functions DB2 – Date/Time BIFs (SQL Buid-In Functions) ADD_MONTHS The ADD_MONTHS function returns a date or timestamp that represents expression plus numeric-expression months. CURDATE The CURDATE function returns a date based on a reading of the time-of-day clock when the SQL statement is executed at the current server. The value returned by the CURDATE function is the same as the value returned by the CURRENT DATE special register. CURTIME The CURTIME function returns a time based on a reading of the time-of-day clock when the SQL statement is executed at the current server. The value returned by the CURTIME function is the same as the value returned by the CURRENT TIME special register. DATE The DATE function returns a date from a value. DAY The DAY function returns the day part of a value. DAYNAME Returns a mixed case character string containing the name of the day (for example, Friday) for the day portion of the argument. DAYOFMONTH The DAYOFMONTH function returns an integer between 1 and 31 that represents the day of the month. DAYOFWEEK The DAYOFWEEK function returns an integer between 1 and 7 that represents the day of the week, where 1 is Sunday and 7 is Saturday. DAYOFWEEK_ISO The DAYOFWEEK_ISO function returns an integer between 1 and 7 that represents the day of the week, where 1 is Monday and 7 is Sunday. DAYOFYEAR The DAYOFYEAR function returns an integer between 1 and 366 that represents the day of the year where 1 is January 1. DAYS The DAYS function returns an integer representation of a date. HOUR The HOUR function returns the hour part of a value. JULIAN_DAY The JULIAN_DAY function returns an integer value representing a number of days from January 1, 4713 B.C. (the start of the Julian date calendar) to the date specified in the argument. LAST_DAY The LAST_DAY scalar function returns a date or timestamp that represents the last day of the month indicated by expression. MICROSECOND The MICROSECOND function returns the microsecond part of a value. MIDNIGHT_SECONDS The MIDNIGHT_SECONDS function returns an integer value that is greater than or equal to 0 and less than or equal to 86 400 representing the number of seconds between midnight and the time value specified in the argument. MIN The MIN scalar function returns the minimum value in a set of values. MINUTE The MINUTE function returns the minute part of a value. MONTH The MONTH function returns the month part of a value. DB2 – Date/Time BIFs (SQL Buid-In Functions) MONTHNAME Returns a mixed case character string containing the name of the month (for example, January) for the month portion of the argument. MONTHS_BETWEEN The MONTHS_BETWEEN function returns an estimate of the number of months between expression1 and expression2. NOW The NOW function returns a timestamp based on a reading of the time-of-day clock when the SQL statement is executed at the current server. The value returned by the NOW function is the same as the value returned by the CURRENT_TIMESTAMP special register. If this function is used more than once within a single SQL statement, or used with the CURDATE or CURTIME scalar functions or the CURRENT_DATE, CURRENT_TIME, or CURRENT_TIMESTAMP special registers within a single statement, all values are based on a single clock reading. QUARTER The QUARTER function returns an integer between 1 and 4 that represents the quarter of the year in which the date resides. For example, any dates in January, February, or March will return the integer 1. ROUND_TIMESTAMP The ROUND_TIMESTAMP function returns a timestamp that is the expression rounded to the unit specified by the format-string. If format-string is not specified, expression is rounded to the nearest day, as if 'DD' was specified for format-string. SECOND The SECOND function returns the seconds part of a value. TIME The TIME function returns a time from a value. TIMESTAMP The TIMESTAMP function returns a timestamp from its argument or arguments. TIMESTAMP_FORMAT The TIMESTAMP_FORMAT function returns a timestamp that is based on the interpretation of the input string using the specified format. TIMESTAMP_ISO Returns a timestamp value based on a date, time, or timestamp argument. If the argument is a date, it inserts zero for the time and microseconds part of the timestamp. If the argument is a time, it inserts the value of CURRENT DATE for the date part of the timestamp and zero for the microseconds part of the timestamp. TIMESTAMPDIFF The TIMESTAMPDIFF function returns an estimated number of intervals of the type defined by the first argument, based on the difference between two timestamps. TRUNC_TIMESTAMP The TRUNC_TIMESTAMP function returns a timestamp that is the expression truncated to the unit specified by the format-string. If format-string is not specified, expression is truncated to the nearest day, as if 'DD' was specified for format-string. WEEK The WEEK function returns an integer between 1 and 54 that represents the week of the year. The week starts with Sunday, and January 1 is always in the first week. WEEK_ISO The WEEK_ISO function returns an integer between 1 and 53 that represents the week of the year. The week starts with Monday. Week 1 is the first week of the year to contain a Thursday, which is equivalent to the first week containing January 4. Thus, it is possible to have up to 3 days at the beginning of the year appear as the last week of the previous year or to have up to 3 days at the end of a year appear as the first week of the next year. YEAR The YEAR function returns the year part of a value. Datos Alfanuméricos óptimos CHAR vs VARCHAR • CHAR (50 caracteres o menos) • CHAR o VARCHAR ( 50 – 2048 Caracteres) Ocupación Promedio del campo ? • >70% del tamaño CHAR • <70% del tamaño VARCHAR • Alta Transaccionalidad Favorece CHAR • • VARCHAR (>2K) VARCHAR, VARGRAPHIC Cuando se define una tabla con datos de longitud variable, se debe definir el tamaño del área de ablocamiento. Si el objetivo primario es: • Ahorro de espacio: utilizar ALLOCATE(0). • Rendimiento: Usar una área de ablocamiento con un tamaño suficiente para contener al menos el 90% de los valores de la columna. Uso de LOBs y VARCHAR en la misma tabla Storage for LOB columns allocated in the same manner as VARCHAR columns. When a column stored in the overflow storage area is referenced, currently all of the columns in that area are paged into memory. A reference to a "smaller" VARCHAR column that is in the overflow area can potentially force extra paging of LOB columns. For example, A VARCHAR(256) column retrieved by application has side-effect of paging in two 5 MB BLOB columns that are in the same row. In order to prevent this, you may want to use ALLOCATE keyword to ensure that only LOB columns are stored in the overflow area. Datos Alfanuméricos óptimos CLOBs vs BLOBs vs DATALINKs Usar BLOB / CLOB si: • • • • • El LOB debe ser parte de la base de datos. Modificaciones sobre un LOB deben ser parte de una transacción de Base de Datos. Desea transferir el LOB directamente a una UDF. Necesita salvar la tabla SQL y todos sus datos en un solo paso. Desea usar funciones SQL como SubStr, Concat,… con datos residentes en LOBs. Usar DATALINK si: • • • • • • Es critico el desempeño en operaciones de Lectura. La aplicación No modifica Objetos Desea poder almacenar la Base de datos y los objetos en sistemas diferentes (ej:NAS) Debe trabajar con objetos mayores a 15MB Desea que los datos tipo LOB sean almacenados por fuera de la Base de Datos Desea que la aplicación GUI /WEB maneje la presentación del objeto directamente desde un archivo que no es base de datos. Datos Alfanuméricos óptimos ROWID vs Identity Columns Identity Columns • Solo las columnas de tipo SMALLINT, INTEGER, BIGINT, DECIMAL o NUMERIC pueden ser creadas como columnas de identidad. • Solo se permite UNA columna de identidad por tabla. • Al cambiar la definición de una tabla, solo se puede especificar como Identity Column aquella se esta adicionando, no es posible con alguna de las columnas existentes. ROWID • El uso de ROWID es otra forma de tener un valor único para una columna asignado por el sistema. • ROWID es similar a identity column pero en lugar de ser un atributo de una columna numérica, es un tipo de dato difernte. CREATE TABLE ORDERS (ORDERNO SMALLINT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 500 INCREMENT BY 1 CYCLE), SHIPPED_TO VARCHAR (36) , ORDER_DATE DATE) CREATE TABLE ORDERS (ORDERNO ROWID GENERATED ALWAYS, SHIPPED_TO VARCHAR (36) , ORDER_DATE DATE) Datos Alfanuméricos óptimos XML Cuando XML se convirtió en la base para muchas comunicaciones program-to-program, tales como Web services y aplicaciones tipo EDI, Los programadores RPG han experimentado dificultades para analizar XML (Parsing) incluso con las funciones ampliadas de búsqueda y manejo de cadenas de caracteres del RPG IV. XML Toolkit for iSeries (5733XT1) • Permite a los programas ILE RPG crear nuevos documentos XML y hacer análisis “parsing” sobre aquellos existentes. • Puede utilizar XML tanto como repositorio de almacenamiento (Datastore) o mecanismo de I/O. Analisis Nativo de XML para RPG IV XML-INTO • Permite leer el contenido de un documento XML directamente en una variable RPG. • Esto es útil si conoce el formato del documento XML y sabe que el nombre de los elementos XML en el documento es el mismo que el de las variables dadas a las variables RPG. XML-SAX • Permite especificar un subprocidimiento para manejo de eventos para poder atender cualquier evento generado por el analizador de XML • Esto es útil si NO se conoce a priori el contenido de un documento XML IBM i GLOBALIZACIÓN IBM Globalización La estrategia de globalización de IBM CORP. es UNICODE para la representación de texto. Aún se encuentran el la Web, en los sistemas y bases de datos conectados a la web Sets de caracteres codificados NO-Unicode. Universo de todos los caracteres existentes Scripts Símbolos Notaciones ... Selección Esquema de Set de Caracteres codificación Set de Caracteres codificados Funciones de Control Set de Caracteres Una colección de elementos usada para representar información textual. Un Set de Caracteres ò “Character Set” normalmente soporta mas de un Idioma Set de Caracteres 697 Página de Código 284 Latin America, Spain Define un subconjunto de caracteres de un Character Set. A cada carácter se le asigna una representación numérica. (Hex code) IBM i Globalización CCSID IBM i esta diseñado para soportar la cultura y lenguajes de muchos paises alrededor del mundo. IBM i CCSID Los CCSID son usados para definir un método de asignación, conservación del significado y interpretación de caracteres a través de varios estados de procesamiento e intercambio de datos. IBM i tiene un robusto soporte de CCSID mediante el sistema operativo. SBCS vs DBCS SBCS • EBCDIC • Cada CCSID puede almacenar x’00’ … x’FF’ = 256 Caracteres DBCS • EBCDIC • Cada CCSID puede almacenar x’0000’ … x’FFFF’ = 65536 Caracteres • Códigos de Asia-Pacifico únicamente • Chino (Simplificado y Tradicional) • Japonés • Coreano Limites Un CCSID por Sesión de Trabajo Un CCSID por Columna de Base de Datos Consideraciones del CCSID CCSID 65535 • • • • • NO utilizar CCSID 65535 en aplicaciones multi-idioma 65535 significa NO traducción Desactiva automáticamente la conversión Mantiene el mismo Code Point a través de múltiples Code Pages 65535 es ¿ aceptable ? si la aplicación solo soporta 1 idioma nacional. Escalamiento CCSID Se utiliza el CCSID del Job , si este fue asignado. Si el CCSID del Job es *USRPRF, se verifica el perfil de usuario. Se utiliza el CCSID del Perfil de Usuario , si este fue asignado. Si el CCSID del Perfil de usuario es *SYSVAL, se verifica el valor del sistema QCCSID. • Si QCCSID es 65535, se verifica el valor del sistema QLANGUAGE. • Si se ha definido ID de Lenguaje, se utiliza el valor QTQ_DEFAULT_CCSID, de lo contrario el ID de lenguaje se convierte a un CCSID. • • • • IBM i Globalización unicode IBM i & Unicode® Unicode es un componente clave para las aplicaciones modernas globales. ¿Qué es Unicode? Unicode proporciona un número único para cada carácter, sin importar la plataforma, sin importar el programa, sin importar el idioma. Set de caracteres Único Contiene caracteres de todos los lenguajes Un numero UNICO para cada carácter Tiene tablas de conversión para todos los sets de caracteres Unicode - Endian Formatos de archivo comunes y su tipo de “endian” BIG ENDIAN The way people always broke their eggs in the Lilliput Land LITTLE ENDIAN The way the King then Big Endian ordered the people to • Adobe Photoshop -- Big Endian broke their eggs • IMG (GEM Raster) -- Big Endian • JPEG -- Big Endian • MacPaint -- Big Endian • SGI (Silicon Graphics) -- Big Endian • Sun Raster -- Big Endian • WPG (WordPerfect Graphics Metafile) -- Big Endian Little Endian Intel, IBM Power(Linux) • • • • • • • BMP (Windows and OS/2 Bitmaps) -- Little Endian GIF -- Little Endian FLI (Autodesk Animator) -- Little Endian PCX (PC Paintbrush) -- Little Endian QTM (Quicktime Movies) -- Little Endian Microsoft RTF (Rich Text Format) -- Little Endian TGA (Targa) -- Little Endian Ambos IBM Power (i, AIX, Linux), Z • TIFF -- Both, Endian identifier encoded into file • XWD (X Window Dump) -- Both, Endian identifier encoded into file • Microsoft RIFF (.WAV & .AVI) – Both • DXF (AutoCad) – Variable Unicode – Codificación • Primera versión de unicode 2Bytes / Char 65535 caracteres • Versión 2 Multibyte > 1 millón de caracteres • Unicode o Universal Character Set (UCS-2) soporta 3 formatos ampliamente aceptados de Unicode Transformation Format (UTF’s) • UTF-8 • No Endian • WEB • Multibyte • UTF-16 (default) • Big Endian • Soporte de Lenguajes de Programación en IBM i • UTF-32 • No existe soporte en IBM i Unicode – Software Habilitado • Software habilitado para Unicode • WebSphere • Lotus Domino • DB2 • IFS • Web Browsers • XML • Java • SAP • JDE Enterprise One • Componentes de IBM i NO habilitados para Unicode • QSYS Library System • IBM i Messages Files • Personal Communication / Client Access Unicode & RPG DRPG_CHAR 10A SBCS Only El tipo de datos A solo trabaja con SBCS. Cada carácter utiliza un byte de memoria y ello limita a un máximo de 256 posibles valores. DRPG_ASIAN 10G DBCS Only Muchos lenguajes, especialmente los Orientales, tienen mas de 256 letras en sus alfabetos; cada carácter del tipo de datos G ocupa dos bytes de memoria, permitiendo hasta 65535 posibles valores. DRPG_UNICODE 10C Default: CCSID 13488 Unicode D CCSID(*UCS2 : 1200) If CCSID 1200 is required El tipo de datos C es utilizado para almacenar el subset UCS-2 de UNICODE. Su objetivo es ser capaz de almacenar todos los posibles caracteres presentes alrededor del mundo tanto de byte sencillo como doble. Ejemplo Unicode CREATE TABLE I71_DB2/DATAUNI ( CHAR_284 CHAR ( 10) CCSID 284 NOT NULL WITH DEFAULT, UCS2_FLD GRAPHIC ( 10) CCSID 1200 NOT NULL WITH DEFAULT, CHAR_037 CHAR ( 10) CCSID 37 NOT NULL WITH DEFAULT, VARC_FLD VARCHAR ( 20) ALLOCATE(10) NOT NULL WITH DEFAULT, CHAR_UTF8 CHAR ( 10) CCSID 1208 NOT NULL WITH DEFAULT) insert into I71_DB2/DATAUNI values('Hola Mundo', 'Hola Mundo' , 'Hola Mundo', 'Hola Mundo', 'Hola Mundo') insert into I71_DB2/DATAUNI values('truncado12', 'truncado12' , 'truncado12', 'truncado12345', 'truncado12') insert into I71_DB2/DATAUNI values('ñññ vs ###', 'ñññ vs ###' , 'ñññ vs ###', 'ñññ vs ###', 'ññ vs #') select * from i71_db2/datauni ....+....1 CHAR_284 Hola Mundo ñññ vs ### truncado12 ....+....2 UCS2_FLD Hola Mundo ñññ vs ### truncado12 ....+....3 CHAR_037 Hola Mundo ñññ vs ### truncado12 ....+....4....+....5 VARC_FLD Hola Mundo ñññ vs ### truncado12345 ....+....6 CHAR_UTF8 Hola Mund0 ññ vs # truncado12 CCSID en SQL vs CCSID en Job CHGJOB CCSID(284) CHAR_284 UCS2_FLD CHAR_037 VARC_FLD CHAR_UTF8 *...+....1....+....2....+....3....+....4....+....5....+....6....+....7.. Hola Mundo■ç■?■%■/■■■(■Í■>■À■?Hola Mundo Hola Mundo ç?%/■(Í>À? C9984DA98904060606020407060606C9984DA98900C9984DA98944444444444666247666 8631044546080F0C01000D050E040F86310445460A863104454600000000008FC10D5E4F Truncado12■È■Ê■Í■>■Ä■/■À■?■■■■Truncado12 truncado12345 ÈÊÍ>Ä/À?■■ A9A98889FF07070706060606060303A9A98889FF00A9A98889FFFFF44444447776666633 39453146120402050E0301040F010239453146120D39453146123450000000425E314F12 ñññ vs ###■w■w■w■■■Î■Ë■■■J■J■J¦¦¦ vs ÑÑÑ ñññ vs ### BwBw■ÎË■Cj 4444AA47770A0A0A020707020D0D0D6664AA4666004444AA47774444444444CACA2772C9 9990520BBB06060600060300010101AAA05209990A9990520BBB00000000002626063031 CHGJOB CCSID(037) *...+....1....+....2....+....3....+....4....+....5....+....6....+....7.. ¦¦¦ vs ÑÑÑ■1■1■1■■■Î■Ë■■■■■■■■ñññ vs ### ¦¦¦ vs ÑÑÑ C£C£■ÎË■■■ 6664AA46660F0F0F020707020202024444AA4777006664AA46664444444444CBCB277222 AAA0520999010101000603000303039990520BBB0AAAA052099900000000003131063033 HIGH-LEVEL PROGRAMMING LANGUAGES CONTROL LANGUAGE (CL) CL Programming • IBM i 7.1 – – – – Nuevos comandos de “workload capping” Soporte de recuperar fuente CL para ILE CL Variables Integer mas grandes para ILE CL Soporte de INCLUDE anidado • IBM i 6.1 – Comando Close Database File (CLOSE) – Comando Include CL Source (INCLUDE) • i5/OS V5R4 – Comando CALLSUBR – Variables tipo Pointer Workload Capping La función de grupos de Carga “workload groups” puede ser usada para limitar la capacidad de procesamiento de una carga de trabajo a un subconjunto de núcleos de procesador en una LPAR. LPAR NO Capping LPAR Workload Capping WEBQUERY 4 CORE WEBQUERY 2 CORE ODBC_JDBC 4 CORE ODBC_JDBC 2 CORE QINTER 4 CORE QINTER 1 CORE QBATCH 4 CORE QBATCH 3 CORE 1. Adicionar el grupo de carga usando el comando Add Workload Group (ADDWLCGRP) 2. Crear una área de datos especial llamada QWTWLCGRP que define cuales subsistemas utilizan que grupo de carga. Comando Create Data Area (CRTDTAARA). 3. Usar el comando Display Data Area (DSPDTAARA) para verificar que se utiliza el numero correcto de espacios. 4. Arrancar los subsistemas definidos en el área de datos. Comando Start Subsystem (STRSBS) command. /* Programa de Ejemplo PGM PARM(&VALOR1C &OPER &VALOR2C) DCL DCL DCL DCL DCL DCL DCL DCL VAR(&VALOR1C) TYPE(*CHAR) LEN(10) VAR(&OPER) TYPE(*CHAR) LEN(1) VAR(&VALOR2C) TYPE(*CHAR) LEN(10) VAR(&MSG) TYPE(*CHAR) LEN(80) VAR(&VALOR1D) TYPE(*INT) VALUE(0) VAR(&VALOR2D) TYPE(*INT) VALUE(0) VAR(&VALTEMP) TYPE(*INT) VALUE(0) VAR(&VALTEMC) TYPE(*CHAR) LEN(10) + VALUE('0000000000’) CHGVAR CHGVAR VAR(&VALOR1D) VALUE(&VALOR1C) VAR(&VALOR2D) VALUE(&VALOR2C) SELECT WHEN CL: Include */ INTEGER WORKFLOW COND(&OPER *EQ '+') THEN(CHGVAR + VAR(&VALTEMP) VALUE(&VALOR1D + &VALOR2D)) WHEN COND(&OPER *EQ '-') THEN(CHGVAR + VAR(&VALTEMP) VALUE(&VALOR1D - &VALOR2D)) WHEN COND(&OPER *EQ '*') THEN(CHGVAR + VAR(&VALTEMP) VALUE(&VALOR1D * &VALOR2D)) WHEN COND(&OPER *EQ '/' *AND &VALOR2D *NE 0) + THEN(CHGVAR VAR(&VALTEMP) VALUE(&VALOR1D + /* ***************************************** */ / &VALOR2D)) /* Ejercicio Subrutina con Include */ OTHERWISE CMD(CHGVAR VAR(&MSG) VALUE('Operador + Invalido o Intento de division por cero')) /* Subrutina que presenta el + ENDSELECT mensaje de salida */ SUBR SUBR(MSGESCAPE)+ CHGVAR VAR(&VALTEMC) VALUE(&VALTEMP) SNDPGMMSG MSGID(CPF9898) MSGF(QCPFMSG) + IF COND(&VALTEMC *NE '0000000000') THEN(DO) MSGDTA('Mensaje..: ' *BCAT &MSG) CHGVAR VAR(&MSG) VALUE(&VALOR1C *BCAT &OPER *BCAT + ENDSUBR &VALOR2C *BCAT '=' *BCAT &VALTEMC) /* ***************************************** */ ENDDO /* LLama Subrutina de Mensaje */ CALLSUBR SUBR(MSGESCAPE) INCLUDE SRCMBR(CLINCLUDE) SRCFILE(I71_RPG/QCLSRC) INCLUDE JAVA IBM JVM mejora el rendimiento de Java • IBM 32-bit & 64-bit Java™ Virtual Machine • Tecnología compartida entre AIX, IBM i y Linux • Mejora el rendimiento y la portabilidad • Comando Work with JVM Jobs (WRKJVMJOB) • Ambiente Java excepcional y de alto rendimiento. Construido por IBM para Power Systems • Totalmente compatible con otras aplicaciones Java estándar de la industria. • Puede ser llamado por APIs o directamente desde otros lenguajes. • Extension de Criptografia por Hardware para Java • IBM Java ToolBox para IBM i • Clases de Java pre-codificadas para acceder a elementos y capacidades nativas de IBM i. Ej: Archivos, Colas de datos, Seguridad. • Soporte de JDBC 4.1, XML Data type, Array Type, Nombres de schema largos. https://www.ibm.com/developerworks/ibmi/techupdates/java http://pic.dhe.ibm.com/infocenter/iseries/v7r1m0/index.jsp?topic=%2Frzahh%2Fpage1.htm Múltiples JDK en una LPAR Ubicaciones Options Opc 8 JDK IBM Technology for Java 5.0 32bit JAVA_HOME: /QOpenSys/QIBM/ProdData/JavaVM/jdk50/32bit Opc 9 IBM Technology for Java 5.0 64bit JAVA_HOME: /QOpenSys/QIBM/ProdData/JavaVM/jdk50/64bit Opc 11 IBM Technology for Java 6.0 32bit JAVA_HOME: /QOpenSys/QIBM/ProdData/JavaVM/jdk60/32bit IBM Technology for Java 6 2.6 32bit JAVA_HOME: /QOpenSys/QIBM/ProdData/JavaVM/jdk626/32bit Opc 12 IBM Technology for Java 6.0 64bit JAVA_HOME: /QOpenSys/QIBM/ProdData/JavaVM/jdk60/64bit IBM Technology for Java 6 2.6 64bit JAVA_HOME: /QOpenSys/QIBM/ProdData/JavaVM/jdk626/64bit Opc 13 IBM Technology for Java 142 64bit JAVA_HOME: /QOpenSys/QIBM/ProdData/JavaVM/jdk14/64bit Opc 14 IBM Technology for Java 7.0 32bit JAVA_HOME: /QOpenSys/QIBM/ProdData/JavaVM/jdk70/32bit Opc 15 IBM Technology for Java 7.0 64bit JAVA_HOME: /QOpenSys/QIBM/ProdData/JavaVM/jdk70/64bit JTOpen Lite (JTLite) Java Toolbox para entornos móviles • Significativamente mes consumo que el Java toolbox for IBM i • Soporta dispositivos móviles con capacidad de ejecutar un entorno Java • Enfocado en suministrar los elementos de mayor uso: • Base de Datos -- JDBC (SQL) y acceso por registro (DDM) • Integrated File System – open, read, write, delete • Llamada de programas (RPG, COBOL, Programas de Servicio, etc) • Comandos • Informacion del Job • Mensajes e información del mensaje (DSPMSG QSYSOPR) • Estado del disco (WRKDSKSTS) • Información de Objetos (WRKOBJ) • Información de Usuarios y Grupos DYNAMIC PROGRAMMING LANGUAGES PHP RUBY PYTHON GROOVY NETREXX … Múltiples Shells y Lenguajes en IBM i Clojure php .... C++ CL Groovy Ruby awk C Rexx Java Phyton fortran COBOL RPG Bourne C PASE Korn Qshell ILE QCMD Múltiples Shells en IBM i Bourne Shell #!/QOpenSys/usr/bin/bsh num1=1 num2=1 num3=1 echo $num1 while [ $num3 -le 60 ] ; do echo $num2 num3=`expr $num1 + $num2` num1=`expr $num2` num2=`expr $num3` done Serie de Fibonacci 1 1 2 3 5 8 13 21 34 55 … C Shell #!/QOpenSys/usr/bin/csh @ num1 = 1 @ num2 = 1 @ num3 = 1 echo $num1 while ( $num3 <= 60 ) echo $num2 @ num3 = $num1 + $num2 @ num1 = $num2 @ num2 = $num3 end php <?php $num1 = 1; $num2 = 1; $num3 = 1; echo "$num1\n"; while ( $num3 <= 60 ) { echo "$num2\n"; $num3 = $num1 + $num2; $num1 = $num2; $num2 = $num3; } ?> Korn (POSIX) Shell #!/QOpenSys/usr/bin/sh num1=1 #!/QOpenSys/usr/bin/ksh num2=1 num1=1 num3=1 #!/QOpenSys/usr/bin/psh num2=1 echo $num1 num1=1 num3=1 while [[ $num3 -le 60 ]] ; do num2=1 echo $num1 echo $num2 num3=1 while [[ $num3 -le 60 ]] ; do let num3=num1+num2 echo echo$num1 $num2 let num1=num2 while [[ $num3 -le 60 ]] ; do let num3=num1+num2 letecho num2=num3 $num2 let num1=num2 donelet num3=num1+num2 let num2=num3 let num1=num2 done let num2=num3 done QShell #!/usr/bin/qsh num1=1 num2=1 num3=1 echo $num1 while [[ $num3 -le 60 ]] ; do echo $num2 let num3=num1+num2 let num1=num2 let num2=num3 done Lenguajes Dinámicos en IBM i NetRexx Jython jRuby Groovy Java ILE Rexx PASE python Ruby Ruby php Múltiples Lenguajes Dinámicos en IBM i Groovy Rexx num1 = 1 num2 = 1 num3 = 1 SAY num1 DO WHILE num3 <= 60 SAY num2 num3 = num1 + num2 num1 = num2 num2 = num3 END Def num1 = 1 Def num2 = 1 Def num3 = 1 println num1 while ( num3 <= 60 ) { println num2 num3 = num1 + num2 num1 = num2 num2 = num3 } php <?php $num1 = 1; $num2 = 1; $num3 = 1; echo "$num1\n"; while ( $num3 <= 60 ) { echo "$num2\n"; $num3 = $num1 + $num2; $num1 = $num2; $num2 = $num3; } ?> Def list = [0, 1] while ( list.last() <= 60 ){ print "${list.last()}\n" list << list.sum() list = list.tail() } NetRexx rpg IV d num1 s d num2 s d num3 s /free num1 = 1; num2 = 1; num3 = 1; dsply (num1); dow num3 <= 60; dsply (num2); num3 = num1 + num2; num1 = num2; num2 = num3; enddo; *inlr = *on; /end-free Java import java.util.*; public class fibo{ public static void main(String[] args){ int0 num1; 10i int0 num2; 10i int0 num3; 10i } } num1=1; num2=1; num3=1; System.out.print(num1 + "\n"); do{ System.out.print(num2 + "\n"); num3 = num1 + num2; num1 = num2; num2 = num3; }while(num3<=60); Múltiples Lenguajes Dinámicos en IBM i Groovy Rexx num1 = 1 num2 = 1 num3 = 1 SAY num1 DO WHILE num3 <= 60 SAY num2 num3 = num1 + num2 num1 = num2 num2 = num3 END Def num1 = 1 Def num2 = 1 Def num3 = 1 println num1 while ( num3 <= 60 ) { println num2 num3 = num1 + num2 num1 = num2 num2 = num3 } php <?php $num1 = 1; $num2 = 1; $num3 = 1; echo "$num1\n"; while ( $num3 <= 60 ) { echo "$num2\n"; $num3 = $num1 + $num2; $num1 = $num2; $num2 = $num3; } ?> Def list = [0, 1] while ( list.last() <= 60 ){ print "${list.last()}\n" list << list.sum() list = list.tail() } NetRexx rpg IV dcl-s num1 int (10); dcl-s num2 int (10); dcl-s num3 int (10); num1 = 1; num2 = 1; num3 = 1; dsply (num1); dow num3 <= 60; dsply (num2); num3 = num1 + num2; num1 = num2; num2 = num3; enddo; *inlr = *on; Java import java.util.*; public class fibo{ public static void main(String[] args){ int num1; int num2; int num3; num1=1; num2=1; num3=1; System.out.print(num1 + "\n"); do{ System.out.print(num2 + "\n"); num3 = num1 + num2; num1 = num2; num2 = num3; }while(num3<=60); } } QSHELL & PASE Unix Shell Shell, es el término usado para referirse a un intérprete de comandos, el cual consiste en la interfaz de usuario tradicional de los sistemas operativos basados en Unix y similares como GNU/Linux. Bourne shell (bsh) • Escrita por Steve Bourne, cuando estaba en Bell Labs. Se distribuyó por primera vez con la Version 7 Unix, en 1978, y se mejoró con los años. Bourne-Again shell (bash) Se escribió como parte del proyecto GNU para proveerlo de un superconjunto de funcionalidad con la shell Bourne. Almquist shell (ash) • Se escribió como reemplazo de la shell Bourne con licencia BSD. Debian Almquist shell (dash) • Dash es un reemplazo moderno de ash en Debian. Korn shell (ksh) • Escrita por David Korn, mientras estuvo en Bell Labs. • ksh siempre intenta respetar el Shell Language Standard (POSIX 1003.2 : "Shell and Utilities Language Committee"). C shell (csh) • escrita por Bill Joy, mientras estuvo en la University of California, Berkeley. Se distribuyó por primera vez con BSD en 1979. Z shell (zsh) • Considerada como la más completa: es lo más cercano que existe en abarcar un superconjunto de sh, ash, bash, csh, ksh, y tcsh. QShell QShell Qshell es un entorno de mandatos basado en los estándares POSIX y X/Open. Consta de las siguientes partes: • • El intérprete de shell (o qsh) es un programa que lee mandatos de un origen de entrada, interpreta cada mandato y luego ejecuta el mandato utilizando los servicios del sistema operativo. Los programas de utilidad (o mandatos) son programas externos que proporcionan funciones adicionales y pueden ser bastante sencillos o muy complejos. mandatos QShell Sistema Operativo Beneficios Qshell Incluye comandos NO encontrados en QCMD o System i Navigator Amplias capacidades para trabajar con IFS Ejecuta scripts de UNIX con muy pocas o sin modificaciones en IBM i. Soporta programación Multithread. Buen entorno d trabajo para crear aplicaciones Java en IBM i PASE Portable Application Solution Environment PASE PASE para i es un entorno de ejecución integrado para permitir que aplicaciones AIX corran en sistema operativo IBM i. • Soporta ABI (application binary interface) de AIX y provee un amplio subconjunto de capacidades suministradas por las Librerías compartidas de AIX, Shells y Utilidades. • Korn, Bourne, C • Soporta el procesamiento directo de instrucciones de maquina IBM PowerPC®, de tal forma que no tiene los inconvenientes de un ambiente que solo emula la instrucciones de maquina. Ejecución de Aplicaciones en PASE para i: • • • • Pueden ser escritas en C, C++, Fortran, o Assembler de PowerPC Usa el mismo formato binario ejecutable de aplicaciones AIX Usa funciones del sistema de IBM i como File System, Seguridad y Sockets Corre en un JOB de IBM i Qshell vs PASE Qshell vs. PASE Comparison Chart Qshell 5722-SS1 option 30 Free Product ID Cost Location of commands /usr/bin and utilities Available shells A unique ILE port combining Korn and Bourne How to invoke an interactive (terminal) shell QSH or STRQSH How to run a UNIX utility, command, or program from standard IBM i QSH or STRQSH (yes, same as above). Pass program name and arguments as a single parameter. Case-sensitive? No, unless otherwise instructed Character encoding EBCDIC Symbolic links to ILE IBM i programs in QSHELL library (e.g., /usr/bin/ls = /qsys.lib/qshell.pgm/ls.pgm) Implementation of utilities i5/OS PASE 5722-SS1 option 33 Free since V5R2 /QOpenSys/usr/bin Port of AIX with three choices: Korn (-sh, default), Bourne (-bsh), and C (-csh) CALL QP2TERM Runs Korn shell by default. Accepts parameters to run different programs such as the C shell: CALL PGM(QP2term) PARM('/qopensys/usr/bin/csh') CALL QP2SHELL (for new ILE activation group) or CALL QP2SHELL2 (for caller's activation group). Pass program name and arguments as separate parameters. Yes, when utilities run from default location, QOpenSys/usr/bin ASCII AIX binaries “Puede seleccionar IBM i PASE sobre Qshell si el programa que intenta ejecutar ya existe en un entorno UNIX (especialmente AIX) Puede seleccionar Qshell sobre IBM i PASE si el programa necesita alto nivel de integración con APIs de ILE de IBM i.” Walt Madden – IBM Corp. Qshell Ejemplo Frutas.txt Naranjas Manzanas Peras Uvas Bananas Fresas Lab1.qsh print "Digite el nombre de una fruta" read fruta print "Usted selecciono la fruta $fruta" Lab2.qsh if [[ $(grep -c Mangos frutas.txt) -eq 0 ]] then echo NO hay Mangos en el archivo frutas.txt fi Qshell Ejemplo Producción El cliente desea analizar su código fuente. Quiere obtener todas las líneas de programación de todos los miembros de un archivo fuente de una biblioteca que cumplan con uno o varios criterios de busqueda FNDSTRPDM STRING(MOVEA) FILE(I71_RPG/QRPGLESRC) MBR(*ALL) OPTION(*NONE) PRTMBRLIST(*YES) PRTRCDS(*ALL *CHAR) FNDSTRPDM STRING(INZ) FILE(I71_RPG/QRPGLESRC) MBR(*ALL) OPTION(*NONE) PRTMBRLIST(*YES) PRTRCDS(*ALL *CHAR) Qshell Ejemplo Producción DSPFD FILE(I71_RPG/QRPGLESRC) TYPE(*MBRLIST) OUTPUT(*PRINT) shell008.qsh #!/usr/bin/qsh # Genera un archivo con las coincidencias de busqueda en un archivo de fuentes # # $1 = Libreria $2 = Archivo de Fuentes # $3 = Archivo de Salida $4 = criterio de busqueda STDOUT STDIN STDOUT # system "DSPFD FILE($1/$2) TYPE(*MBRLIST)" | awk008.awk | \ while read line STDIN STDOUT STDIN do system "RUNQRY QRY(*NONE) QRYFILE(($1/$2 $line))" | \ awk -v MBR=$line '/'$4'/ { printf("%-10s^%s\n", MBR, $0) }' >>$3 OUT done #!/QOpenSys/usr/bin/awk -f awk008.awk BEGIN { x=0 } { if ( $1 == "Member" && $2 == "Size") { x=1 } else { if ( $0 ~ /Total number of members ./) { x=0 } } if ( x == 1 && $1 != "Text:" && $1 != "Member" && NF == 8) { print $1 } } #!/QOpenSys/usr/bin/awk -f BEGIN { x=0 } { if ( $1 == "Member" && $2 == "Size") { x=1 } else { if ( $0 ~ /Total number of members ./) { x=0 } } if ( x == 1 && $1 != "Text:" && $1 != "Member" && NF == 8) { print $1 } } Ejecucion shell008.qsh QSH shell008.qsh i71_rpg cat aa.txt qrpglesrc aa.txt Miembro fuente Separador ^ Numero de Linea Fecha edicion cat aa.txt | rfile –wQ qsys/qsysprt movea|inz Gracias !! Octavio Bustos [email protected] 571 6351270 www.redsis.com