Search in sources :

Example 36 with IFSFile

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

the class Copy_IBMi_PC method copyDataFromMemberToFile.

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

Example 37 with IFSFile

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

the class Copy_IBMi_PC method walkIfsDirectory_CreateNestedPcDirectories.

/**
 * Walk through IFS directory recursively to create shadow directories in PC
 * target directory; Shadow directories are named by last names of the IFS
 * directory paths so that only one-level directories are inserted to the PC
 * target directory.
 *
 * @param ifsDirectory IFS directory path
 * @param pcDirPathString Target PC directory name
 * @return
 */
protected String walkIfsDirectory_CreateNestedPcDirectories(IFSFile ifsDirectory, String pcDirPathString) {
    try {
        // Get list of objects in the IFS directory that may be directories and single files.
        // Here we process directories only.
        IFSFile[] objectList = ifsDirectory.listFiles();
        // Process only non-empty directory
        if (objectList.length > 0) {
            for (IFSFile subDirectory : objectList) {
                // Only IFS sub-directories are processed
                if (subDirectory.isDirectory()) {
                    // Newly created PC directory path is built as
                    // PC directory path string from parameter  plus
                    // the last part (leaf) of the subDirectory path
                    String newPcDirectoryPathString = pcDirPathString + pcFileSep + subDirectory.getName();
                    // Create the new nested PC directory if it does not exist
                    if (!Files.exists(Paths.get(newPcDirectoryPathString))) {
                        Files.createDirectory(Paths.get(newPcDirectoryPathString));
                        row = "Info: PC directory  " + newPcDirectoryPathString + "  was created.";
                        mainWindow.msgVector.add(row);
                        mainWindow.showMessages(nodes);
                    }
                    // Recursive call with IFS sub-directory and new PC path (parent of the new PC directory)
                    walkIfsDirectory_CreateNestedPcDirectories(subDirectory, newPcDirectoryPathString);
                }
            }
        }
        return "";
    } catch (Exception exc) {
        exc.printStackTrace();
        return "ERROR";
    }
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IFSFile(com.ibm.as400.access.IFSFile)

Example 38 with IFSFile

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

the class Copy_IBMi_PC method copyFromSourceFile.

/**
 * Copy Source File (all members) to PC directory.
 *
 * @param remoteServer
 * @param as400PathString
 * @param pcPathString
 * @return
 */
@SuppressWarnings("UseSpecificCatch")
protected String copyFromSourceFile(AS400 remoteServer, String as400PathString, String pcPathString) {
    // Extract individual names (library, file, member) from the AS400 IFS path
    extractNamesFromIfsPath(as400PathString);
    // Path to the input source file
    String inSourceFilePath = "/QSYS.LIB/" + libraryName + ".LIB/" + fileName + ".FILE";
    try {
        IFSFile ifsDirectory = new IFSFile(remoteServer, inSourceFilePath);
        // from Source Physical Files only
        if (ifsDirectory.isSourcePhysicalFile()) {
            // to PC directory only
            if (Files.isDirectory(Paths.get(pcPathString))) {
                String pcDirectoryName = pcPathString.substring(pcPathString.lastIndexOf(pcFileSep) + 1);
                // Create NEW directory with the Source Physical File name.
                if (!pcDirectoryName.equals(fileName)) {
                    pcPathString = pcPathString + pcFileSep + fileName;
                    try {
                        Files.createDirectory(Paths.get(pcPathString));
                    } catch (Exception dir) {
                        dir.printStackTrace();
                        row = "Error: Creating new PC directory  " + pcPathString + "  -  " + dir.toString();
                        mainWindow.msgVector.add(row);
                        mainWindow.showMessages(noNodes);
                        return "ERROR";
                    }
                }
                // If the PC directory has the same name as Source Physical File - NO new directory is created and processing continues.
                // -------------------------------------
                // Copy members to the PC directory
                boolean atLeastOneErrorInMembers = false;
                IFSFile[] ifsFiles = ifsDirectory.listFiles();
                for (IFSFile ifsFile : ifsFiles) {
                    // Insert new or rewrite existing file in PC directory
                    String msgTextMbr = copyFromSourceMember(remoteServer, ifsFile.toString(), pcPathString + pcFileSep + ifsFile.getName());
                    // If at least one message is not empty - note error
                    if (!msgTextMbr.isEmpty()) {
                        atLeastOneErrorInMembers = true;
                    }
                }
                if (atLeastOneErrorInMembers) {
                    row = "Comp: Source physical file  " + libraryName + "/" + fileName + "  was copied to PC directory  " + pcPathString + ".";
                } else {
                    row = "Error: Source physical file  " + libraryName + "/" + fileName + "  was NOT completely copied to PC directory  " + pcPathString + ".";
                }
                msgText = atLeastOneErrorInMembers ? "ERROR" : "";
            }
        }
        return msgText;
    } catch (Exception exc) {
        exc.printStackTrace();
        row = "Error: Copying from source physical file  " + libraryName + "/" + fileName + "  -  " + exc.toString();
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(noNodes);
        return "ERROR";
    }
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IFSFile(com.ibm.as400.access.IFSFile)

Example 39 with IFSFile

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

the class Copy_IBMi_PC method copyToPcDirectory.

/**
 * Copy IBM i IFS directory/file or Source file/member or Save file
 * to PC directory;
 * If the output PC file does not exist, one is created.
 *
 * @param as400PathString
 * @param pcPathString
 * @param ifsPathStringPrefix
 * @return
 */
@SuppressWarnings("UseSpecificCatch")
protected String copyToPcDirectory(String as400PathString, String pcPathString, String ifsPathStringPrefix) {
    extractNamesFromIfsPath(as400PathString);
    IFSFile ifsPath = new IFSFile(remoteServer, as400PathString);
    if (pcPathString == null) {
    // Alert - set target!
    }
    sourcePathString = ifsPath.getPath();
    try {
        // ---------------
        if (sourcePathString.startsWith("/QSYS.LIB/")) {
            if (ifsPath.isDirectory()) {
                // --------------------
                if (ifsPath.isSourcePhysicalFile()) {
                    msgText = copyFromSourceFile(remoteServer, sourcePathString, pcPathString);
                    if (msgText.isEmpty()) {
                        row = "Comp: Source physical file  " + libraryName + "/" + fileName + "  was copied to PC directory  " + pcPathString + ".";
                        mainWindow.msgVector.add(row);
                        mainWindow.showMessages(nodes);
                    } else {
                        row = "Comp: Source physical file  " + libraryName + "/" + fileName + "  was NOT completely copied to PC directory  " + pcPathString + ".";
                        mainWindow.msgVector.add(row);
                        mainWindow.showMessages(noNodes);
                    }
                } else if (sourcePathString.endsWith(".LIB")) {
                    // Library to PC directory/file:
                    // -------
                    row = "Error: IBM i library  " + libraryName + "  cannot be copied to PC. Only files from the library can be copied.";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(noNodes);
                    msgText = "ERROR";
                }
                return msgText;
            } else if (sourcePathString.endsWith(".MBR")) {
                // Member of Source Physical File to PC file:
                // ------
                msgText = copyFromSourceMember(remoteServer, sourcePathString, pcPathString);
                if (msgText.isEmpty()) {
                    row = "Comp: Source member  " + libraryName + "/" + fileName + "(" + memberName + ")  was copied to PC directory  " + pcPathString + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(nodes);
                } else {
                    row = "Comp: Source member  " + libraryName + "/" + fileName + "(" + memberName + ")  was NOT copied to PC directory  " + pcPathString + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(noNodes);
                }
                return msgText;
            } else if (sourcePathString.endsWith(".SAVF")) {
                // Save File to PC directory/file:
                // ---------
                copyFromSaveFile(remoteServer, sourcePathString, pcPathString);
                return msgText;
            }
        } else // 
        // 
        // IFS (Integrated File System):
        // -----------------------------
        // Path prefix is the leading part of the path up to and including the last slash:
        // ifsPathStringPrefix = sourcePathString.substring(0, sourcePathString.indexOf(ifsPath.getName()));
        {
            if (ifsPath.isDirectory()) {
                // --------------
                try {
                    // Create the first shadow directory in PC target directory.
                    // The name of the directory is the IFS path name without the path prefix.
                    pcPathString = pcPathString + pcFileSep + ifsPath.toString().substring(ifsPathStringPrefix.length());
                    if (!Files.exists(Paths.get(pcPathString))) {
                        Files.createDirectories(Paths.get(pcPathString));
                        row = "Info: PC directory  " + pcPathString + "  was created.";
                        mainWindow.msgVector.add(row);
                        mainWindow.showMessages(nodes);
                        msgText = "";
                    }
                } catch (Exception exc) {
                    msgText = "ERROR";
                    exc.printStackTrace();
                    row = "Error: Copying IFS directory  " + sourcePathString + "  to PC directory  " + pcPathString + "  -  " + exc.toString() + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(noNodes);
                    // Fatal error - no continuation is possible
                    return "ERROR";
                }
                // Create parameter for the next method call
                IFSFile ifsDirectory = new IFSFile(remoteServer, sourcePathString);
                // Create nested shadow directories in PC target directory
                msgText = walkIfsDirectory_CreateNestedPcDirectories(ifsDirectory, pcPathString);
                // Copy IFS files to appropriate PC shadow directories
                msgText = copyIfsFilesToPcDirectories(ifsDirectory, pcPathString, ifsPathStringPrefix);
                if (msgText.isEmpty()) {
                    row = "Comp: IFS directory  " + sourcePathString + "  was copied to PC directory  " + pcPathString + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(nodes);
                } else {
                    row = "Comp: IFS directory  " + sourcePathString + "  was NOT completely copied to PC directory  " + pcPathString + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(noNodes);
                }
                return msgText;
            } else // 
            // 
            // IFS stream file: to PC directory
            // ----------------
            {
                IFSFile ifsFile = new IFSFile(remoteServer, sourcePathString);
                // If the output PC file does not exist - create an empty file and continue.
                // ------------------------------------
                // PC file = PC direcrory + IFS file
                String pcFilePathString = pcPathString + pcFileSep + ifsFile.getName();
                Path pcFilePath = Paths.get(pcPathString);
                // If the file does not exist, create one.
                if (Files.notExists(pcFilePath)) {
                    Files.createFile(pcFilePath);
                }
                // Copy the IFS file to PC file
                msgText = copyToPcFile(ifsFile.toString(), pcFilePathString, notFromWalk);
                if (msgText.isEmpty()) {
                    row = "Comp: IFS file  " + sourcePathString + "  was copied to PC directory  " + pcPathString + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(nodes);
                } else {
                    row = "Comp: IFS file  " + sourcePathString + "  was NOT copied to PC directory  " + pcPathString + ".";
                    mainWindow.msgVector.add(row);
                    mainWindow.showMessages(noNodes);
                }
                return msgText;
            }
        }
        return "";
    } catch (Exception exc) {
        exc.printStackTrace();
        row = "Error: Copying  " + sourcePathString + "  to  " + pcPathString + "  -  " + exc.toString() + ".";
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(noNodes);
        return "ERROR";
    }
}
Also used : Path(java.nio.file.Path) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IFSFile(com.ibm.as400.access.IFSFile)

Example 40 with IFSFile

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

the class Copy_IBMi_PC method copyIfsFilesToPcDirectories.

/**
 * Copying AS400 IFS files to PC directories created before (see
 * walkIfsDirectory_CreateNestedPcDirectories method).
 *
 * @param ifsPath IFS directory path
 * @param pcDirPathString Target PC directory name
 * @param ifsPathStringPrefix
 * @return
 */
@SuppressWarnings("UseSpecificCatch")
protected String copyIfsFilesToPcDirectories(IFSFile ifsPath, String pcDirPathString, String ifsPathStringPrefix) {
    String msgTextDir;
    boolean atLeastOneErrorInFiles = false;
    try {
        IFSFile[] objectList = ifsPath.listFiles();
        if (objectList.length != 0) {
            for (IFSFile ifsDirFile : objectList) {
                String newDirPathString = pcDirPathString + pcFileSep + ifsDirFile.getName();
                // IFS directory
                if (ifsDirFile.isDirectory()) {
                    // Recursive call with different parameter values
                    copyIfsFilesToPcDirectories(ifsDirFile, newDirPathString, ifsPathStringPrefix);
                } else // 
                // Single IFS file
                {
                    if (ifsDirFile.isFile()) {
                        ifsPathStringPrefix = ifsDirFile.toString().substring(0, ifsDirFile.toString().lastIndexOf("/"));
                        // Append
                        String newFilePathString = pcDirPathString + ifsDirFile.toString().substring(ifsPathStringPrefix.length());
                        // Copy the IFS file to PC directory created before
                        msgTextDir = copyToPcFile(ifsDirFile.toString(), newFilePathString, fromWalk);
                        if (!msgTextDir.isEmpty()) {
                            atLeastOneErrorInFiles = true;
                        }
                    /*                     
                     if (atLeastOneErrorInFiles) {
                        row = "Comp: IFS file  " + ifsDirFile.toString() + "  was copied to PC directory  " + newFilePathString + ".";
                     } else {
                        //row = "Error: IFS file  " + ifsDirFile.toString() + "  was NOT copied to PC directory  " + newFilePathString + ".";
                     }
                     mainWindow.msgVector.add(row);
                             */
                    }
                }
            }
            msgText = atLeastOneErrorInFiles ? "ERROR" : "";
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    return msgText;
}
Also used : IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) 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