Search in sources :

Example 21 with AS400

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

the class Copy_PC_IBMi method walkPcDirectory_CreateNestedIfsDirectories.

/**
 * Walk through PC directory recursively to create shadow directories in IFS target directory. Shadow directories are
 * named by last names of the PC directory paths so that only one-level directories are inserted to the IFS target
 * directory.
 *
 * @param remoteServer
 * @param sourcePathString
 * @param ifsPath
 * @return
 */
protected String walkPcDirectory_CreateNestedIfsDirectories(AS400 remoteServer, String sourcePathString, IFSFile ifsPath) {
    try {
        Stream<Path> stream = Files.list(Paths.get(sourcePathString));
        stream.forEach(inPath -> {
            String pcPathName = inPath.toString();
            // Path to the new shadow directory to be created in IFS
            String newDirPathString = ifsPath.toString() + "/" + pcPathName.substring(pcPathName.lastIndexOf(pcFileSep) + 1);
            IFSFile ifsNewPath = new IFSFile(remoteServer, newDirPathString);
            // Only directories in PC are processed (not single files)
            if (Files.isDirectory(inPath)) {
                try {
                    if (!ifsNewPath.toString().contains(pcFileSep + ".")) {
                        // Create new shadow IFS directory
                        ifsNewPath.mkdir();
                        // Add message text to the message table and show it
                        row = "Info: Directory  " + pcPathName + "  was created in IFS directory  " + ifsPath.toString() + ".";
                        mainWindow.msgVector.add(row);
                        mainWindow.showMessages();
                    }
                    // Recursive call with different PC path
                    walkPcDirectory_CreateNestedIfsDirectories(remoteServer, pcPathName, ifsNewPath);
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
            }
        });
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    return "";
}
Also used : Path(java.nio.file.Path) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IFSFile(com.ibm.as400.access.IFSFile)

Example 22 with AS400

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

the class Copy_PC_IBMi method copyToSaveFile.

/**
 * Copy PC file to a new or existing Save File
 *
 * @param targetPathString
 * @param sourcePathString
 * @param toLibrary
 * @return
 */
@SuppressWarnings("UseSpecificCatch")
protected String copyToSaveFile(String sourcePathString, String targetPathString, boolean toLibrary) {
    // Extract individual names (libraryName, fileName, memberName) from the AS400 IFS path
    extractNamesFromIfsPath(targetPathString);
    String saveFilePathString;
    // Copy to LIBRARY
    if (toLibrary) {
        // Save file name is derived from PC file name excluding suffix .savf
        saveFileName = sourcePathString.substring(sourcePathString.lastIndexOf(pcFileSep) + 1, sourcePathString.lastIndexOf(".savf"));
        // Save file path string is derived from the path string of the library by adding the PC file name with suffix
        // .SAVF in upper case
        saveFilePathString = targetPathString + "/" + sourcePathString.substring(sourcePathString.lastIndexOf(pcFileSep) + 1).toUpperCase();
        // Create a new Save File if it does not exist
        try {
            SaveFile saveFile = new SaveFile(remoteServer, libraryName, saveFileName);
            if (!saveFile.exists()) {
                saveFile.create();
            }
        } catch (Exception exc) {
            exc.printStackTrace();
            row = "Error1: " + exc.toString();
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "ERROR";
        }
        // Copy the PC file to Save file using FTP (File Transfer Protocol)
        AS400FTP ftp = new AS400FTP(remoteServer);
        try {
            // FTP Binary data transfer
            // ftp.setDataTransferType(AS400FTP.BINARY); // not necessary when suffix is .savf
            // FTP Put command
            ftp.put(sourcePathString, saveFilePathString);
            ftp.disconnect();
            row = "Comp: PC file  " + sourcePathString + "  was copied to save file  " + libraryName + "/" + saveFileName + ".";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "";
        } catch (Exception exc) {
            exc.printStackTrace();
            row = "Error: Copying PC file  " + sourcePathString + "  to save file  " + libraryName + "/" + saveFileName + "  failed:  " + exc.toString();
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "ERROR";
        }
    } else // 
    // Copy to IFS FILE
    {
        // Save file name is derived from PC file name excluding suffix .savf
        saveFileName = sourcePathString.substring(sourcePathString.lastIndexOf(pcFileSep) + 1);
        if (!sourcePathString.endsWith(".savf")) {
            row = "Error: Copying PC save file  " + sourcePathString + "  ending with suffix \".savf\" cannot be copied to the existing file  " + targetPathString + "  with a different suffix.";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "ERROR";
        } else {
            // Copy the PC file to Save file using FTP (File Transfer Protocol)
            AS400FTP ftp = new AS400FTP(remoteServer);
            try {
                // FTP Binary data transfer
                // ftp.setDataTransferType(AS400FTP.BINARY); // not necessary when suffix is .savf
                // FTP Put command
                ftp.put(sourcePathString, targetPathString);
                ftp.disconnect();
                row = "Comp: PC save file  " + sourcePathString + "  was copied to IFS save file  " + targetPathString + ".";
                mainWindow.msgVector.add(row);
                mainWindow.showMessages();
                return "";
            } catch (Exception exc) {
                exc.printStackTrace();
                row = "Error: Copying PC save file  " + sourcePathString + "  to IFS save file  " + targetPathString + "  failed:  " + exc.toString();
                mainWindow.msgVector.add(row);
                mainWindow.showMessages();
                return "ERROR";
            }
        }
    }
}
Also used : SaveFile(com.ibm.as400.access.SaveFile) AS400FTP(com.ibm.as400.access.AS400FTP) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException)

Example 23 with AS400

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

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

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

Aggregations

IFSFile (com.ibm.as400.access.IFSFile)16 AS400Text (com.ibm.as400.access.AS400Text)14 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)14 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)14 AS400Message (com.ibm.as400.access.AS400Message)12 AS400 (com.ibm.as400.access.AS400)11 CommandCall (com.ibm.as400.access.CommandCall)9 IOException (java.io.IOException)8 AS400FileRecordDescription (com.ibm.as400.access.AS400FileRecordDescription)5 Record (com.ibm.as400.access.Record)5 RecordFormat (com.ibm.as400.access.RecordFormat)5 SequentialFile (com.ibm.as400.access.SequentialFile)5 BadLocationException (javax.swing.text.BadLocationException)5 ProgramCall (com.ibm.as400.access.ProgramCall)4 Point (java.awt.Point)4 Path (java.nio.file.Path)4 AS400SecurityException (com.ibm.as400.access.AS400SecurityException)3 RequestNotSupportedException (com.ibm.as400.access.RequestNotSupportedException)3 IntrospectionException (java.beans.IntrospectionException)3 ConnectorException (org.identityconnectors.framework.common.exceptions.ConnectorException)3