Search in sources :

Example 11 with AS400

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

the class Copy_IBMi_IBMi method copyFromSourceMember.

/**
 * Copy Source member to Source file or Library.
 *
 * @param remoteServer
 * @param sourcePathString
 * @param targetPathString
 * @return
 */
protected String copyFromSourceMember(AS400 remoteServer, String sourcePathString, String targetPathString) {
    msgText = "";
    // Get object names from source path string: qsyslib, library, file,
    // member.
    extractNamesFromIfsPath(sourcePathString);
    // Save the object names for command "from" parameters
    String inLibName = libraryName;
    String inFileName = fileName;
    String inMbrName = memberName;
    // Build new member name appended by source type
    String typedMemberName = inMbrName;
    String sourceType;
    if (properties.get("SOURCE_TYPE").equals("*DEFAULT")) {
        // Get default source type for standard source physical file name (QCLSRC, QRPGLESRC, ...)
        sourceType = getDefaultSourceType(fileName);
    } else {
        // Get source type from combo box
        sourceType = (String) properties.get("SOURCE_TYPE");
    }
    // Add the source type to member name
    typedMemberName += "." + sourceType;
    // Create source file path
    IFSFile sourcePath = new IFSFile(remoteServer, sourcePathString);
    // Create target file path
    IFSFile targetPath = new IFSFile(remoteServer, targetPathString);
    try {
        // Enable calling CL commands
        CommandCall cmdCall = new CommandCall(remoteServer);
        String newTargetPathString = targetPathString;
        // ------------------------
        if (targetPath.isSourcePhysicalFile()) {
            // For both Source file or member, CPYSRCPF command is used.
            // Get object names from target path string for command "to"
            // parameters
            extractNamesFromIfsPath(targetPathString);
            // Target is a directory (source file)
            if (targetPath.isDirectory()) {
                // If target is IFS directory, the new file path will be:
                // directory + typed member name
                newTargetPathString = targetPathString + "/" + inMbrName + ".MBR";
            // Target is file (member)
            } else {
                // If target is IFS file, the new file path will be:
                // file's directory (prefix up to last "/") + typed member name
                newTargetPathString = targetPathString;
            }
            // Check if member names are equal and overwriting data is allowed
            targetPath = new IFSFile(remoteServer, newTargetPathString);
            if (targetPath.exists() && !overwriteAllowed) {
                // IFS file exists and overwriting data is NOT allowed
                row = "Error: Source member " + inLibName + "/" + inFileName + "(" + inMbrName + ") " + "cannot be copied source member  " + libraryName + "/" + fileName + "(" + memberName + ") . Overwriting files is not allowed.";
                mainWindow.msgVector.add(row);
                mainWindow.showMessages(nodes);
                return "ERROR";
            }
            // 
            // Copy Source Physical File command
            // ---------------------------------
            String command_CPYSRCF = "CPYSRCF FROMFILE(" + inLibName + "/" + inFileName + ") " + "TOFILE(" + libraryName + "/" + fileName + ") FROMMBR(" + inMbrName + ") TOMBR(" + memberName + ") MBROPT(*REPLACE)";
            // Perform the command
            cmdCall.run(command_CPYSRCF);
            int sourceCcsid = sourcePath.getCCSID();
            sourceCcsidStr = String.valueOf(sourceCcsid);
            int targetCcsid = targetPath.getCCSID();
            targetCcsidStr = String.valueOf(targetCcsid);
            // 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: Copy source member  " + inLibName + "/" + inFileName + "(" + inMbrName + ")  using command CPYSRCF   -  " + as400Message.getID() + " " + as400Message.getText();
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                    return "ERROR";
                } else {
                    row = "Info: Copy source member  " + inLibName + "/" + inFileName + "(" + inMbrName + ")  using command CPYSRCF  -  " + as400Message.getID() + " " + as400Message.getText();
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages();
                }
            }
            row = "Info: Source member " + inLibName + "/" + inFileName + "(" + inMbrName + ") was copied to source file  " + libraryName + "/" + fileName + "(" + memberName + "). Convert " + sourceCcsidStr + " -> " + targetCcsidStr + ".";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages(nodes);
            return "";
        } else {
            if (targetPath.isDirectory()) {
                // To directory
                // ------------
                // If target is IFS directory, the new file path will be:
                // directory + typed member name
                newTargetPathString = targetPathString + "/" + typedMemberName;
            // To file
            // -------
            } else {
                // If target is IFS file, the new file path will be:
                // file's directory (prefix up to last "/") + typed member name
                newTargetPathString = targetPathString.substring(0, targetPathString.lastIndexOf("/")) + "/" + typedMemberName;
            }
        }
        // For both directory and file continue.
        // ---------------------------
        targetPath = new IFSFile(remoteServer, newTargetPathString);
        // Check if overwriting data is allowed
        if (targetPath.exists() && !overwriteAllowed) {
            // IFS file exists and overwriting data is NOT allowed
            row = "Error: Source member " + libraryName + "/" + fileName + "(" + typedMemberName + ") cannot be copied to IFS directory " + targetPathString + ". Overwriting files is not allowed.";
            mainWindow.msgVector.add(row);
            mainWindow.showMessages(nodes);
            return "ERROR";
        }
        // 
        // Copy source member to IFS file command
        // ------------------------------
        String commandText = "CPYTOSTMF FROMMBR('" + sourcePathString + "') TOSTMF('" + newTargetPathString + "') STMFOPT(*REPLACE) " + "CVTDTA(*AUTO) STMFCCSID(*STMF) ENDLINFMT(*LF)";
        // Perform the command
        cmdCall.run(commandText);
        // Obtain CCSID attribute of the target IFS file
        // targetPath = new IFSFile(remoteServer, newTargetPathString);
        int sourceCcsid = sourcePath.getCCSID();
        sourceCcsidStr = String.valueOf(sourceCcsid);
        int targetCcsid = 0;
        if (targetPath.exists()) {
            // CCSID attribute of IFS file
            targetCcsid = targetPath.getCCSID();
        } else {
            // CCSID attribute of source file
            targetCcsid = sourcePath.getCCSID();
        }
        targetCcsidStr = String.valueOf(targetCcsid);
        // 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: Copy source member using command CPYTOSTMF to IFS file with CCSID " + targetCcsidStr + ".  -  " + as400Message.getID() + " " + as400Message.getText();
                mainWindow.msgVector.add(row);
                mainWindow.showMessages();
                return "ERROR";
            } else {
                row = "Info: Copy source member using command CPYTOSTMF to IFS file with CCSID " + targetCcsidStr + ".  -  " + as400Message.getID() + " " + as400Message.getText();
                mainWindow.msgVector.add(row);
                mainWindow.showMessages();
            }
        }
        // Positive completion message
        row = "Comp: Source member  " + sourcePathString + "  with CCSID " + sourceCcsidStr + " was copied to IFS file  " + newTargetPathString + "  with CCSID attribute " + targetCcsidStr + ".";
        mainWindow.msgVector.add(row);
        mainWindow.showMessages();
    } catch (Exception exc) {
        exc.printStackTrace();
        row = "Error: Copy source member using command CPYTOSTMF to IFS file with CCSID " + targetCcsidStr + ".  -  " + exc.toString();
        mainWindow.msgVector.add(row);
        mainWindow.showMessages();
    }
    return msgText;
}
Also used : CommandCall(com.ibm.as400.access.CommandCall) AS400Message(com.ibm.as400.access.AS400Message) IFSFile(com.ibm.as400.access.IFSFile)

