Search in sources :

Example 11 with IFSFile

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

the class Copy_PC_IBMi method copyFromPcDirectory.

/**
 * Copying a PC directory to IFS directory or to Library/Source File.
 *
 * @param sourcePathString
 * @param targetPathString
 * @param sourcePathStringPrefix
 */
protected void copyFromPcDirectory(String sourcePathString, String targetPathString, String sourcePathStringPrefix) {
    // Get object and member names (libraryName, fileName, memberName
    extractNamesFromIfsPath(targetPathString);
    if (!sourcePathString.contains(pcFileSep + ".")) {
        IFSFile targetPath = new IFSFile(remoteServer, targetPathString + "/" + sourcePathString.substring(sourcePathStringPrefix.length()));
        // --------------------------------
        if (!targetPathString.startsWith("/QSYS.LIB")) {
            // Create the first shadow IFS directory
            try {
                if (!targetPath.exists()) {
                    // Create new directory in target IFS directory with PC file ending name
                    targetPath.mkdir();
                    // Add message text to the message table and show it
                    row = "Info: Directory  " + sourcePathString + "  was created in IFS directory  " + targetPathString + ".";
                    mainWindow.msgVector.add(row);
                }
            } catch (Exception exc) {
                exc.printStackTrace();
                row = exc.toString();
                mainWindow.msgVector.add(row);
                mainWindow.showMessages();
                return;
            }
            // Create shadow directories in the first shadow IFS directory created above
            msgText = walkPcDirectory_CreateNestedIfsDirectories(remoteServer, sourcePathString, targetPath);
            // Copy PC files to appropriate IFS shadow directories
            msgText = copyPcFilesToIfsDirectories(sourcePathString, targetPath, sourcePathStringPrefix);
            // Construct a message in the message table and show it
            if (msgText.isEmpty()) {
                row = "Comp: PC directory  " + sourcePathString + "  was copied to IFS directory  " + targetPathString + ".";
            } else {
                row = "Comp: PC directory  " + sourcePathString + "  was NOT completely copied to IFS directory  " + targetPathString + ".";
            }
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
        }
        // ------------------
        if (targetPathString.startsWith("/QSYS.LIB")) {
            if (ibmCcsid.equals("*DEFAULT")) {
                ibmCcsid = "500";
            }
            // Create new source physical file in the library and call copyToSourceFile() method
            if (targetPathString.endsWith(".LIB")) {
                // Extract individual names (libraryName, fileName, memberName) from the AS400 IFS path
                extractNamesFromIfsPath(targetPathString);
                // Extract a new file name from the last component of the PC path string.
                // The file name extracted by the method before was null!
                fileName = sourcePathString.substring(sourcePathString.lastIndexOf(pcFileSep) + 1);
                // Create new source physical file
                String sourceRecordLength = (String) properties.get("SOURCE_RECORD_LENGTH");
                // The property contains all digits. It was made certain when the user entered the value.
                int sourceRecordLengthInt = Integer.parseInt(sourceRecordLength);
                // Source record must contain 12 byte prefix to data line: sequence number (6) and date (6)
                sourceRecordLengthInt += 12;
                // Build command CRTSRCPF to create a source physical file with certain CCSID in the library
                String commandText = "CRTSRCPF FILE(" + libraryName + "/" + fileName + ") " + "RCDLEN(" + sourceRecordLengthInt + ") CCSID(" + ibmCcsid + ")";
                // Enable calling CL commands
                CommandCall cmdCall = new CommandCall(remoteServer);
                try {
                    // Run the command
                    cmdCall.run(commandText);
                    // Get messages from the command if any
                    AS400Message[] as400MessageList = cmdCall.getMessageList();
                    // Send all messages from the command. After ESCAPE message - return.
                    for (AS400Message as400Message : as400MessageList) {
                        if (as400Message.getType() == AS400Message.ESCAPE) {
                            row = "Error: Create source physical file  " + libraryName + "/" + fileName + " using CRTSRCPF command  -  " + as400Message.getID() + " " + as400Message.getText();
                            mainWindow.msgVector.add(row);
                            mainWindow.showMessages();
                            return;
                        } else {
                            row = "Info: Create source physical file  " + libraryName + "/" + fileName + " using CRTSRCPF command  -  " + as400Message.getID() + " " + as400Message.getText();
                            mainWindow.msgVector.add(row);
                            mainWindow.showMessages();
                        }
                    }
                } catch (Exception exc) {
                    exc.printStackTrace();
                    row = "Error: Copying PC directory  " + sourcePathString + "  to source physical File  " + libraryName + "/" + fileName + "  -  " + exc.toString();
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                    // Must return! Could be fatal error (e. g. lock of the source file)!
                    return;
                }
                // Copy members to the new source physical file in a library
                msgText = copyToSourceFile(sourcePathString, targetPathString + "/" + fileName + ".FILE");
                if (msgText.isEmpty()) {
                    row = "Comp: PC directory  " + sourcePathString + "  was copied to source physical file  " + libraryName + "/" + fileName + ".";
                } else {
                    row = "Comp: PC directory  " + sourcePathString + "  was NOT completely copied to source physical file  " + libraryName + "/" + fileName + ".";
                }
                mainWindow.msgVector.add(row);
                mainWindow.showMessages();
            } else // ---------------------------------------------------------
            if (targetPathString.endsWith(".FILE")) {
                // Copy single PC file to source file to existing member or as a new member
                msgText = copyToSourceFile(sourcePathString, targetPathString);
                if (msgText.isEmpty()) {
                    row = "Comp: PC directory  " + sourcePathString + "  was copied to source physical file  " + libraryName + "/" + fileName + ".";
                } else {
                    row = "Comp: PC directory  " + sourcePathString + "  was NOT completely copied to source physical file  " + libraryName + "/" + fileName + ".";
                }
                mainWindow.msgVector.add(row);
                mainWindow.showMessages();
            } else // ----------------------------------------
            if (targetPathString.endsWith(".MBR")) {
                row = "Error: PC directory  " + sourcePathString + "  cannot be copied to a source physical file member  " + libraryName + "/" + fileName + "(" + memberName + ").";
                mainWindow.msgVector.add(row);
                mainWindow.showMessages();
            }
        }
    }
}
Also used : CommandCall(com.ibm.as400.access.CommandCall) AS400Message(com.ibm.as400.access.AS400Message) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IFSFile(com.ibm.as400.access.IFSFile)

