Search in sources :

Example 6 with Record

use of com.ibm.as400.access.Record in project IBMiProgTool by vzupka.

the class WrkSplF method convertSpooledFile.

/**
 * Read input stream and convert byte array buffers to text file (SpooledFile.txt) and to text area (spoolTextArea).
 *
 * @param splf
 * @return
 */
@SuppressWarnings("ConvertToTryWithResources")
protected String convertSpooledFile(SpooledFile splf) {
    /* String splfFileNumberChar = String.valueOf(splf.getNumber()); System.out.print("File name convertSpooledfile: "
       * + splf.getName()); System.out.print(" \tFile number: " + splfFileNumberChar); System.out.print(" \tJob name: "
       * + splf.getJobName()); System.out.print(" \tUser name: " + splf.getJobUser());
       * System.out.print(" \tJob number: " + splf.getJobNumber()); System.out.print(" \tDate: " +
       * splf.getCreateDate()); System.out.print(" \tTime: " + splf.getCreateTime()); System.out.println(); */
    try {
        Integer numberParInt = splf.getNumber();
        PrintParameterList printParameterList = new PrintParameterList();
        printParameterList.setParameter(SpooledFile.ATTR_SPOOLFILE, namePar);
        printParameterList.setParameter(SpooledFile.ATTR_SPLFNUM, numberParInt);
        printParameterList.setParameter(SpooledFile.ATTR_JOBNAME, jobPar);
        printParameterList.setParameter(SpooledFile.ATTR_JOBUSER, userPar);
        printParameterList.setParameter(SpooledFile.ATTR_JOBNUMBER, jobNumberPar);
        printParameterList.setParameter(SpooledFile.ATTR_DATE, datePar);
        printParameterList.setParameter(SpooledFile.ATTR_TIME, timePar);
        InputStream inputStream = splf.getInputStream(printParameterList);
        // Open output text file
        BufferedWriter outfileText = Files.newBufferedWriter(spoolTextPath, Charset.forName(pcCharset), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
        // Create empty text area for converted lines
        spoolTextArea = new JTextArea();
        byte[] workBuffer = new byte[2000000];
        byte[] inputBuffer = new byte[20000];
        final int SINGLE_CHARACTERS = 10;
        final int CLASS = 15;
        final int COMMAND_CLASSES = 20;
        final int PRESENTATION_POSITION = 30;
        final int TRANSPARENT = 40;
        final int VERTICAL_CHANNEL_SELECT = 50;
        final int RVPP = 80;
        final int AHPP = 90;
        final int AVPP = 100;
        final int RHPP = 110;
        final int NBR_TRANSP_BYTES = 120;
        final int VERTICAL_CHANNEL = 130;
        final int CLASS_COUNTDOWN = 180;
        int endPointer = 0;
        int classCount = 0;
        int machineState = SINGLE_CHARACTERS;
        int bytesRead = inputStream.read(inputBuffer);
        int currentPosInLine = 0;
        // End position in line for continuation when replacing mode ends
        int resumePosInLine = 0;
        boolean isReplacingPrecedingBytes = false;
        while (bytesRead != -1) {
            for (int idx = 0; idx < bytesRead; idx++) {
                byte byteRead = inputBuffer[idx];
                // --------------------------------------------------------------------------------------
                switch(machineState) {
                    case SINGLE_CHARACTERS:
                        {
                            // Skipped control characters
                            if (// Null
                            byteRead == 0x00 || // ASCII Transparency (ATRN)
                            byteRead == 0x01 || // ?
                            byteRead == 0x02 || // ?
                            byteRead == 0x03 || // Superscript (SPS)
                            byteRead == 0x09 || // Repeat (RPT)
                            byteRead == 0x0A || // Carriage Return (CR)
                            byteRead == 0x0D || // Backspace (BS)
                            byteRead == 0x16 || // Unit Backspace (UBS)
                            byteRead == 0x1A || // Word Underscore (WUS)
                            byteRead == 0x23 || // Switch (SW)
                            byteRead == 0x2A || // Bell/Stop (BEL/STP)
                            byteRead == 0x2F || // Numeric Backspace (NBS)
                            byteRead == 0x36 || // Subscript (SBS)
                            byteRead == 0x38) {
                                // System.out.print(byteToHex(byteRead));
                                break;
                            }
                            // ===================
                            if (// Required New Line (RNL)
                            byteRead == 0x06 || // Vertical Tab (VT)
                            byteRead == 0x0B || // Form Feed (FF)
                            byteRead == 0x0C || // New Line (NL)
                            byteRead == 0x15 || // Interchange Record Separator (IRE)
                            byteRead == 0x1E || // Line Feed/Index (LF/INX)
                            byteRead == 0x25 || // Index Return (IRT)
                            byteRead == 0x33 || // Required Form Feed/Required Page End (RFF/RFE)
                            byteRead == 0x3A) {
                                // - set pointer to the resume position.
                                if (isReplacingPrecedingBytes) {
                                    // Set pointer to resume position in line
                                    endPointer = endPointer + resumePosInLine - currentPosInLine;
                                    // End replacing mode
                                    isReplacingPrecedingBytes = false;
                                }
                                // Interpreted by CR and LF - Carriage Return and Line Feed
                                // CR
                                workBuffer[endPointer] = 0x0d;
                                endPointer++;
                                // LF
                                workBuffer[endPointer] = 0x25;
                                endPointer++;
                                currentPosInLine = 0;
                                break;
                            }
                            // Presentation position (34)
                            if (byteRead == 0x34) {
                                // System.out.println("Presentation Position command: " + byteToHex(byteRead));
                                machineState = PRESENTATION_POSITION;
                                break;
                            }
                            // Command classes introduced by 2B
                            if (byteRead == 0x2B) {
                                // System.out.println("B2 command classes: " + byteToHex(byteRead));
                                machineState = COMMAND_CLASSES;
                                break;
                            }
                            // --------------------
                            if (byteRead >= 0x40 || byteRead < 0xf9 || // Substitute (SUB)
                            byteRead == 0x3f) {
                                // System.out.print(byteToHex(byteRead));
                                if (byteRead == 0x3f) {
                                    workBuffer[endPointer] = 0x40;
                                } else {
                                    workBuffer[endPointer] = byteRead;
                                }
                                endPointer++;
                                currentPosInLine++;
                                break;
                            }
                            // Horizontal tab (HT)
                            if (// Horizontal Tab (HT)
                            byteRead == 0x05) {
                                // This command is not used by Twinax
                                break;
                            }
                            // Indent tab (IT)
                            if (// Indent tab (IT)
                            byteRead == 0x39) {
                                // This command is not used by Twinax
                                break;
                            }
                            // Transparent (TRN)
                            if (byteRead == 0x35) {
                                // System.out.print("TRN Transparent tab: " + byteToHex(byteRead));
                                // System.out.print(byteToHex(byteRead));
                                machineState = TRANSPARENT;
                                break;
                            }
                            // Vertical Channel Select (VCS)
                            if (byteRead == 0x04) {
                                // System.out.print("VCS Vertical Channel Select: " + byteToHex(byteRead));
                                // System.out.print(byteToHex(byteRead));
                                // Interpreted by CR and LF - Carriage Return and Line Feed
                                // CR
                                workBuffer[endPointer] = 0x0d;
                                endPointer++;
                                // LF
                                workBuffer[endPointer] = 0x25;
                                endPointer++;
                                machineState = VERTICAL_CHANNEL_SELECT;
                                break;
                            }
                            break;
                        }
                    case PRESENTATION_POSITION:
                        {
                            // Cast to *byte* is important because some types are negative numbers!
                            if (// Relative Vertical Presentation Position (RVPP)
                            byteRead == (byte) 0x4c) {
                                machineState = RVPP;
                                break;
                            } else if (// Absolute Horizontal Presentation Position (AHPP)
                            byteRead == (byte) 0xc0) {
                                machineState = AHPP;
                                break;
                            } else if (// Absolute Vertical Presentation Position (AVPP)
                            byteRead == (byte) 0xc4) {
                                machineState = AVPP;
                                break;
                            } else if (// Relative Horizontal Presentation Position (RHPP)
                            byteRead == (byte) 0xc8) {
                                machineState = RHPP;
                                break;
                            } else {
                            // System.out.println("Invalid Presentation position type: " + byteToHex(byteRead));
                            }
                            break;
                        }
                    case RVPP:
                        {
                            // Insert (count - 1) new lines
                            for (int cnt = 0; cnt < byteRead - 1; cnt++) {
                                // Interpreted by CR and LF - Carriage Return and Line Feed
                                // CR
                                workBuffer[endPointer] = 0x0d;
                                endPointer++;
                                // LF
                                workBuffer[endPointer] = 0x25;
                                endPointer++;
                            }
                            machineState = SINGLE_CHARACTERS;
                            break;
                        }
                    case AHPP:
                        {
                            // - insert new line and reset the last position in line to zero (start of line)
                            if (unsignedByteToInt(byteRead) < currentPosInLine) {
                                // Begin replacing mode in which already written bytes in the work buffer
                                // are being replaced by new bytes read from input.
                                isReplacingPrecedingBytes = true;
                                // Remember the current position in the line as a new beginning for adding bytes
                                // after the replacing mode ends.
                                resumePosInLine = currentPosInLine;
                                // Set pointer back to the work buffer where already written text in the line began
                                endPointer = endPointer - currentPosInLine + byteRead - 1;
                                // Set new last posiion in line to the first presentation position in the line
                                currentPosInLine = byteRead;
                            } else {
                                // Add RELATIVE number of spaces (absolute presentation position - currentPosInLine)
                                int numberOfSpaces = unsignedByteToInt(byteRead) - currentPosInLine - 1;
                                for (int cnt = 0; cnt < numberOfSpaces; cnt++) {
                                    // Insert a space
                                    workBuffer[endPointer] = 0x40;
                                    endPointer++;
                                }
                                // Increment current position in line by the number of added spaces
                                currentPosInLine += numberOfSpaces;
                            }
                            machineState = SINGLE_CHARACTERS;
                            break;
                        }
                    case AVPP:
                        {
                            // because the count is usually 01
                            for (int cnt = 0; cnt < byteRead + 2; cnt++) {
                                // Interpreted by CR and LF - Carriage Return and Line Feed
                                // CR
                                workBuffer[endPointer] = 0x0d;
                                endPointer++;
                                // LF
                                workBuffer[endPointer] = 0x25;
                                endPointer++;
                            }
                            machineState = SINGLE_CHARACTERS;
                            break;
                        }
                    case RHPP:
                        {
                            // Insert (count -1) spaces (assume that RHPP is a positive number)
                            for (int cnt = 0; cnt < byteRead - 1; cnt++) {
                                // Interpret by inserting a space
                                workBuffer[endPointer] = 0x40;
                                endPointer++;
                            }
                            machineState = SINGLE_CHARACTERS;
                            break;
                        }
                    case TRANSPARENT:
                        {
                            // System.out.print(byteToHex(byteRead));
                            // Next byte will be skipped - number of bytes following this command
                            // not to be checked for printed datastream commands
                            machineState = NBR_TRANSP_BYTES;
                            break;
                        }
                    case NBR_TRANSP_BYTES:
                        {
                            // System.out.print(byteToHex(byteRead));
                            // No operation will be done (but machineState changed)
                            machineState = SINGLE_CHARACTERS;
                            break;
                        }
                    case VERTICAL_CHANNEL_SELECT:
                        {
                            // System.out.print(byteToHex(byteRead));
                            machineState = VERTICAL_CHANNEL;
                            break;
                        }
                    case VERTICAL_CHANNEL:
                        {
                            // System.out.print(byteToHex(byteRead));
                            // Vertical channel ID
                            // X'7A' = 10
                            // X'7B' = 11
                            // X'7C' = 12
                            // X'81' = 1
                            // X'82' = 2
                            // X'83' = 3
                            // X'84' = 4
                            // X'85' = 5
                            // X'86' = 6
                            // X'87' = 7
                            // X'88' = 8
                            // X'89' = 9
                            // Interpreted by CR and LF - Carriage Return and Line Feed
                            // CR
                            workBuffer[endPointer] = 0x0d;
                            endPointer++;
                            // LF
                            workBuffer[endPointer] = 0x25;
                            endPointer++;
                            machineState = SINGLE_CHARACTERS;
                            break;
                        }
                    case COMMAND_CLASSES:
                        {
                            // System.out.println("Class: " + byteToHex(byteRead));
                            // hexLine += byteToHex(byteRead);
                            machineState = CLASS;
                            break;
                        }
                    case CLASS:
                        {
                            // System.out.print(byteToHex(byteRead));
                            // This byte is the number (count) of this and following bytes.
                            // Save the count for later comparison.
                            classCount = byteRead;
                            // System.out.println("Class count = " + classCount);
                            machineState = CLASS_COUNTDOWN;
                            break;
                        }
                    case CLASS_COUNTDOWN:
                        {
                            // System.out.print(byteToHex(byteRead));
                            // Decrement class count and compare if greater than zero
                            classCount--;
                            if (classCount > 0) {
                                // System.out.println("Class count = " + classCount);
                                machineState = CLASS_COUNTDOWN;
                            } else {
                                // System.out.println("Class Countdown 0");
                                machineState = SINGLE_CHARACTERS;
                            }
                            break;
                        }
                    default:
                        {
                        // System.out.println("\nUNKNOWN CONTROL CHARACTER! " + byteToHex(byteRead));
                        }
                }
            // end switch
            // This is the end of the state machine
            }
            // end for
            // System.out.println("\n FIRST BYTE: " + byteToHex(inputBuffer[0]));
            // Copy the printable part of the work array (up to *endPointer* position)
            // to a new buffer that will be written out.
            byte[] bufferToWrite = new byte[endPointer];
            // Copy bytes from the work buffer to the new buffer
            for (int indx = 0; indx < endPointer; indx++) {
                bufferToWrite[indx] = workBuffer[indx];
            }
            // Create object for conversion from bytes to characters
            AS400Text textConverter = new AS400Text(endPointer, ibmCcsidInt, remoteServer);
            // int CCSID = textConverter.getCcsid();
            // System.out.println(" CCSID: " + CCSID);
            // Convert byte array buffer to text line
            String textLine = (String) textConverter.toObject(bufferToWrite);
            // System.out.println(textLine);
            // Write text line to the text file
            outfileText.write(textLine);
            // Write text line to text area
            spoolTextArea.append(textLine);
            // Read next input buffer
            bytesRead = inputStream.read(inputBuffer);
            // Reset pointer in work buffer so it points to the beginning
            endPointer = 0;
        }
        // Close files
        inputStream.close();
        outfileText.close();
        row = "Info: Spooled file characters were converted using CCSID  " + ibmCcsid + ".";
        mainWindow.msgVector.add(row);
        // do not add child nodes
        mainWindow.showMessages(noNodes);
        mainWindow.scrollMessagePane.getVerticalScrollBar().removeAdjustmentListener(mainWindow.messageScrollPaneAdjustmentListenerMax);
        return spoolTextArea.getText();
    } catch (Exception exc) {
        System.out.println("Error: " + exc.toString());
        exc.printStackTrace();
        row = "Error: Spooled file CCSID   '" + ibmCcsid + "'   or  text file character set   '" + pcCharset + "'   is not correct.  -  " + exc.toString();
        mainWindow.msgVector.add(row);
        row = "Set \"IBM i CCSID\" to 65535 and press button \"Spooled file\" to display the spooled file again.";
        mainWindow.msgVector.add(row);
        // do not add child nodes
        mainWindow.showMessages(noNodes);
        mainWindow.scrollMessagePane.getVerticalScrollBar().removeAdjustmentListener(mainWindow.messageScrollPaneAdjustmentListenerMax);
        return "ERROR";
    }
}
Also used : JTextArea(javax.swing.JTextArea) AS400Text(com.ibm.as400.access.AS400Text) PrintObjectTransformedInputStream(com.ibm.as400.access.PrintObjectTransformedInputStream) InputStream(java.io.InputStream) PrintParameterList(com.ibm.as400.access.PrintParameterList) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) BufferedWriter(java.io.BufferedWriter)

