Search in sources :

Example 6 with AS400Text

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

the class SearchWindow method readSourceMember.

/**
 * Read Source Member data into text area.
 *
 * @return
 */
protected JTextArea readSourceMember() {
    IFSFile ifsFile = new IFSFile(remoteServer, mainWindow.sourcePathString);
    // Create an AS400FileRecordDescription object that represents the file
    AS400FileRecordDescription inRecDesc = new AS400FileRecordDescription(remoteServer, mainWindow.sourcePathString);
    try {
        // Decide what CCSID is appropriate for displaying the member
        int ccsidAttribute = ifsFile.getCCSID();
        // 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, mainWindow.sourcePathString);
        // 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);
        mainWindow.row = "Info: Source member  " + mainWindow.sourcePathString + "  has CCSID  " + ccsidAttribute + ".";
        mainWindow.msgVector.add(mainWindow.row);
        mainWindow.showMessages(mainWindow.nodes);
    } catch (Exception exc) {
        exc.printStackTrace();
        mainWindow.row = "Error: " + exc.toString();
        mainWindow.msgVector.add(mainWindow.row);
        mainWindow.showMessages(mainWindow.nodes);
    }
    // Remove message scroll listener (cancel scrolling to the last message)
    mainWindow.scrollMessagePane.getVerticalScrollBar().removeAdjustmentListener(mainWindow.messageScrollPaneAdjustmentListenerMax);
    return textArea;
}
Also used : SequentialFile(com.ibm.as400.access.SequentialFile) RecordFormat(com.ibm.as400.access.RecordFormat) DecimalFormat(java.text.DecimalFormat) PatternSyntaxException(java.util.regex.PatternSyntaxException) 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 7 with AS400Text

use of com.ibm.as400.access.AS400Text 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 8 with AS400Text

use of com.ibm.as400.access.AS400Text in project camel by apache.

the class Jt400PgmProducer method handlePGMOutput.

private void handlePGMOutput(Exchange exchange, ProgramCall pgmCall, ProgramParameter[] inputs) throws InvalidPayloadException {
    Object body = exchange.getIn().getMandatoryBody();
    Object[] params = (Object[]) body;
    List<Object> results = new ArrayList<Object>();
    int i = 1;
    for (ProgramParameter pgmParam : pgmCall.getParameterList()) {
        byte[] output = pgmParam.getOutputData();
        Object javaValue = params[i - 1];
        if (output != null) {
            int length = pgmParam.getOutputDataLength();
            AS400DataType typeConverter;
            if (getISeriesEndpoint().getFormat() == Jt400Configuration.Format.binary) {
                typeConverter = new AS400ByteArray(length);
            } else {
                typeConverter = new AS400Text(length, iSeries);
            }
            javaValue = typeConverter.toObject(output);
        }
        results.add(javaValue);
        i++;
    }
    Object[] bodyOUT = new Object[results.size()];
    bodyOUT = results.toArray(bodyOUT);
    exchange.getOut().setBody(bodyOUT);
}
Also used : ProgramParameter(com.ibm.as400.access.ProgramParameter) AS400Text(com.ibm.as400.access.AS400Text) ArrayList(java.util.ArrayList) AS400DataType(com.ibm.as400.access.AS400DataType) AS400ByteArray(com.ibm.as400.access.AS400ByteArray)

Example 9 with AS400Text

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

the class Copy_IBMi_IBMi method copyToIfsFile.

/**
 * Copy IFS file or Source member or Save file to an IFS file; If the target
 * IFS file does not exist, one is created.
 *
 * @param targetPathString
 * @param sourcePathString
 * @param fromWalk
 * @return
 */