Example 12 with IFSFile

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

the class Copy_PC_IBMi method copyToSourceMember.

/**
 * Copy PC text file to the IBM i source member.
 *
 * @param sourcePathString
 * @param targetPathString
 * @param fromDirectory
 * @return
 */
protected String copyToSourceMember(String sourcePathString, String targetPathString, boolean fromDirectory) {
    if (ibmCcsid.equals("*DEFAULT")) {
        ibmCcsid = "500";
        ibmCcsidInt = 500;
    }
    // Extract individual names (libraryName, fileName, memberName) from the AS400 IFS path
    extractNamesFromIfsPath(targetPathString);
    if (sourcePathString.endsWith(pcFileSep)) {
        sourcePathString = sourcePathString.substring(0, sourcePathString.lastIndexOf(pcFileSep));
    }
    // Get source type from the PC file name
    String sourceType;
    if (sourcePathString.lastIndexOf(".") > 0) {
        // If file name has postfix with a dot, the posfix will be the source type
        sourceType = sourcePathString.substring(sourcePathString.lastIndexOf(".") + 1);
    } else {
        // If file name does not have a postfix (there is no dot), the source type will be MBR
        sourceType = "MBR";
    }
    // Path to input PC text file
    Path inTextFile = Paths.get(sourcePathString);
    // Path to the output source member
    String outMemberPathString = "/QSYS.LIB/" + libraryName + ".LIB/" + fileName + ".FILE" + "/" + memberName + ".MBR";
    IFSFile ifsMbr = new IFSFile(remoteServer, outMemberPathString);
    String clrPfmCommand;
    String chgPfmCommand;
    // Enable calling CL commands
    CommandCall cmdCall = new CommandCall(remoteServer);
    msgText = "";
    try {
        // Open PC input file regarded as a text file.
        if (pcCharset.equals("*DEFAULT")) {
            // Decode input using its encoding. Ignore PC charset parameter.
            inFile = Files.newBufferedReader(inTextFile);
        } else {
            // Decode input using PC charset parameter.
            inFile = Files.newBufferedReader(inTextFile, Charset.forName(pcCharset));
        }
        try {
            // Read the first text line
            textLine = inFile.readLine();
        // If an error is found in the first line of the file,
        // processing is broken, the error is caught (see catch blocks), a message is reported,
        // and no member is created.
        } catch (Exception exc) {
            exc.printStackTrace();
            row = "Error: Data of the PC file  " + sourcePathString + "  cannot be copied to the source physical file  " + libraryName + "/" + fileName + "  -  " + exc.toString();
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            msgText = "ERROR";
            return msgText;
        }
        // -----------------------------------
        if (ifsMbr.exists() && !properties.getProperty("OVERWRITE_FILE").equals("Y")) {
            row = "Info: PC file  " + sourcePathString + "  cannot be copied to the existing source physical member  " + libraryName + "/" + fileName + "(" + memberName + "). Overwriting files is not allowed.";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "ERROR";
        }
        // SEQUENCE NUMBER and DATE information fields in the first 6 + 6 positions.
        try {
            // Non-empty member can be checked for information fields if the line is longer than 12
            if (textLine != null && textLine.length() > 12) {
                int seqNbr = Integer.parseInt(textLine.substring(0, 6));
                int date = Integer.parseInt(textLine.substring(6, 12));
                seqAndDatePresent = true;
            } else {
                // Otherwise the line cannot have information fields
                seqAndDatePresent = false;
            }
        } catch (NumberFormatException nfe) {
            seqAndDatePresent = false;
        }
        if (seqAndDatePresent) {
            // Input records contain sequence and data fields
            // ----------------------------------------------
            // Copying is done directly using a sequential file preserving sequence and data field values.
            // Clear physical file member
            clrPfmCommand = "CLRPFM FILE(" + libraryName + "/" + fileName + ") MBR(" + memberName + ")";
            cmdCall.run(clrPfmCommand);
            // 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]);
            // 
            // Note: Now create the member if no error was found in the first text line.
            // -----
            // 
            // Create the member (SequentialFile object)
            outSeqFile = new SequentialFile(remoteServer, outMemberPathString);
            // Set the record format (the only one)
            outSeqFile.setRecordFormat(format[0]);
            try {
                // Open the member
                outSeqFile.open();
            } 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);
                // Change member to set its Source Type
                chgPfmCommand = "CHGPFM FILE(" + libraryName + "/" + fileName + ") MBR(" + memberName + ") SRCTYPE(" + sourceType + ")";
                // Perform the CL command
                cmdCall.run(chgPfmCommand);
                // Open the new member
                outSeqFile.open();
            }
            // Process all lines
            while (textLine != null) {
                // Get lengths of three fields of the source record
                int lenSEQ = format[0].getFieldDescription("SRCSEQ").getLength();
                int lenDAT = format[0].getFieldDescription("SRCDAT").getLength();
                // Set the three field values from the input text line according to their lengths
                outRecord.setField("SRCSEQ", new BigDecimal(new BigInteger(textLine.substring(0, lenSEQ)), 2));
                outRecord.setField("SRCDAT", new BigDecimal(textLine.substring(lenSEQ, lenSEQ + lenDAT)));
                outRecord.setField("SRCDTA", textLine.substring(lenSEQ + lenDAT));
                try {
                    // Write source record
                    outSeqFile.write(outRecord);
                    // Read next text line
                    textLine = inFile.readLine();
                } catch (Exception exc) {
                    exc.printStackTrace();
                    row = "Error: 1 Data of the PC file  " + sourcePathString + "  cannot be copied to the source physical file  " + libraryName + "/" + fileName + "  -  " + exc.toString();
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                    msgText = "ERROR";
                    break;
                }
            }
            // Close files
            inFile.close();
            outSeqFile.close();
        } else {
            // Input records DO NOT contain sequence and data fields
            // -----------------------------------------------------
            // Copying is done indirectly using a temporary IFS file in the /home/userName directory.
            // First create an IFS '/home/userName directory if it does not exist
            String home_userName = "/home/" + userName;
            IFSFile ifsDir = new IFSFile(remoteServer, home_userName);
            // Create new directory
            ifsDir.mkdir();
            // String for command CHGATR to set CCSID attribute of the new directory
            String command_CHGATR = "CHGATR OBJ('" + home_userName + ") ATR(*CCSID) VALUE(" + ibmCcsid + ") SUBTREE(*ALL)";
            // Perform the command
            cmdCall.run(command_CHGATR);
            // Create hidden temporary file (with leading dot) in the directory
            String tmp_File = home_userName + "/.tmp" + Timestamp.valueOf(LocalDateTime.now()).toString();
            IFSFile ifsTmpFile = new IFSFile(remoteServer, tmp_File);
            ifsTmpFile.createNewFile();
            // Copy PC file to temporary IFS file
            copyFromPcFile(sourcePathString, tmp_File, notFromWalk);
            // Copy data from temporary IFS file to the member. If the member does not exist it is created.
            String commandCpyFrmStmfString = "CPYFRMSTMF FROMSTMF('" + tmp_File + "') TOMBR('" + targetPathString + "') MBROPT(*REPLACE) CVTDTA(*AUTO) STMFCCSID(*STMF) DBFCCSID(*FILE)";
            // Perform the command
            cmdCall.run(commandCpyFrmStmfString);
            // Delete the temporary file
            ifsTmpFile.delete();
        }
        row = "Info: PC file  " + sourcePathString + "  was copied to source physical file member  " + libraryName + "/" + fileName + "(" + memberName + "). Convert " + pcCharset + " -> " + ibmCcsid + ".";
        mainWindow.msgVector.add(row);
        mainWindow.showMessages();
        if (!msgText.isEmpty()) {
            return "ERROR";
        }
        if (msgText.isEmpty() && !fromDirectory) {
            row = "Comp: PC file  " + sourcePathString + "  was copied to source physical file member  " + libraryName + "/" + fileName + "(" + memberName + "). Convert " + pcCharset + " -> " + ibmCcsid + ".";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "";
        }
        if (!msgText.isEmpty() && !fromDirectory) {
            row = "Comp: PC file  " + sourcePathString + "  was NOT completely copied to source physical file member  " + libraryName + "/" + fileName + "(" + memberName + "). Convert " + pcCharset + " -> " + ibmCcsid + ".";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "ERROR";
        }
    } catch (Exception exc) {
        try {
            inFile.close();
            outSeqFile.close();
        } catch (Exception exce) {
            exce.printStackTrace();
        }
        exc.printStackTrace();
        row = "Error: 3 PC file  " + sourcePathString + "  cannot be copied to the source physical file  " + libraryName + "/" + fileName + "  -  " + exc.toString();
        mainWindow.msgVector.add(row);
        mainWindow.showMessages();
        // Must not continue in order not to lock an object
        return "ERROR";
    }
    return "";
}
Also used : Path(java.nio.file.Path) CommandCall(com.ibm.as400.access.CommandCall) SequentialFile(com.ibm.as400.access.SequentialFile) RecordFormat(com.ibm.as400.access.RecordFormat) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) BigDecimal(java.math.BigDecimal) AS400FileRecordDescription(com.ibm.as400.access.AS400FileRecordDescription) BigInteger(java.math.BigInteger) Record(com.ibm.as400.access.Record) IFSFile(com.ibm.as400.access.IFSFile)