Example 7 with Record

use of com.ibm.as400.access.Record in project IBMiProgTool by vzupka.

the class DisplayFile method displaySourceMember.

/**
 * Display source member using its CCSID attribute; Only data part of the source record is translated (to String -
 * UTF-16).
 *
 * @param remoteServer
 * @param as400PathString
 */
protected void displaySourceMember(AS400 remoteServer, String as400PathString) {
    this.setTitle("Display member  '" + as400PathString + "'");
    IFSFile ifsFile = new IFSFile(remoteServer, as400PathString);
    // Create an AS400FileRecordDescription object that represents the file
    AS400FileRecordDescription inRecDesc = new AS400FileRecordDescription(remoteServer, as400PathString);
    try {
        // Decide what CCSID is appropriate for displaying the member
        int ccsidAttribute = ifsFile.getCCSID();
        characterSetLabel.setText("CCSID " + ccsidAttribute + " was used for display.");
        // Get list of record formats of the database file
        RecordFormat[] format = inRecDesc.retrieveRecordFormat();
        // Create an AS400File object that represents the file
        SequentialFile as400seqFile = new SequentialFile(remoteServer, as400PathString);
        // Set the record format (the only one)
        as400seqFile.setRecordFormat(format[0]);
        // Open the source physical file member as a sequential file
        as400seqFile.open(AS400File.READ_ONLY, 0, AS400File.COMMIT_LOCK_LEVEL_NONE);
        // Read the first source member record
        Record inRecord = as400seqFile.readNext();
        // --------------------
        while (inRecord != null) {
            StringBuilder textLine = new StringBuilder();
            // Source record is composed of three source record fields: seq.
            // number, date, source data.
            DecimalFormat df1 = new DecimalFormat("0000.00");
            DecimalFormat df2 = new DecimalFormat("000000");
            // Sequence number - 6 bytes
            String seq = df1.format((Number) inRecord.getField("SRCSEQ"));
            String seq2 = seq.substring(0, 4) + seq.substring(5);
            textLine.append(seq2);
            // Date - 6 bytes
            String srcDat = df2.format((Number) inRecord.getField("SRCDAT"));
            // textLine.append(srcDat);
            textLine.append(srcDat);
            // Data from source record (the source line)
            byte[] bytes = inRecord.getFieldAsBytes("SRCDTA");
            // Create object for conversion from bytes to characters
            // Ignore "IBM i CCSID" parameter - display characters in the
            // member.
            AS400Text textConverter = new AS400Text(bytes.length, remoteServer);
            // Convert byte array buffer to text line (String - UTF-16)
            String translatedData = (String) textConverter.toObject(bytes);
            // Append translated data to text line
            textLine.append(translatedData).append(NEW_LINE);
            // Append text line to text area
            textArea.append(textLine.toString());
            // Read next source member record
            inRecord = as400seqFile.readNext();
        }
        // Close the file
        as400seqFile.close();
        // Set scroll bar to top
        textArea.setCaretPosition(0);
        // Display the window.
        setVisible(true);
        row = "Info: Source member  " + as400PathString + "  has CCSID  " + ccsidAttribute + ".";
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(nodes);
    } catch (Exception exc) {
        exc.printStackTrace();
        row = "Error: " + exc.toString();
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(nodes);
    }
    // Remove message scroll listener (cancel scrolling to the last message)
    mainWindow.scrollMessagePane.getVerticalScrollBar().removeAdjustmentListener(mainWindow.messageScrollPaneAdjustmentListenerMax);
}
Also used : SequentialFile(com.ibm.as400.access.SequentialFile) RecordFormat(com.ibm.as400.access.RecordFormat) DecimalFormat(java.text.DecimalFormat) Point(java.awt.Point) PatternSyntaxException(java.util.regex.PatternSyntaxException) BadLocationException(javax.swing.text.BadLocationException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) AS400FileRecordDescription(com.ibm.as400.access.AS400FileRecordDescription) AS400Text(com.ibm.as400.access.AS400Text) Record(com.ibm.as400.access.Record) IFSFile(com.ibm.as400.access.IFSFile)