protected String copyToIfsFile(String sourcePathString, String targetPathString, boolean fromWalk) {
    if (targetPathString.equals(sourcePathString)) {
        return "ERROR";
    }
    // Path to input IFS file
    inputDirFile = new IFSFile(remoteServer, sourcePathString);
    // Path to output IFS file
    outputDirFile = new IFSFile(remoteServer, targetPathString);
    try {
        // ---------------
        if (sourcePathString.startsWith("/QSYS.LIB/")) {
            extractNamesFromIfsPath(sourcePathString);
            if (sourcePathString.endsWith(".FILE") && inputDirFile.isSourcePhysicalFile()) {
                if (targetPathString.endsWith(".savf")) {
                    row = "Error: Source file  " + libraryName + "/" + fileName + "  cannot be copied to IFS file  " + targetPathString + "  ending with .savf.";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(nodes);
                    return "ERROR";
                }
                msgText = copyFromSourceFile(remoteServer, sourcePathString, targetPathString);
                if (msgText.isEmpty()) {
                    row = "Comp: Source file  " + libraryName + "/" + fileName + "  was copied to IFS file  " + targetPathString + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(nodes);
                    return "";
                } else {
                    row = "Comp File: Source file  " + libraryName + "/" + fileName + "  was NOT copied to IFS file.";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(nodes);
                    return "ERROR";
                }
            }
            if (sourcePathString.endsWith(".MBR")) {
                if (targetPathString.endsWith(".savf")) {
                    row = "Error: Source member  " + libraryName + "/" + fileName + "(" + memberName + ")  cannot be copied to IFS file  " + targetPathString + "  ending with .savf.";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(nodes);
                    return "ERROR";
                }
                msgText = copyFromSourceMember(remoteServer, sourcePathString, targetPathString);
                if (msgText.isEmpty()) {
                    row = "Comp: Source member  " + libraryName + "/" + fileName + "(" + memberName + ")  was copied to IFS file  " + targetPathString + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(nodes);
                    return "";
                } else {
                    row = "Comp File: Source member  " + libraryName + "/" + fileName + "(" + memberName + ")  was NOT copied to IFS file.";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(nodes);
                    return "ERROR";
                }
            } else // ---------
            if (inputDirFile.toString().contains(".LIB") && inputDirFile.toString().endsWith(".SAVF")) {
                msgText = copyFromSaveFile(remoteServer, sourcePathString, targetPathString);
                return msgText;
            }
        } else {
            if (outputDirFile.isDirectory()) {
                // When IFS directory, add source file name
                // ------------------
                // IFS file path string = target IFS directory + source IFS file
                // name
                targetPathString = sourcePathStringPrefix + "/" + inputDirFile.getName();
                outputDirFile = new IFSFile(remoteServer, targetPathString);
            }
            // =======================================
            try {
                byte[] inputByteArray = new byte[2000000];
                int bytesRead;
                // ---------------------------------
                if (outputDirFile.exists() && !overwriteAllowed) {
                    row = "Error: IFS file  " + inputDirFile + "  was NOT copied to the existing file  " + targetPathString + ". Overwriting files is not allowed.";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(noNodes);
                    return "ERROR";
                }
                // Get input file CCSID attribute
                int inputFileCcsid = inputDirFile.getCCSID();
                // Target file CCSID attribute - not yet ready
                int outputFileCcsid;
                // -------------------------------------
                if (!outputDirFile.exists()) {
                    // If target file does not exist, create one and set its CCSID
                    // from the input file
                    outputDirFile.createNewFile();
                    outputDirFile.setCCSID(inputFileCcsid);
                }
                outputFileCcsid = outputDirFile.getCCSID();
                // Open input IFS file
                ifsInStream = new IFSFileInputStream(remoteServer, sourcePathString);
                // 
                if (ibmCcsid.equals("*DEFAULT") || outputFileCcsid == inputFileCcsid) {
                    ifsOutStream = new IFSFileOutputStream(remoteServer, targetPathString);
                    // Copy IFS file to IFS file reading input stream to byte
                    // array and using output stream for output
                    // Read first portion of bytes
                    bytesRead = ifsInStream.read(inputByteArray);
                    // Repeat if at least one byte was read
                    while (bytesRead > 0) {
                        // Write out bytes read before
                        ifsOutStream.write(inputByteArray, 0, bytesRead);
                        // Read next portion of bytes
                        bytesRead = ifsInStream.read(inputByteArray);
                    }
                    // Close files
                    ifsOutStream.close();
                    ifsInStream.close();
                    if (fromWalk) {
                        row = "Info: IFS file  " + sourcePathString + "  was copied unchanged (binary) to IFS file  " + targetPathString + ". " + outputFileCcsid + " -> " + outputFileCcsid + ".";
                    } else {
                        row = "Comp: IFS file  " + sourcePathString + "  was copied unchanged (binary) to IFS file  " + targetPathString + ". " + outputFileCcsid + " -> " + outputFileCcsid + ".";
                    }
                // 
                } else {
                    // 
                    // Conversion from source IFS file's CCSID to target IFS file's CCSID
                    // ----------
                    // Open output IFS file
                    ifsOutStream = new IFSFileOutputStream(remoteServer, targetPathString, outputFileCcsid);
                    // Copy IFS file to IFS file reading input stream to byte
                    // array and using byte array for output
                    // Read first portion of bytes
                    bytesRead = ifsInStream.read(inputByteArray);
                    // Repeat if at least one byte was read
                    while (bytesRead > 0) {
                        // Convert input byte array with input CCSID to String
                        // (UTF-16)
                        AS400Text textConverter = new AS400Text(bytesRead, inputFileCcsid, remoteServer);
                        String text = (String) textConverter.toObject(inputByteArray);
                        // Convert data from String (UTF-16) to outpu byte array
                        // with output CCSID
                        AS400Text textConverter2 = new AS400Text(bytesRead, outputFileCcsid, remoteServer);
                        byte[] outputByteArray = (byte[]) textConverter2.toBytes(text);
                        // Write converted text in second byte array to output
                        // stream
                        ifsOutStream.write(outputByteArray, 0, outputByteArray.length);
                        // Read next byte array
                        bytesRead = ifsInStream.read(inputByteArray);
                        // Close files
                        ifsOutStream.close();
                        ifsInStream.close();
                        if (fromWalk) {
                            row = "Info: IFS file  " + sourcePathString + "  was copied to IFS file  " + targetPathString + ", Convert  " + inputFileCcsid + " -> " + outputFileCcsid;
                        } else {
                            row = "Comp: IFS file  " + sourcePathString + "  was copied to IFS file  " + targetPathString + ", Convert  " + inputFileCcsid + " -> " + outputFileCcsid;
                        }
                    }
                }
                mainWindow.msgVector.add(row);
                mainWindow.showMessages(nodes);
                return "";
            } catch (Exception exc) {
                exc.printStackTrace();
                row = "Error: Copying to IFS file " + targetPathString + "  -  " + exc.toString();
                mainWindow.msgVector.add(row);
                mainWindow.showMessages(nodes);
                return "ERROR";
            }
        }
    } catch (Exception exc) {
        exc.printStackTrace();
        row = "Error: Copying to IFS file " + targetPathString + "  -  " + exc.toString();
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(nodes);
        return "ERROR";
    }
    return "";
}
Also used : IFSFileOutputStream(com.ibm.as400.access.IFSFileOutputStream) AS400Text(com.ibm.as400.access.AS400Text) IFSFile(com.ibm.as400.access.IFSFile) IFSFileInputStream(com.ibm.as400.access.IFSFileInputStream)