Example 13 with IFSFile

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

the class Copy_PC_IBMi method copyFromPcFile.

/**
 * Copying simple PC file to IBMi IFS directory/file or to Source File/Source Member or to Save File
 *
 * @param sourcePathString
 * @param targetPathString
 * @param fromWalk
 * @return
 */
protected String copyFromPcFile(String sourcePathString, String targetPathString, boolean fromWalk) {
    if (!sourcePathString.contains(pcFileSep + ".")) {
        try {
            // Extract individual names (libraryName, fileName, memberName) from the AS400 IFS path
            extractNamesFromIfsPath(targetPathString);
            // Path to PC file
            Path pcFilePath = Paths.get(sourcePathString);
            // IFS file or directory object
            IFSFile targetPath = new IFSFile(remoteServer, targetPathString);
            // 
            if (!targetPathString.startsWith("/QSYS.LIB")) {
                String outFileName;
                if (targetPath.isDirectory()) {
                    // 
                    // to IFS directory:
                    // IFS file name = IFS directory name + PC file name
                    outFileName = targetPathString + "/" + pcFilePath.getFileName();
                    if (outFileName.endsWith(".savf")) {
                        copyToSaveFile(sourcePathString, outFileName, notToLibrary);
                        return "";
                    }
                } else {
                    // 
                    // to IFS file:
                    // IFS file name does not change
                    outFileName = targetPathString;
                    if (outFileName.endsWith(".savf")) {
                        copyToSaveFile(sourcePathString, outFileName, notToLibrary);
                        return "";
                    }
                    // If input PC file ends with .savf, output IFS file must also end with .savf
                    if (sourcePathString.endsWith(".savf") && !outFileName.endsWith(".savf")) {
                        row = "Error: PC file  " + sourcePathString + "  ending with suffix \".savf\" cannot be copied to IFS file  " + outFileName + "  with a different suffix.";
                        mainWindow.msgVector.add(row);
                        mainWindow.showMessages();
                        return "ERROR";
                    }
                }
                // Create IFS file object
                IFSFile outFilePath = new IFSFile(remoteServer, outFileName);
                if (outFilePath.exists() && !properties.getProperty("OVERWRITE_FILE").equals("Y")) {
                    row = "Error: PC file  " + sourcePathString + "  was NOT copied to the existing file  " + outFileName + ". Overwriting files is not allowed.";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                    return "ERROR";
                }
                // Default CCSID for IFS files is 819
                if (ibmCcsid.equals("*DEFAULT")) {
                    ibmCcsid = "819";
                    ibmCcsidInt = 819;
                }
                // no conversion id necessary and transfer is faster.
                if (pcCharset.toUpperCase().equals("UTF-8") && ibmCcsid.equals("1208") || pcCharset.toUpperCase().equals("UTF-16") && ibmCcsid.equals("1200") || pcCharset.toUpperCase().equals("UTF-16") && ibmCcsid.equals("13488") || // ASCII Windows
                pcCharset.toUpperCase().equals("WINDOWS-1250") && ibmCcsid.equals("1250") || // ASCII Windows
                pcCharset.toUpperCase().equals("WINDOWS-1251") && ibmCcsid.equals("1251") || // ASCII Windows
                pcCharset.toUpperCase().equals("CP1250") && ibmCcsid.equals("1250") || // ASCII Windows
                pcCharset.toUpperCase().equals("CP1251") && ibmCcsid.equals("1251") || // ASCII Latin-1
                pcCharset.toUpperCase().equals("ISO-8859-1") && ibmCcsid.equals("819") || // ASCII Latin-1
                pcCharset.toUpperCase().equals("ISO-8859-1") && ibmCcsid.equals("858") || // EBCDIC Latin-1
                pcCharset.toUpperCase().equals("IBM500") && ibmCcsid.equals("500") || // EBCDIC Latin-1
                pcCharset.toUpperCase().equals("CP500") && ibmCcsid.equals("500") || // ASCII Latin-2
                pcCharset.toUpperCase().equals("ISO-8859-2") && ibmCcsid.equals("912") || // EBCDIC Latin-2
                pcCharset.toUpperCase().equals("IBM870") && ibmCcsid.equals("870")) {
                    // Allocate buffer for data
                    ByteBuffer byteBuffer = ByteBuffer.allocate(2000000);
                    // Open output IFS file - SHARED for all users, REWRITE data
                    // 
                    IFSFileOutputStream ifsOutStream = new IFSFileOutputStream(remoteServer, outFileName, IFSFileOutputStream.SHARE_ALL, false);
                    // Force this CCSID as an attribute to the output IFS file
                    outFilePath.setCCSID(ibmCcsidInt);
                    // Open the input PC file
                    FileChannel fileChannel = (FileChannel) Files.newByteChannel(pcFilePath);
                    // Copy PC file to IFS file with byte buffer
                    int bytesRead = fileChannel.read(byteBuffer);
                    while (bytesRead > 0) {
                        for (int idx = 0; idx < bytesRead; idx++) {
                            // New line byte must be changed for EBCDIC
                            if (byteBuffer.get(idx) == 0x15) {
                                byteBuffer.put(idx, (byte) 0x25);
                            }
                        }
                        ifsOutStream.write(byteBuffer.array(), 0, bytesRead);
                        // Set start of buffer to read next bytes into
                        byteBuffer.rewind();
                        bytesRead = fileChannel.read(byteBuffer);
                    }
                    // Close files
                    ifsOutStream.close();
                    fileChannel.close();
                    if (fromWalk) {
                        row = "Info: PC file  " + sourcePathString + "  was copied unchanged (binary) to IFS file  " + outFileName + ", CCSID " + ibmCcsid + ".";
                    } else {
                        row = "Comp: PC file  " + sourcePathString + "  was copied unchanged (binary) to IFS file  " + outFileName + ", CCSID " + ibmCcsid + ".";
                    }
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                } else {
                    // 
                    // Conversion from pcCharset to ibmCcsid
                    // -------------------------------------
                    // 
                    byte[] byteArray = new byte[2000000];
                    // Open input
                    BufferedReader bufferedReader;
                    if (pcCharset.equals("*DEFAULT")) {
                        pcCharset = "ISO-8859-1";
                    }
                    // Input will be decoded using PC charset parameter.
                    bufferedReader = Files.newBufferedReader(pcFilePath, Charset.forName(pcCharset));
                    // }
                    // Open output
                    IFSFileOutputStream ifsOutStream = new IFSFileOutputStream(remoteServer, outFileName, IFSFileOutputStream.SHARE_ALL, false, ibmCcsidInt);
                    // Force the CCSID from application parameter to the IFS file as an attribute
                    outFilePath.setCCSID(ibmCcsidInt);
                    // Copy data
                    int nbrOfBytes = 0;
                    String textLine = bufferedReader.readLine();
                    while (textLine != null) {
                        textLine += "\r\n";
                        // Decide how long in bytes the line is given target encoding.
                        if (ibmCcsid.equals("1200") || ibmCcsid.equals("13488")) {
                            // Get length in bytes for conversion to Unicode 1200 (UTF-16) and 13488 (UCS-2)
                            nbrOfBytes = textLine.length() * 2;
                        } else if (ibmCcsid.equals("1208")) {
                            // Get length in bytes
                            // for UTF-8 -> 1208
                            // and for single byte CCSIDs.
                            nbrOfBytes = textLine.getBytes().length;
                        } else {
                            // Get length of bytes of the text line for single byte characters
                            nbrOfBytes = textLine.length();
                        }
                        // Create text converter with correct length in bytes
                        AS400Text textConverter = new AS400Text(nbrOfBytes, ibmCcsidInt, remoteServer);
                        try {
                            byteArray = textConverter.toBytes(textLine);
                        } catch (Exception exc) {
                            exc.printStackTrace();
                            row = "Error: 1 Copying PC text file  " + sourcePathString + "  to IFS file  " + targetPathString + ".  Convert  " + pcCharset + " -> " + ibmCcsid + ".  -  " + exc.toString();
                            mainWindow.msgVector.add(row);
                            mainWindow.showMessages();
                            return "ERROR";
                        }
                        ifsOutStream.write(byteArray);
                        // Read next line
                        textLine = bufferedReader.readLine();
                    }
                    bufferedReader.close();
                    ifsOutStream.close();
                    if (fromWalk) {
                        row = "Info: PC file  " + sourcePathString + "  was copied to IFS file  " + outFileName + ",  Convert " + pcCharset + " -> " + ibmCcsid + ".";
                    } else {
                        row = "Comp: PC file  " + sourcePathString + "  was copied to IFS file  " + outFileName + ",  Convert " + pcCharset + " -> " + ibmCcsid + ".";
                    }
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                }
                return "";
            } else // --------------------------------------------------------
            if (targetPathString.endsWith(".LIB")) {
                // Default CCSID for Library objects is 500 (EBCDIC Latin-1)
                if (ibmCcsid.equals("*DEFAULT")) {
                    ibmCcsid = "500";
                    ibmCcsidInt = 500;
                }
                // PC file with suffix .savf to LIBRARY
                if (pcFilePath.getFileName().toString().endsWith(".savf")) {
                    msgText = copyToSaveFile(sourcePathString, targetPathString, toLibrary);
                } else // 
                // 
                // PC file without .savf suffix is NOT ALLOWED to copy to LIBRARY!
                {
                    row = "Error: PC file  " + sourcePathString + "  without .savf suffix cannot be copied to the library  " + libraryName + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                }
            // PC file to SAVE FILE
            } else if (targetPathString.contains(".LIB") && targetPathString.endsWith(".SAVF")) // && targetPath.getSubtype().equals("SAVF")
            {
                msgText = copyToSaveFile(sourcePathString, targetPathString, notToLibrary);
                if (!msgText.isEmpty()) {
                    row = "Comp: PC file  " + sourcePathString + "  was NOT copied to the save file  " + libraryName + "/" + fileName + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                }
            } else if (targetPathString.endsWith(".FILE")) {
                // File ending with .savf is not allowed to source member
                if (sourcePathString.endsWith(".savf")) {
                    row = "Error: PC file  " + sourcePathString + "  ending with .savf cannot be copied to source file  " + libraryName + "/" + fileName + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                    return "ERROR";
                }
                // Insert to source file as a member
                msgText = copyToSourceFile(sourcePathString, targetPathString);
                if (!msgText.isEmpty()) {
                    // + libraryName + "/" + fileName + "."
                    row = "Comp: PC file  " + sourcePathString + "  was NOT copied to the existing source physical file  ";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                }
            } else if (targetPathString.endsWith(".MBR")) {
                // 
                if (Files.isDirectory(pcFilePath)) {
                    // PC file to SOURCE MEMBER
                    msgText = copyToSourceMember(sourcePathString, targetPathString, fromDirectory);
                } else {
                    // File ending with .savf is not allowed to source member
                    if (sourcePathString.endsWith(".savf")) {
                        row = "Error: PC file  " + sourcePathString + "  ending with .savf cannot be copied to source member  " + libraryName + "/" + fileName + "/" + memberName + ".";
                        mainWindow.msgVector.add(row);
                        mainWindow.showMessages();
                        return "ERROR";
                    }
                    // Rewrite source member
                    msgText = copyToSourceMember(sourcePathString, targetPathString, notFromDirectory);
                }
                if (!msgText.isEmpty()) {
                    row = "Comp: PC file  " + sourcePathString + "  was NOT copied to the existing source physical member  " + libraryName + "/" + fileName + "(" + memberName + ").";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                }
            }
        } catch (Exception exc) {
            exc.printStackTrace();
            row = "Error: 2 Copying PC file  " + sourcePathString + "  to IFS file  " + targetPathString + ". Convert  " + pcCharset + " -> " + ibmCcsid + ".  -  " + exc.toString();
            mainWindow.msgVector.add(row);
            mainWindow.showMessages();
            return "ERROR";
        }
    }
    return msgText;
}
Also used : Path(java.nio.file.Path) IFSFileOutputStream(com.ibm.as400.access.IFSFileOutputStream) AS400Text(com.ibm.as400.access.AS400Text) FileChannel(java.nio.channels.FileChannel) BufferedReader(java.io.BufferedReader) ByteBuffer(java.nio.ByteBuffer) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IFSFile(com.ibm.as400.access.IFSFile)