Example 8 with Record

use of com.ibm.as400.access.Record in project IBMiProgTool by vzupka.

the class EditFile method displaySourceMember.

protected void displaySourceMember() {
    this.setTitle("Edit member  '" + filePathString + "'");
    // Extract individual names (libraryName, fileName, memberName) from the AS400 IFS path
    extractNamesFromIfsPath(filePathString);
    IFSFile ifsFile = new IFSFile(remoteServer, filePathString);
    // Create an AS400FileRecordDescription object that represents the file
    AS400FileRecordDescription inRecDesc = new AS400FileRecordDescription(remoteServer, filePathString);
    // Set editability
    textArea.setEditable(true);
    textArea.setText("");
    try {
        ccsidAttribute = ifsFile.getCCSID();
        characterSetLabel.setText("CCSID " + ccsidAttribute + " was used for display.");
        // Get list of record formats of the database file
        RecordFormat[] format = inRecDesc.retrieveRecordFormat();
        // Create an AS400File object that represents the file
        SequentialFile as400seqFile = new SequentialFile(remoteServer, filePathString);
        // Set the record format (the only one)
        as400seqFile.setRecordFormat(format[0]);
        // Open the source physical file member as a sequential file
        as400seqFile.open(AS400File.READ_ONLY, 0, AS400File.COMMIT_LOCK_LEVEL_NONE);
        // Read the first source member record
        Record inRecord = as400seqFile.readNext();
        // --------------------
        while (inRecord != null) {
            StringBuilder textLine = new StringBuilder();
            // Prefix is not displayed because it must not be edited!!!
            // Source record is composed of three source record fields: seq.
            // number, date, source data.
            // -- DecimalFormat df1 = new DecimalFormat("0000.00");
            // -- DecimalFormat df2 = new DecimalFormat("000000");
            // Sequence number - 6 bytes String seq = df1.format((Number)
            // --inRecord.getField("SRCSEQ"));
            // String seq2 = seq.substring(0, 4) + seq.substring(5);
            // Date - 6 bytes
            // --String srcDat = df2.format((Number)
            // inRecord.getField("SRCDAT"));
            // Data from source record (the source line)
            byte[] bytes = inRecord.getFieldAsBytes("SRCDTA");
            // Create object for conversion from bytes to characters
            // Ignore "IBM i CCSID" parameter - display characters in the
            // member.
            AS400Text textConverter = new AS400Text(bytes.length, remoteServer);
            // Convert byte array buffer to text line (String - UTF-16)
            String translatedData = (String) textConverter.toObject(bytes);
            // Append translated data to text line
            textLine.append(translatedData).append(NEW_LINE);
            // Append text line to text area
            textArea.append(textLine.toString());
            // Read next source member record
            inRecord = as400seqFile.readNext();
        }
        // Close the file
        as400seqFile.close();
    } catch (Exception exc) {
        isError = true;
        exc.printStackTrace();
        row = "Error in displaying source member: " + exc.toString();
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(nodes);
    }
    // Remove message scroll listener (cancel scrolling to the last message)
    mainWindow.scrollMessagePane.getVerticalScrollBar().removeAdjustmentListener(mainWindow.messageScrollPaneAdjustmentListenerMax);
}
Also used : SequentialFile(com.ibm.as400.access.SequentialFile) AS400Text(com.ibm.as400.access.AS400Text) RecordFormat(com.ibm.as400.access.RecordFormat) Record(com.ibm.as400.access.Record) CannotUndoException(javax.swing.undo.CannotUndoException) CannotRedoException(javax.swing.undo.CannotRedoException) BadLocationException(javax.swing.text.BadLocationException) IFSFile(com.ibm.as400.access.IFSFile) AS400FileRecordDescription(com.ibm.as400.access.AS400FileRecordDescription)