Example 12 with AS400

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

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

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

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

the class DisplayFile method displayIfsFile.

/**
 * Display contents of the IFS file using its CCSID attribute
 *
 * @param remoteServer
 * @param ifsFilePathString
 */
protected void displayIfsFile(AS400 remoteServer, String ifsFilePathString) {
    this.setTitle("Display IFS file  '" + ifsFilePathString + "'");
    // The user can correct the parameter "IBMi CCSID" and try again.
    try {
        IFSFile ifsFile = new IFSFile(remoteServer, ifsFilePathString);
        int attributeCCSID = ifsFile.getCCSID();
        characterSetLabel.setText("CCSID " + attributeCCSID + " was used for display.");
        byte[] inputBuffer = new byte[100000];
        byte[] workBuffer = new byte[100000];
        try (IFSFileInputStream inputStream = new IFSFileInputStream(remoteServer, ifsFilePathString)) {
            int bytesRead = inputStream.read(inputBuffer);
            while (bytesRead != -1) {
                for (int idx = 0; idx < bytesRead; idx++) {
                    // Copy input byte to output byte
                    workBuffer[idx] = inputBuffer[idx];
                }
                // Copy the printable part of the work array to a new buffer that will be written out.
                byte[] bufferToWrite = new byte[bytesRead];
                // Copy bytes from the work buffer to the new buffer
                for (int indx = 0; indx < bytesRead; indx++) {
                    bufferToWrite[indx] = workBuffer[indx];
                }
                // Create object for conversion from bytes to characters
                AS400Text textConverter = new AS400Text(bytesRead, attributeCCSID, remoteServer);
                // Convert byte array buffer to text line
                String textLine = (String) textConverter.toObject(bufferToWrite);
                // Append the line to text area
                textArea.append(textLine + NEW_LINE);
                // Read next input buffer
                bytesRead = inputStream.read(inputBuffer);
            }
            // Set scroll bar to top
            textArea.setCaretPosition(0);
            // Display the window.
            setVisible(true);
            row = "Info: IFS file  " + ifsFilePathString + "  has CCSID  " + attributeCCSID + ".";
            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 : AS400Text(com.ibm.as400.access.AS400Text) Point(java.awt.Point) PatternSyntaxException(java.util.regex.PatternSyntaxException) BadLocationException(javax.swing.text.BadLocationException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) IFSFile(com.ibm.as400.access.IFSFile) IFSFileInputStream(com.ibm.as400.access.IFSFileInputStream)

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