Example 14 with IFSFile

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

the class Copy_PC_IBMi method copyPcFilesToIfsDirectories.

/**
 * Copying PC files to IFS directories created before (see walkPcDirectory_CreateNestedIfsDirectories method).
 *
 * @param sourcePathString
 * Source PC directory name
 * @param ifsPath
 * Target IFS directory path
 * @param sourcePathStringPrefix
 * @return
 */
protected String copyPcFilesToIfsDirectories(String sourcePathString, IFSFile ifsPath, String sourcePathStringPrefix) {
    msgTextDir = "";
    atLeastOneErrorInFiles = false;
    try {
        if (!sourcePathString.contains(pcFileSep + ".")) {
            // Get list of PC directory objects
            Stream<Path> stream = Files.list(Paths.get(sourcePathString));
            // Process all objects of the list
            stream.forEach(inPath -> {
                String pcPathName = inPath.toString();
                String pcFileName = inPath.getFileName().toString();
                String nextPcFile = sourcePathString + pcFileSep + pcFileName;
                // Path to the new shadow directory is the target IFS path plus PC file name ending the PC path
                String newDirPathString = ifsPath.toString() + "/" + pcFileName;
                // Create object of IFSFile type
                IFSFile ifsNewPath = new IFSFile(remoteServer, newDirPathString);
                // -------------
                if (Files.isDirectory(inPath)) {
                    if (!pcPathName.contains(pcFileSep + ".")) {
                        // Recursive call with new IFS path object
                        copyPcFilesToIfsDirectories(pcPathName, ifsNewPath, sourcePathStringPrefix);
                    }
                } else // 
                // 
                // Simple PC file:
                // ---------------
                // Add PC file name ("leaf" of the PC path) to get file path to the PC file to be copied
                {
                    if (!nextPcFile.contains(pcFileSep + ".")) {
                        // Copy from PC file to IFS file (that will be created given the new path name)
                        msgTextDir = copyFromPcFile(nextPcFile, ifsNewPath.toString(), fromWalk);
                        if (!msgTextDir.isEmpty()) {
                            atLeastOneErrorInFiles = true;
                        }
                        // Add a message in the message table and show it
                        if (atLeastOneErrorInFiles) {
                            row = "Comp: PC file  " + nextPcFile + "  was NOT copied to IFS directory  " + ifsNewPath.toString() + ".";
                        } else {
                            row = "Comp: PC file  " + nextPcFile + "  was copied to IFS directory  " + ifsNewPath.toString() + ".";
                        }
                    }
                }
            });
            msgText = atLeastOneErrorInFiles ? "ERROR" : "";
        }
    } catch (Exception exc) {
        exc.printStackTrace();
        row = "Error PC files to IFS: " + exc.toString();
        mainWindow.msgVector.add(row);
        mainWindow.showMessages();
    }
    return msgText;
}
Also used : Path(java.nio.file.Path) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IFSFile(com.ibm.as400.access.IFSFile)