Example 10 with AS400Text

use of com.ibm.as400.access.AS400Text 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)

Aggregations

AS400Text (com.ibm.as400.access.AS400Text)15 IFSFile (com.ibm.as400.access.IFSFile)11 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)6 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)6 BadLocationException (javax.swing.text.BadLocationException)6 IFSFileInputStream (com.ibm.as400.access.IFSFileInputStream)5 AS400FileRecordDescription (com.ibm.as400.access.AS400FileRecordDescription)4 IFSFileOutputStream (com.ibm.as400.access.IFSFileOutputStream)4 Record (com.ibm.as400.access.Record)4 RecordFormat (com.ibm.as400.access.RecordFormat)4 SequentialFile (com.ibm.as400.access.SequentialFile)4 PatternSyntaxException (java.util.regex.PatternSyntaxException)4 CannotRedoException (javax.swing.undo.CannotRedoException)4 CannotUndoException (javax.swing.undo.CannotUndoException)4 Point (java.awt.Point)3 BufferedWriter (java.io.BufferedWriter)3 Path (java.nio.file.Path)3 DecimalFormat (java.text.DecimalFormat)3 AS400ByteArray (com.ibm.as400.access.AS400ByteArray)2 AS400DataType (com.ibm.as400.access.AS400DataType)2