Example 9 with Record

use of com.ibm.as400.access.Record in project IBMiProgTool by vzupka.

the class EditFile method rewriteSourceMemberDirect.

/**
 * Rewrite source member with edited text area directly, without intermediate temporary IFS file; Records are
 * written, updated or deleted, with numbers and dates using BigDecimal objects;
 *
 * THIS METHOD IS NOT USED because it is very slow.
 *
 * @return
 */
protected String rewriteSourceMemberDirect() {
    // Extract individual names (libraryName, fileName, memberName) from the
    // AS400 IFS path
    extractNamesFromIfsPath(filePathString);
    // Path to the output source member
    String outMemberPathString = "/QSYS.LIB/" + libraryName + ".LIB/" + fileName + ".FILE" + "/" + memberName + ".MBR";
    try {
        Files.delete(tmpFilePath);
        String[] lines = textArea.getText().split("\n");
        // ------------------------------------
        if (!properties.getProperty("OVERWRITE_FILE").equals("Y")) {
            row = "Info: Member  " + libraryName + "/" + fileName + "(" + memberName + ")   cannot be overwtitten. " + " Overwriting files is not allowed.";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "ERROR";
        }
        // Overwrite is allowed
        // --------------------
        // Obtain output database file record description
        AS400FileRecordDescription outRecDesc = new AS400FileRecordDescription(remoteServer, outMemberPathString);
        // Retrieve record format from the record description
        RecordFormat[] format = outRecDesc.retrieveRecordFormat();
        // Obtain output record object
        Record outRecord = new Record(format[0]);
        msgText = "";
        if (lines.length > 0) {
            // Create the member (SequentialFile object)
            outSeqFile = new SequentialFile(remoteServer, outMemberPathString);
            // Set the record format (the only one)
            outSeqFile.setRecordFormat(format[0]);
            try {
                outSeqFile.open(AS400File.READ_WRITE, 100000, AS400File.COMMIT_LOCK_LEVEL_NONE);
            } catch (com.ibm.as400.access.AS400Exception as400exc) {
                as400exc.printStackTrace();
                // Add new member if open could not be performed (when the
                // member does not exist)
                // (the second parameter is a text description)
                // The new member inherits the CCSID from its parent Source
                // physical file
                outSeqFile.addPhysicalFileMember(memberName, "Source member " + memberName);
                // Open the new member
                outSeqFile.open(AS400File.READ_WRITE, 100000, AS400File.COMMIT_LOCK_LEVEL_NONE);
            }
            // Member records contain sequence and data fields
            // -----------------------------------------------
            // Get length of member data field
            int lenDTA = format[0].getFieldDescription("SRCDTA").getLength();
            // Base sequential number - 6 digits
            BigDecimal seqNumber = new BigDecimal("0000.00");
            // Increment to the previous sequential number - 6 digits
            BigDecimal increment = new BigDecimal("0001.00");
            // Get actual date and transform it to YYMMDD
            LocalDate date = LocalDate.now();
            int intYear = date.getYear();
            int intMonth = date.getMonthValue();
            int intDay = date.getDayOfMonth();
            String strYear = String.valueOf(intYear);
            String strMonth = String.valueOf(intMonth);
            if (intMonth < 10) {
                strMonth = "0" + strMonth;
            }
            String strDay = String.valueOf(intDay);
            if (intDay < 10) {
                strDay = "0" + strDay;
            }
            String strSrcDat = strYear.substring(2) + strMonth + strDay;
            String dataLine;
            // Process all lines
            for (int idx = 0; idx < lines.length; idx++) {
                // System.out.println("0'" + lines[idx] + "'");
                if (lines[idx].equals("\n")) {
                    // System.out.println("1'" + lines[idx] + "'");
                    dataLine = " ";
                } else {
                    // System.out.println("2'" + lines[idx] + "'");
                    dataLine = lines[idx].replace("\r", "");
                }
                seqNumber = seqNumber.add(increment);
                // Insert sequential number into the source record (zoned
                // decimal, 2 d.p.)
                outRecord.setField("SRCSEQ", seqNumber);
                // Insert today's date YYMMDD into the source record (zoned
                // decimal, 0 d.p.)
                outRecord.setField("SRCDAT", new BigDecimal(strSrcDat));
                // Adjust data line obtained from the text area - truncate
                // or pad by spaces if necessary
                int dataLength;
                if (dataLine.length() >= lenDTA) {
                    // Shorten the data line to fit the data field in the
                    // record
                    dataLength = lenDTA;
                } else {
                    // Pad the data line with spaces to fit the data field
                    // in the record
                    char[] chpad = new char[lenDTA - dataLine.length()];
                    for (int jdx = 0; jdx < chpad.length; jdx++) {
                        // pad the data line with spaces
                        chpad[jdx] = ' ';
                    }
                    dataLine = dataLine + String.valueOf(chpad);
                    dataLength = lenDTA;
                }
                // Insert data to the member data field
                outRecord.setField("SRCDTA", dataLine.substring(0, dataLength));
                // area
                try {
                    outSeqFile.positionCursor(idx + 1);
                    outSeqFile.update(outRecord);
                } catch (Exception exc) {
                    exc.printStackTrace();
                    row = "Error: 1 Data cannot be written to the source member  " + libraryName + "/" + fileName + "(" + memberName + ")  -  " + exc.toString();
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                    msgText = "ERROR";
                    break;
                }
            }
            // Close file
            outSeqFile.close();
            // Set caret at the beginning of the text area
            textArea.setCaretPosition(0);
            textArea.requestFocus();
            row = "Comp: Source member  " + libraryName + "/" + fileName + "(" + memberName + ")  was saved.";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "";
        }
    } catch (Exception exc) {
        try {
            outSeqFile.close();
        } catch (Exception exce) {
            exce.printStackTrace();
        }
        exc.printStackTrace();
        row = "Error: 3 Data cannot be written to the source member  " + libraryName + "/" + fileName + "(" + memberName + ")  -  " + exc.toString();
        mainWindow.msgVector.add(row);
        mainWindow.showMessages();
        // Must not continue in order not to lock an object
        return "ERROR";
    }
    return "";
}
Also used : SequentialFile(com.ibm.as400.access.SequentialFile) RecordFormat(com.ibm.as400.access.RecordFormat) LocalDate(java.time.LocalDate) Point(java.awt.Point) BigDecimal(java.math.BigDecimal) CannotUndoException(javax.swing.undo.CannotUndoException) CannotRedoException(javax.swing.undo.CannotRedoException) BadLocationException(javax.swing.text.BadLocationException) AS400FileRecordDescription(com.ibm.as400.access.AS400FileRecordDescription) Record(com.ibm.as400.access.Record)