Example 15 with IFSFile

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

the class CreateAndDeleteInIBMi method walkIfsDirectory_DeleteNestedDirectories.

/**
 * Walk through IFS directory recursively to delete nested directories and
 * files.
 *
 * @param ifsPathString
 */
protected void walkIfsDirectory_DeleteNestedDirectories(String ifsPathString) {
    // Create IFSFile object representing an IFS object (directory or file)
    IFSFile ifsDirectory = new IFSFile(remoteServer, ifsPathString);
    try {
        // Get list of objects in the current directory
        IFSFile[] inObjects = ifsDirectory.listFiles();
        // First delete files in all nested directories walking through directories (going into recursion)
        for (IFSFile inObject : inObjects) {
            String inPathName = inObject.toString();
            try {
                // - delete the file if it exists
                if (!inObject.isDirectory()) {
                    if (inObject.exists()) {
                        row = "Info: Deleting IFS file " + inObject + ".";
                        mainWindow.msgVector.add(row);
                        mainWindow.showMessages();
                        inObject.delete();
                    }
                }
                // - call this method recursively to delete remaining files in all nested directories
                if (inObject.isDirectory()) {
                    // Recursive call with different IFS path
                    walkIfsDirectory_DeleteNestedDirectories(inPathName);
                }
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
        // After deleting files delete all directories (going back from recursion)
        row = "Info: Deleting IFS directory " + ifsDirectory + ".";
        mainWindow.msgVector.add(row);
        mainWindow.showMessages();
        ifsDirectory.delete();
    } catch (Exception exc) {
        exc.printStackTrace();
    }
}
Also used : IFSFile(com.ibm.as400.access.IFSFile)

Aggregations

IFSFile (com.ibm.as400.access.IFSFile)44 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)14 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)14 AS400Text (com.ibm.as400.access.AS400Text)11 CommandCall (com.ibm.as400.access.CommandCall)9 AS400Message (com.ibm.as400.access.AS400Message)8 Path (java.nio.file.Path)7 AS400FileRecordDescription (com.ibm.as400.access.AS400FileRecordDescription)5 IFSFileInputStream (com.ibm.as400.access.IFSFileInputStream)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 Point (java.awt.Point)4 PatternSyntaxException (java.util.regex.PatternSyntaxException)4 IFSFileOutputStream (com.ibm.as400.access.IFSFileOutputStream)3 DecimalFormat (java.text.DecimalFormat)3 CannotRedoException (javax.swing.undo.CannotRedoException)3 CannotUndoException (javax.swing.undo.CannotUndoException)3 BufferedWriter (java.io.BufferedWriter)2