Search in sources :

Example 26 with AS400

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

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

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

Example 29 with AS400

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

the class Copy_IBMi_PC method copyFromSaveFile.

/**
 * Copy Save File to PC directory or PC file as .savf type.
 *
 * @param remoteServer
 * @param as400PathString
 * @param pcPathString
 * @return
 */
protected String copyFromSaveFile(AS400 remoteServer, String as400PathString, String pcPathString) {
    System.out.println("as400PathString: " + as400PathString);
    AS400FTP ftp = new AS400FTP(remoteServer);
    String filePathString;
    String directoryOrFile;
    try {
        // Get fileName value from the IFS path string
        extractNamesFromIfsPath(as400PathString);
        // 
        if (Files.isDirectory(Paths.get(pcPathString))) {
            filePathString = pcPathString + pcFileSep + saveFileName + ".savf";
            directoryOrFile = "directory";
        } else {
            filePathString = pcPathString;
            directoryOrFile = "file";
        }
        if (!Files.exists(Paths.get(filePathString))) {
            Files.createFile(Paths.get(filePathString));
        } else {
            if (!filePathString.endsWith(".savf")) {
                row = "Error: Save file  " + libraryName + "/" + saveFileName + "  cannot be coppied to the PC file  " + filePathString + ".  Target file name must end with suffix .savf.";
                mainWindow.msgVector.add(row);
                mainWindow.showMessages(noNodes);
                return "ERROR";
            }
        }
        // Binary data transfer
        ftp.setDataTransferType(AS400FTP.BINARY);
        // Get command
        ftp.get(as400PathString, filePathString);
        ftp.disconnect();
        row = "Comp: Save file  " + libraryName + "/" + saveFileName + "  was copied to PC " + directoryOrFile + " " + pcPathString + ".";
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(nodes);
        return "";
    } catch (Exception exc) {
        exc.printStackTrace();
        row = "Error: Copying save file  " + libraryName + "/" + saveFileName + "  -  " + exc.toString() + ".";
        mainWindow.msgVector.add(row);
        mainWindow.showMessages(noNodes);
        return "ERROR";
    }
}
Also used : AS400FTP(com.ibm.as400.access.AS400FTP) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException)

Example 30 with AS400

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

the class MainWindow method connectReconnect.

/**
 */
protected boolean connectReconnect() {
    // Set wait-cursor (rotating wheel?)
    // setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    // Keeps the scroll pane at the LAST MESSAGE.
    scrollMessagePane.getVerticalScrollBar().addAdjustmentListener(messageScrollPaneAdjustmentListenerMax);
    // *****
    // ========
    // ======================================== Connetion to the server
    // 
    // Get connection to the IBM i SERVER.
    // The third parameter (password) should NOT be specified. The user must sign on.
    remoteServer = new AS400(hostTextField.getText(), userNameTextField.getText());
    // Connect FILE service of the IBM i server.
    try {
        // Introductory message - waiting for the server.
        row = "Wait: Connecting to server  " + properties.getProperty("HOST") + " . . .";
        msgVector.add(row);
        // Reload LEFT side. Do not use Right side! It would enter a loop.
        showMessages(noNodes);
        remoteServer.connectService(AS400.FILE);
        SystemValue sysVal = new SystemValue(remoteServer, "QCCSID");
        row = "Info: System value QCCSID is " + sysVal.getValue() + ".";
        msgVector.add(row);
        // Reload LEFT side. Do not use Right side! It would enter a loop.
        showMessages(noNodes);
        try {
            infile = Files.newBufferedReader(parPath, Charset.forName(encoding));
            properties.load(infile);
            infile.close();
            properties.setProperty("LIBRARY_PATTERN", libraryPatternTextField.getText());
            properties.setProperty("FILE_PATTERN", filePatternTextField.getText());
            properties.setProperty("MEMBER_PATTERN", memberPatternTextField.getText());
            outfile = Files.newBufferedWriter(parPath, Charset.forName(encoding));
            properties.store(outfile, PROP_COMMENT);
            outfile.close();
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    } catch (Exception exc) {
        exc.printStackTrace();
        row = "Error: Connection to server  " + properties.getProperty("HOST") + "  failed.  -  " + exc.toString();
        msgVector.add(row);
        showMessages(noNodes);
        // Change cursor to default
        setCursor(Cursor.getDefaultCursor());
        // Remove setting last element of messages
        scrollMessagePane.getVerticalScrollBar().removeAdjustmentListener(messageScrollPaneAdjustmentListenerMax);
        return false;
    }
    // 
    // ================================= End of connection to the server
    // =======
    // *****
    // Show completion message when connection to IBM i server connected.
    row = "Comp: Server IBM i  " + properties.getProperty("HOST") + "  has been connected to user  " + remoteServer.getUserId() + " and is retrieving the Integrated File System.";
    msgVector.add(row);
    showMessages(noNodes);
    // Change cursor to default
    setCursor(Cursor.getDefaultCursor());
    // Remove setting last element of messages
    scrollMessagePane.getVerticalScrollBar().removeAdjustmentListener(messageScrollPaneAdjustmentListenerMax);
    // Check connection and keep connection alive in background.
    chkConn = new CheckConnection(remoteServer);
    chkConn.execute();
    return true;
}
Also used : SystemValue(com.ibm.as400.access.SystemValue) AS400(com.ibm.as400.access.AS400) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) IllegalCharsetNameException(java.nio.charset.IllegalCharsetNameException) IOException(java.io.IOException)

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