Example 10 with Record

use of com.ibm.as400.access.Record in project IBMiProgTool by vzupka.

the class Copy_IBMi_PC method copyDataFromMemberToFile.

/**
 * Copy data from source member to PC file;
 * If the output PC file does not exist, one is created.
 *
 * @param remoteServer
 * @param as400PathString
 * @param pcPathString
 * @return
 */
@SuppressWarnings("UseSpecificCatch")
protected String copyDataFromMemberToFile(AS400 remoteServer, String as400PathString, String pcPathString) {
    IFSFile ifsFile = new IFSFile(remoteServer, as400PathString);
    // Create an AS400FileRecordDescription object that represents the file
    AS400FileRecordDescription inRecDesc = new AS400FileRecordDescription(remoteServer, as400PathString);
    Path pcFilePath = Paths.get(pcPathString);
    try {
        int ccsidAttribute = ifsFile.getCCSID();
        int ccsidForDisplay = ccsidAttribute;
        // In this case, the universal CCSID 65535 is assumed.
        if (ccsidAttribute == 1208) {
            ccsidForDisplay = 65535;
        }
        if (ibmCcsidInt == 1208) {
            ibmCcsidInt = 65535;
        }
        // Get list of record formats of the database file
        RecordFormat[] format = inRecDesc.retrieveRecordFormat();
        // Create an AS400File object that represents the file
        SequentialFile as400seqFile = new SequentialFile(remoteServer, as400PathString);
        // Set the record format (the only one)
        as400seqFile.setRecordFormat(format[0]);
        // Open the source physical file member as a sequential file
        as400seqFile.open(AS400File.READ_ONLY, 0, AS400File.COMMIT_LOCK_LEVEL_NONE);
        // 
        if (Files.exists(pcFilePath) && !properties.getProperty("OVERWRITE_FILE").equals("Y")) {
            row = "Info: Source member " + libraryName + "/" + fileName + "(" + memberName + ") cannot be copied to PC file " + pcPathString + ". Overwriting files is not allowed.";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages(noNodes);
            return "ERROR";
        }
        // If the file does not exist, create it
        if (!Files.exists(pcFilePath)) {
            Files.createFile(pcFilePath);
        }
        // Rewrite the PC file with records from the source member
        // -------------------
        // 
        // Open the output PC text file - with specified character set
        // ----------------------------
        // Characters read from input are translated to the specified character set if possible.
        // If input characters are incapable to be translated, an error message is reported (UnmappableCharacterException).
        BufferedWriter pcOutFile;
        if (pcCharset.equals("*DEFAULT")) {
            // Ignore PC charset parameter for binary transfer.
            pcOutFile = Files.newBufferedWriter(pcFilePath, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
        } else {
            // Use PC charset parameter for conversion.
            pcOutFile = Files.newBufferedWriter(pcFilePath, Charset.forName(pcCharset), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
        }
        // Read the first source member record
        Record inRecord = as400seqFile.readNext();
        // --------------------
        while (inRecord != null) {
            StringBuilder textLine = new StringBuilder();
            if (sourceRecordPrefixPresent) {
                // Source record is composed of three source record fields: seq. number, date, source data.
                DecimalFormat df1 = new DecimalFormat("0000.00");
                DecimalFormat df2 = new DecimalFormat("000000");
                String seq = df1.format((Number) inRecord.getField("SRCSEQ"));
                String seq2 = seq.substring(0, 4) + seq.substring(5);
                textLine.append(seq2);
                String srcDat = df2.format((Number) inRecord.getField("SRCDAT"));
                textLine.append(srcDat);
            }
            // Otherwise, source record consists of source data only
            // Convert source data into byte array
            byte[] byteArray = inRecord.getFieldAsBytes("SRCDTA");
            String translatedData;
            // Translate member data using parameter "IBM i CCSID"
            AS400Text textConverter = new AS400Text(byteArray.length, ibmCcsidInt, remoteServer);
            if (ibmCcsid.equals("*DEFAULT")) {
                // Translate member data using its CCSID attribute (possibly modified)
                textConverter = new AS400Text(byteArray.length, ccsidForDisplay, remoteServer);
            }
            // Convert byte array buffer to String text line (UTF-16)
            String str = (String) textConverter.toObject(byteArray);
            if (pcCharset.equals("*DEFAULT")) {
                // Assign "ISO-8859-1" as default charset
                pcCharset = "ISO-8859-1";
            }
            // Translate the String into PC charset
            translatedData = new String(str.getBytes(pcCharset), pcCharset);
            textLine.append(translatedData).append(NEW_LINE);
            // Write the translated text line to the PC file
            pcOutFile.write(textLine.toString());
            // Read next source member record
            inRecord = as400seqFile.readNext();
        }
        // Close the files
        pcOutFile.close();
        as400seqFile.close();
        row = "Info: Source member " + libraryName + "/" + fileName + "(" + memberName + ")  was copied to PC file  " + pcPathString + " using charset " + pcCharset + ".";
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(noNodes);
        return "";
    } catch (Exception exc) {
        exc.printStackTrace();
        row = "Error: Copying member  " + libraryName + "/" + fileName + "(" + memberName + ")  -  " + exc.toString();
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(noNodes);
        return "ERROR";
    }
}
Also used : Path(java.nio.file.Path) SequentialFile(com.ibm.as400.access.SequentialFile) RecordFormat(com.ibm.as400.access.RecordFormat) DecimalFormat(java.text.DecimalFormat) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) AS400FileRecordDescription(com.ibm.as400.access.AS400FileRecordDescription) BufferedWriter(java.io.BufferedWriter) AS400Text(com.ibm.as400.access.AS400Text) Record(com.ibm.as400.access.Record) IFSFile(com.ibm.as400.access.IFSFile)

Aggregations

IFSFile (com.ibm.as400.access.IFSFile)7 AS400FileRecordDescription (com.ibm.as400.access.AS400FileRecordDescription)6 Record (com.ibm.as400.access.Record)6 RecordFormat (com.ibm.as400.access.RecordFormat)6 SequentialFile (com.ibm.as400.access.SequentialFile)6 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)6 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)6 AS400Text (com.ibm.as400.access.AS400Text)5 CommandCall (com.ibm.as400.access.CommandCall)3 Point (java.awt.Point)3 DecimalFormat (java.text.DecimalFormat)3 BadLocationException (javax.swing.text.BadLocationException)3 AS400Message (com.ibm.as400.access.AS400Message)2 BufferedWriter (java.io.BufferedWriter)2 BigDecimal (java.math.BigDecimal)2 Path (java.nio.file.Path)2 PatternSyntaxException (java.util.regex.PatternSyntaxException)2 JTextArea (javax.swing.JTextArea)2 CannotRedoException (javax.swing.undo.CannotRedoException)2 CannotUndoException (javax.swing.undo.CannotUndoException)2