Example usage for org.apache.commons.net.tftp TFTP BINARY_MODE

List of usage examples for org.apache.commons.net.tftp TFTP BINARY_MODE

Introduction

In this page you can find the example usage for org.apache.commons.net.tftp TFTP BINARY_MODE.

Prototype

int BINARY_MODE

To view the source code for org.apache.commons.net.tftp TFTP BINARY_MODE.

Click Source Link

Document

The binary transfer mode.

Usage

From source file:TFTPExample.java

public static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;/*from w  w w.  ja  v  a2s.c  om*/

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];
        if (arg.startsWith("-")) {
            if (arg.equals("-r")) {
                receiveFile = true;
            } else if (arg.equals("-s")) {
                receiveFile = false;
            } else if (arg.equals("-a")) {
                transferMode = TFTP.ASCII_MODE;
            } else if (arg.equals("-b")) {
                transferMode = TFTP.BINARY_MODE;
            } else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else {
            break;
        }
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    tftp = new TFTPClient();

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(60000);

    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        System.err.println("Error: could not open local UDP socket.");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        FileOutputStream output = null;
        File file;

        file = new File(localFilename);

        // If file exists, don't overwrite it.
        if (file.exists()) {
            System.err.println("Error: " + localFilename + " already exists.");
            System.exit(1);
        }

        // Try to open local file for writing
        try {
            output = new FileOutputStream(file);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for writing.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to receive remote file via TFTP
        try {
            tftp.receiveFile(remoteFilename, transferMode, output, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while receiving file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and output file
            tftp.close();
            try {
                if (output != null) {
                    output.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }

    } else {
        // We're sending a file
        FileInputStream input = null;

        // Try to open local file for reading
        try {
            input = new FileInputStream(localFilename);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for reading.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to send local file via TFTP
        try {
            tftp.sendFile(remoteFilename, transferMode, input, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while sending file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and input file
            tftp.close();
            try {
                if (input != null) {
                    input.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }
    }
}

From source file:com.xiangzhurui.util.ftp.TFTPExample.java

public static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;//  w w w.j  ava2  s  .  c om

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];
        if (arg.startsWith("-")) {
            if (arg.equals("-r")) {
                receiveFile = true;
            } else if (arg.equals("-s")) {
                receiveFile = false;
            } else if (arg.equals("-a")) {
                transferMode = TFTP.ASCII_MODE;
            } else if (arg.equals("-b")) {
                transferMode = TFTP.BINARY_MODE;
            } else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else {
            break;
        }
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    tftp = new TFTPClient();

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(60000);

    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        System.err.println("Error: could not open local UDP socket.");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        FileOutputStream output = null;
        File file;

        file = new File(localFilename);

        // If file exists, don't overwrite it.
        if (file.exists()) {
            System.err.println("Error: " + localFilename + " already exists.");
            System.exit(1);
        }

        // Try to open local file for writing
        try {
            output = new FileOutputStream(file);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for writing.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to receive remote file via TFTP
        try {
            tftp.receiveFile(remoteFilename, transferMode, output, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while receiving file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and output file
            tftp.close();
            try {
                if (output != null) {
                    output.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }

    } else {
        // We're sending a file
        FileInputStream input = null;

        // Try to open local file for reading
        try {
            input = new FileInputStream(localFilename);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for reading.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to send local file via TFTP
        try {
            tftp.sendFile(remoteFilename, transferMode, input, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while sending file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and input file
            tftp.close();
            try {
                if (input != null) {
                    input.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }

    }

}

From source file:com.cablelabs.fsm.AutoProvState.java

private String autoGenerate(int msgIndexQueue) {
    Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
    Properties dut = SystemSettings.getSettings(SettingConstants.DUT);
    Boolean autoProv = SystemSettings.getBooleanSetting(SettingConstants.AUTO_GENERATE);
    Boolean autoGen = SystemSettings.getBooleanSetting(SettingConstants.AUTO_PROVISION);
    if (autoProv && autoGen) {
        if (pd != null && platform != null && dut != null) {
            String pcscfLabel = dut.getProperty(SettingConstants.PCSCF);
            String macAddr = dut.getProperty(SettingConstants.MAC_ADDRESS);
            String tftpIP = platform.getProperty(SettingConstants.TFTP_SERVER_IP);
            String tftpPort = platform.getProperty(SettingConstants.TFTP_SERVER_PORT);
            String phone1 = dut.getProperty(SettingConstants.PHONE_NUMBER_1);
            String phone2 = dut.getProperty(SettingConstants.PHONE_NUMBER_2);
            String cw = platform.getProperty(SettingConstants.CW_NUMBER);
            if (macAddr != null && pcscfLabel != null && tftpIP != null && tftpPort != null && cw != null) {

                // Next verify the port is not set to zero
                try {
                    int port = Integer.parseInt(tftpPort);
                    if (port > 0 && port <= 65535) {

                        // Next make sure the TFTP Server IP is not set to 0.0.0.0
                        if (tftpIP.equals("0.0.0.0")) {
                            logger.warn(PC2LogCategory.PCSim2, subCat,
                                    "The TFTP Server IP setting in the platform file is not valid. Ending auto generate operation.");
                            return null;
                        }// www. j  a  va 2 s.  c om

                        File input = new File(SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                + SettingConstants.CW + cw + File.separator + pd.getProvFileName());
                        if (input != null) {
                            ProvGen pg = new ProvGen(input);
                            if (phone1 != null)
                                pg.changePhoneNum(SettingConstants.AUTO_GENERATE_PHONE_NUMBER_1, phone1);
                            if (phone2 != null)
                                pg.changePhoneNum(SettingConstants.AUTO_GENERATE_PHONE_NUMBER_2, phone2);
                            Properties pcscf = SystemSettings.getSettings(pcscfLabel);
                            if (pcscf != null) {
                                String pcscfIP = pcscf.getProperty(SettingConstants.IP);
                                if (pcscfIP != null)
                                    pg.changePCSCF(pcscfIP);
                            }
                            String newFileName = macAddr + ".bin";
                            if (pg.output(SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                    + SettingConstants.CW + cw + File.separator + newFileName)) {
                                // Test system
                                //File output = new File(SettingConstants.AUTO_PROV_FILE_DIRECTORY + newFileName);
                                //File pact = new File(SettingConstants.AUTO_PROV_FILE_DIRECTORY + "chinmaya_base_ph1_pcscf.bin");
                                //pg.compare(pact, output);
                                // Create a data entry of the issued event
                                //ProvisioningData issuePD = new ProvisioningData(macAddr, pd.getPolicyFileName(), newFileName);
                                logger.info(PC2LogCategory.FSM, subCat,
                                        "AutoProvState beginning to TFTP the new provisioning file.");

                                // Next we need to TFTP the file to the server
                                TFTPClient client = new TFTPClient();
                                File binFile = new File(
                                        SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                                + SettingConstants.CW + cw + File.separator + newFileName);
                                if (binFile.isFile() && binFile.canRead()) {
                                    FileInputStream istrm = new FileInputStream(binFile);
                                    //InetAddress ia = InetAddress.getByName("10.4.1.37");
                                    client.open(); // client.open(20003, ia);
                                    client.sendFile(newFileName, TFTP.BINARY_MODE, istrm, tftpIP, port);
                                    client.close();
                                    logger.info(PC2LogCategory.FSM, subCat,
                                            "TFTP of the new provisioning file is complete.");
                                    super.processPrelude(msgIndexQueue);
                                } else {
                                    logger.warn(PC2LogCategory.FSM, subCat,
                                            "The " + macAddr + ".bin doesn't appear in the "
                                                    + SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                                    + SettingConstants.CW + cw
                                                    + " Ending auto generate operation.");
                                }
                            } else {
                                logger.error(PC2LogCategory.FSM, subCat,
                                        "AutoProvState could not locate provisioning template file["
                                                + input.getAbsolutePath() + "].");
                            }
                        }
                        //                  else {
                        //                     logger.info(PC2LogCategory.FSM, subCat, "AutoProvState is terminating because the input directory is null.");
                        //                  }
                    } else {
                        logger.info(PC2LogCategory.PCSim2, subCat,
                                "AutoProvState is terminating because the port(" + port
                                        + ") is less than 0 or greater than 65535.");
                    }
                } catch (NumberFormatException nfe) {
                    logger.warn(PC2LogCategory.FSM, subCat,
                            "AutoProvState is not auto generating a provisioning file because the "
                                    + "TFTP Server Port setting doesn't appear to be a number.");
                } catch (UnknownHostException uhe) {
                    logger.warn(PC2LogCategory.FSM, subCat,
                            "AutoProvState is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + uhe.getMessage() + "\n" + uhe.getStackTrace());
                } catch (IOException ioe) {
                    logger.warn(PC2LogCategory.FSM, subCat,
                            "AutoProvState is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + ioe.getMessage() + "\n" + ioe.getStackTrace());
                }

            } else {
                logger.info(PC2LogCategory.FSM, subCat,
                        "AutoProvState is stopping because one of the values is null.\n" + "macAddr=" + macAddr
                                + " pcscfLabel=" + pcscfLabel + " tftpIP=" + tftpIP + " tftpPort=" + tftpPort);
            }
        } else {
            if (pd != null)
                logger.info(PC2LogCategory.FSM, subCat,
                        "The provisioning data is null, terminating processing.");
            if (platform != null)
                logger.info(PC2LogCategory.FSM, subCat,
                        "The Platform settings is null, terminating processing.");
            if (dut != null)
                logger.info(PC2LogCategory.FSM, subCat, "The DUT settings is null, terminating processing.");
        }
    } else {
        Generate g = new Generate(EventConstants.AUTO_PROV_PROMPT, null, this.owner.getName());
        try {
            g.execute(super.api, 0);
        } catch (PC2Exception pce) {
            logger.error(PC2LogCategory.FSM, subCat,
                    name + " couldn't generate " + EventConstants.AUTO_PROV_PROMPT + " event to the FSM.");
        }
    }

    return null;
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * This method determines if the provisioning file used to conduct a test needs to
 * be generated from one of the templates prior to starting the test.
 * @return - the MAC address used for the name of the file
 *///w  w w  .  j ava 2 s .c om
private String autoGenerate(ProvisioningData pd) {
    Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
    Properties dut = SystemSettings.getSettings(SettingConstants.DUT);
    if (pd != null && platform != null && dut != null) {
        String pcscfLabel = dut.getProperty(SettingConstants.PCSCF);
        String macAddr = dut.getProperty(SettingConstants.MAC_ADDRESS);
        String tftpIP = platform.getProperty(SettingConstants.TFTP_SERVER_IP);
        String tftpPort = platform.getProperty(SettingConstants.TFTP_SERVER_PORT);
        String phone1 = dut.getProperty(SettingConstants.PHONE_NUMBER_1);
        String phone2 = dut.getProperty(SettingConstants.PHONE_NUMBER_2);
        String cw = platform.getProperty(SettingConstants.CW_NUMBER);
        if (macAddr != null && pcscfLabel != null && tftpIP != null && tftpPort != null && cw != null) {
            // First see if we have already issued a generated file.
            if (!provDB.issued(macAddr, pd)) {
                // Next verify the port is not set to zero
                try {
                    int port = Integer.parseInt(tftpPort);
                    if (port > 0 && port <= 65535) {

                        // Next make sure the TFTP Server IP is not set to 0.0.0.0
                        if (tftpIP.equals("0.0.0.0")) {
                            logger.warn(PC2LogCategory.PCSim2, subCat,
                                    "The TFTP Server IP setting in the platform file is not valid. Ending auto generate operation.");
                            return null;
                        }

                        File input = new File(SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                + SettingConstants.CW + cw + File.separator + pd.getProvFileName());
                        if (input != null) {
                            ProvGen pg = new ProvGen(input);
                            if (phone1 != null)
                                pg.changePhoneNum(SettingConstants.AUTO_GENERATE_PHONE_NUMBER_1, phone1);
                            if (phone2 != null)
                                pg.changePhoneNum(SettingConstants.AUTO_GENERATE_PHONE_NUMBER_2, phone2);
                            Properties pcscf = SystemSettings.getSettings(pcscfLabel);
                            if (pcscf != null) {
                                String pcscfIP = pcscf.getProperty(SettingConstants.IP);
                                if (pcscfIP != null)
                                    pg.changePCSCF(pcscfIP);
                            }
                            String newFileName = macAddr + ".bin";
                            if (pg.output(SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                    + SettingConstants.CW + cw + File.separator + newFileName)) {
                                // Test system
                                //File output = new File(SettingConstants.AUTO_PROV_FILE_DIRECTORY + newFileName);
                                //File pact = new File(SettingConstants.AUTO_PROV_FILE_DIRECTORY + "chinmaya_base_ph1_pcscf.bin");
                                //pg.compare(pact, output);
                                // Create a data entry of the issued event
                                //ProvisioningData issuePD = new ProvisioningData(macAddr, pd.getPolicyFileName(), newFileName);
                                logger.info(PC2LogCategory.PCSim2, subCat,
                                        "Beginning to TFTP the new provisioning file.");
                                provDB.setIssuedData(macAddr, pd);

                                // Next we need to TFTP the file to the server
                                TFTPClient client = new TFTPClient();
                                File binFile = new File(
                                        SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                                + SettingConstants.CW + cw + File.separator + newFileName);
                                if (binFile.isFile() && binFile.canRead()) {
                                    FileInputStream istrm = new FileInputStream(binFile);
                                    //InetAddress ia = InetAddress.getByName("10.4.1.37");
                                    client.open(); // client.open(20003, ia);
                                    client.sendFile(newFileName, TFTP.BINARY_MODE, istrm, tftpIP, port);
                                    client.close();
                                    logger.info(PC2LogCategory.PCSim2, subCat,
                                            "TFTP of the new provisioning file is complete.");
                                    return macAddr;
                                } else {
                                    logger.warn(PC2LogCategory.PCSim2, subCat,
                                            "The " + macAddr + ".bin doesn't appear in the "
                                                    + SettingConstants.AUTO_PROV_FILE_DIRECTORY + File.separator
                                                    + SettingConstants.CW + cw
                                                    + " Ending auto generate operation.");
                                }
                            } else {
                                logger.error(PC2LogCategory.PCSim2, subCat,
                                        "PCSim2 could not locate provisioning template file["
                                                + input.getAbsolutePath() + "].");
                            }
                        }
                        //                     else {
                        //                        logger.info(PC2LogCategory.PCSim2, subCat, "Auto provisioning is terminating because the input directory is null.");
                        //                     }
                    } else {
                        logger.info(PC2LogCategory.PCSim2, subCat,
                                "Auto provisioning is terminating because the port(" + port
                                        + ") is less than 0 or greater than 65535.");
                    }
                } catch (NumberFormatException nfe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "TFTP Server Port setting doesn't appear to be a number.");
                } catch (UnknownHostException uhe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + uhe.getMessage() + "\n" + uhe.getStackTrace());
                } catch (IOException ioe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + ioe.getMessage() + "\n" + ioe.getStackTrace());
                }
            } else {
                logger.info(PC2LogCategory.PCSim2, subCat,
                        "Auto provisioning detected the same same provisioning template is already in use, skipping operation.");

            }
        } else {
            logger.info(PC2LogCategory.PCSim2, subCat,
                    "Auto provisioning is stopping because one of the values is null.\n" + "macAddr=" + macAddr
                            + " pcscfLabel=" + pcscfLabel + " tftpIP=" + tftpIP + " tftpPort=" + tftpPort);
        }
    } else {
        if (pd != null)
            logger.info(PC2LogCategory.PCSim2, subCat,
                    "The provisioning data is null, terminating processing.");
        if (platform != null)
            logger.info(PC2LogCategory.PCSim2, subCat,
                    "The Platform settings is null, terminating processing.");
        if (dut != null)
            logger.info(PC2LogCategory.PCSim2, subCat, "The DUT settings is null, terminating processing.");
    }

    return null;
}

From source file:com.t_oster.liblasercut.drivers.LaosCutter.java

@Override
public void sendJob(LaserJob job, ProgressListener pl, List<String> warnings)
        throws IllegalJobException, Exception {
    currentFrequency = -1;//  w w w  . j  a  v  a  2 s  .c  o m
    currentPower = -1;
    currentSpeed = -1;
    currentFocus = 0;
    currentPurge = false;
    currentVentilation = false;
    pl.progressChanged(this, 0);
    BufferedOutputStream out;
    ByteArrayOutputStream buffer = null;
    pl.taskChanged(this, "checking job");
    checkJob(job);
    job.applyStartPoint();
    if (!useTftp) {
        pl.taskChanged(this, "connecting");
        Socket connection = new Socket();
        connection.connect(new InetSocketAddress(hostname, port), 3000);
        out = new BufferedOutputStream(connection.getOutputStream());
        pl.taskChanged(this, "sending");
    } else {
        buffer = new ByteArrayOutputStream();
        out = new BufferedOutputStream(buffer);
        pl.taskChanged(this, "buffering");
    }
    this.writeJobCode(job, out, pl);
    if (this.isUseTftp()) {
        pl.taskChanged(this, "connecting");
        TFTPClient tftp = new TFTPClient();
        tftp.setDefaultTimeout(5000);
        //open a local UDP socket
        tftp.open();
        pl.taskChanged(this, "sending");
        ByteArrayInputStream bain = new ByteArrayInputStream(buffer.toByteArray());
        tftp.sendFile(job.getName().replace(" ", "") + ".lgc", TFTP.BINARY_MODE, bain, this.getHostname(),
                this.getPort());
        tftp.close();
        bain.close();
        if (debugFilename != null && !"".equals(debugFilename)) {
            pl.taskChanged(this, "writing " + debugFilename);
            FileOutputStream o = new FileOutputStream(new File(debugFilename));
            o.write(buffer.toByteArray());
            o.close();
        }
        pl.taskChanged(this, "sent.");
    }
    pl.progressChanged(this, 100);
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * This method creates the T.I.M results file for the a specific
 * test case./*from ww w  .jav a2  s.  c  om*/
 */
private void generateResults(TSDocument doc) {
    String fileName = doc.getLogFileName();
    int index = fileName.lastIndexOf("_ss.log");
    String timFileName = fileName.substring(0, index) + "_ss.res";
    File tim = new File(timFileName);
    if (!tim.exists()) {
        Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
        Properties dut = SystemSettings.getSettings("DUT");
        try {
            FileOutputStream output = null;
            if (tim.createNewFile()) {
                output = new FileOutputStream(tim);
            } else {
                output = new FileOutputStream((timFileName + "_" + System.currentTimeMillis()));
            }

            String testerName = platform.getProperty(SettingConstants.TESTER_NAME);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date stop = new Date();
            String cw = platform.getProperty(SettingConstants.CW_NUMBER);
            if (!cw.startsWith("CW"))
                cw = "CW" + cw;
            String result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                    + "<res-document xmlns=\"http://cablelabs.com/TEPResultDocument\" version=\"1.0\">\n\t"
                    + "<execution method=\"automatic\" start=\"" + sdf.format(doc.getStart()) + "\" stop=\""
                    + sdf.format(stop) + "\" />\n\t" + "<tester username=\"" + testerName + "\" />\n\t"
                    + "<certwave name=\"" + cw + "\" />\n\t" + "<test-result type=\""
                    + platform.getProperty(SettingConstants.DUT_SUBGROUP) + "\" name=\"" + doc.getNumber()
                    + "\"\n\tproduct=\"" + dut.getProperty(SettingConstants.DUT_VENDOR) + "\" result=\""
                    + ((testPassed == null || testPassed) ? "PASS" : "FAIL") + "\"\n\tunit=\""
                    + dut.getProperty(SettingConstants.PRODUCT_UNIT) + "\"/>\n" + "</res-document>";
            if (output != null) {
                output.write(result.getBytes());
                output.close();
            }
            //            else 
            //               logger.fatal(PC2LogCategory.Parser, subCat,
            //                     "Couldn't write TIM file! Writing to log file for preservation!\n" + result);
        } catch (IOException ioe) {
            logger.error(PC2LogCategory.Parser, subCat, "Could not create new TIM file[" + timFileName + "].");
        }

        String tftpIP = platform.getProperty(SettingConstants.TFTP_SERVER_IP);
        String tftpPort = platform.getProperty(SettingConstants.TFTP_SERVER_PORT);

        if (tftpIP != null && tftpPort != null) {
            boolean recProv = SystemSettings
                    .resolveBooleanSetting(platform.getProperty(SettingConstants.RECORD_PROVISIONING_FILE));
            if (recProv && dut != null)
                try {
                    RecordProvFileListener rpfl = new RecordProvFileListener();
                    boolean success = rpfl.run();
                    String provFile = rpfl.getValue();
                    if (success) {

                        int port = Integer.parseInt(tftpPort);
                        if (port > 0 && port <= 65535) {

                            // Next make sure the TFTP Server IP is not set to 0.0.0.0
                            if (tftpIP.equals("0.0.0.0")) {
                                logger.warn(PC2LogCategory.PCSim2, subCat,
                                        "The TFTP Server IP setting in the platform file is not valid. Ending auto generate operation.");
                            } else {
                                // Next we need to TFTP the file from the server
                                TFTPClient client = new TFTPClient();
                                int dirIndex = fileName.lastIndexOf("/", index);
                                File dir = new File(fileName.substring(0, dirIndex) + PROV_FILE_DIRECTORY);
                                if (dir.exists() && !dir.isDirectory()) {
                                    logger.error(PC2LogCategory.PCSim2, subCat, "The path " + dir.getPath()
                                            + " is not a directory. Terminating the recording of the provisioning file.");
                                }
                                File binFile = new File(fileName.substring(0, dirIndex + 1)
                                        + PROV_FILE_DIRECTORY + File.separator
                                        + fileName.substring(dirIndex + 1, index) + "_prov.bin");
                                boolean exists = false;
                                if (!binFile.exists())
                                    exists = binFile.createNewFile();
                                if (exists && binFile.canWrite()) {
                                    FileOutputStream ostrm = new FileOutputStream(binFile);
                                    //InetAddress ia = InetAddress.getByName("10.4.1.37");
                                    client.open(); // client.open(20003, ia);
                                    client.receiveFile(provFile, TFTP.BINARY_MODE, ostrm, tftpIP, port);
                                    client.close();
                                    logger.info(PC2LogCategory.PCSim2, subCat,
                                            "TFTP of the record provisioning file is complete.");
                                } else {
                                    logger.warn(PC2LogCategory.PCSim2, subCat,
                                            "The system could not TFTP the provisioning file because TFTP address is "
                                                    + tftpIP + ".");
                                }
                            }
                        } else {
                            logger.warn(PC2LogCategory.PCSim2, subCat,
                                    "Recording of the provisioning file is terminating because the port(" + port
                                            + ") is less than 0 or greater than 65535.");
                        }
                    } else {
                        logger.warn(PC2LogCategory.PCSim2, subCat,
                                "Recording of the provisioning file is terminating because PACT returned an error string of \""
                                        + provFile + "\".");
                    }
                } catch (NumberFormatException nfe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "TFTP Server Port setting doesn't appear to be a number.");
                } catch (UnknownHostException uhe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + uhe.getMessage() + "\n" + uhe.getStackTrace());
                } catch (IOException ioe) {
                    logger.warn(PC2LogCategory.PCSim2, subCat,
                            "PCSim2 is not auto generating a provisioning file because the "
                                    + "system encountered an error when attempting to send the file to the TFTP Server.\n"
                                    + ioe.getMessage() + "\n" + ioe.getStackTrace());
                }
        }
    }
}

From source file:org.apache.common.net.examples.ftp.TFTPExample.java

public final static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;/*from w w w  .j  a  va 2s  . c  o  m*/

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];
        if (arg.startsWith("-")) {
            if (arg.equals("-r")) {
                receiveFile = true;
            } else if (arg.equals("-s")) {
                receiveFile = false;
            } else if (arg.equals("-a")) {
                transferMode = TFTP.ASCII_MODE;
            } else if (arg.equals("-b")) {
                transferMode = TFTP.BINARY_MODE;
            } else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else {
            break;
        }
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    tftp = new TFTPClient();

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(60000);

    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        System.err.println("Error: could not open local UDP socket.");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        FileOutputStream output = null;
        File file;

        file = new File(localFilename);

        // If file exists, don't overwrite it.
        if (file.exists()) {
            System.err.println("Error: " + localFilename + " already exists.");
            System.exit(1);
        }

        // Try to open local file for writing
        try {
            output = new FileOutputStream(file);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for writing.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to receive remote file via TFTP
        try {
            tftp.receiveFile(remoteFilename, transferMode, output, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while receiving file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and output file
            tftp.close();
            try {
                if (output != null) {
                    output.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }

    } else {
        // We're sending a file
        FileInputStream input = null;

        // Try to open local file for reading
        try {
            input = new FileInputStream(localFilename);
        } catch (IOException e) {
            tftp.close();
            System.err.println("Error: could not open local file for reading.");
            System.err.println(e.getMessage());
            System.exit(1);
        }

        // Try to send local file via TFTP
        try {
            tftp.sendFile(remoteFilename, transferMode, input, hostname);
        } catch (UnknownHostException e) {
            System.err.println("Error: could not resolve hostname.");
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error: I/O exception occurred while sending file.");
            System.err.println(e.getMessage());
            System.exit(1);
        } finally {
            // Close local socket and input file
            tftp.close();
            try {
                if (input != null) {
                    input.close();
                }
                closed = true;
            } catch (IOException e) {
                closed = false;
                System.err.println("Error: error closing file.");
                System.err.println(e.getMessage());
            }
        }

        if (!closed) {
            System.exit(1);
        }

    }

}

From source file:org.apache.commons.net.examples.ftp.TFTPExample.java

public static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    final TFTPClient tftp;
    int timeout = 60000;
    boolean verbose = false;

    // Parse options
    for (argc = 0; argc < args.length; argc++) {
        arg = args[argc];/*from www .ja v a 2 s . c o m*/
        if (arg.startsWith("-")) {
            if (arg.equals("-r")) {
                receiveFile = true;
            } else if (arg.equals("-s")) {
                receiveFile = false;
            } else if (arg.equals("-a")) {
                transferMode = TFTP.ASCII_MODE;
            } else if (arg.equals("-b")) {
                transferMode = TFTP.BINARY_MODE;
            } else if (arg.equals("-t")) {
                timeout = 1000 * Integer.parseInt(args[++argc]);
            } else if (arg.equals("-v")) {
                verbose = true;
            } else {
                System.err.println("Error: unrecognized option.");
                System.err.print(USAGE);
                System.exit(1);
            }
        } else {
            break;
        }
    }

    // Make sure there are enough arguments
    if (args.length - argc != 3) {
        System.err.println("Error: invalid number of arguments.");
        System.err.print(USAGE);
        System.exit(1);
    }

    // Get host and file arguments
    hostname = args[argc];
    localFilename = args[argc + 1];
    remoteFilename = args[argc + 2];

    // Create our TFTP instance to handle the file transfer.
    if (verbose) {
        tftp = new TFTPClient() {
            @Override
            protected void trace(String direction, TFTPPacket packet) {
                System.out.println(direction + " " + packet);
            }
        };
    } else {
        tftp = new TFTPClient();
    }

    // We want to timeout if a response takes longer than 60 seconds
    tftp.setDefaultTimeout(timeout);

    // We haven't closed the local file yet.
    closed = false;

    // If we're receiving a file, receive, otherwise send.
    if (receiveFile) {
        closed = receive(transferMode, hostname, localFilename, remoteFilename, tftp);
    } else {
        // We're sending a file
        closed = send(transferMode, hostname, localFilename, remoteFilename, tftp);
    }

    System.out.println("Recd: " + tftp.getTotalBytesReceived() + " Sent: " + tftp.getTotalBytesSent());

    if (!closed) {
        System.out.println("Failed");
        System.exit(1);
    }

    System.out.println("OK");
}

From source file:org.jnode.protocol.tftp.TFTPURLConnection.java

/**
 * @see java.net.URLConnection#getInputStream()
 *///from   ww w .  j a  va 2s  .c om
public InputStream getInputStream() throws IOException {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    final TFTPClient tftp = new TFTPClient();
    final InetAddress hostAddr = InetAddress.getByName(host);
    tftp.open(TFTP.DEFAULT_PORT);
    try {
        tftp.receiveFile(path, TFTP.BINARY_MODE, os, hostAddr);
    } finally {
        tftp.close();
    }
    return new ByteArrayInputStream(os.toByteArray());
}