Example usage for org.apache.commons.net.ftp FTPClient login

List of usage examples for org.apache.commons.net.ftp FTPClient login

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient login.

Prototype

public boolean login(String username, String password) throws IOException 

Source Link

Document

Login to the FTP server using the provided username and password.

Usage

From source file:org.apache.sqoop.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;
    try {/* w  w w .  j  av a  2s.  com*/
        String username = conf.get(DBConfiguration.USERNAME_PROPERTY);
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = DBConfiguration.getPassword((JobConf) conf);
        }

        String connectString = conf.get(DBConfiguration.URL_PROPERTY);
        String server = connectString;
        int port = 0;
        String[] parts = connectString.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                LOG.warn("Invalid port number: " + e.toString());
            }
        }

        if (null != mockFTPClient) {
            ftp = mockFTPClient;
        } else {
            ftp = new FTPClient();
        }

        FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS);
        ftp.configure(config);

        if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
        }
        try {
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
        } catch (IOException ioexp) {
            throw new IOException("Could not connect to server " + server, ioexp);
        }

        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString());
        }
        LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set ASCII transfer mode
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
        LOG.info("System type detected: " + ftp.getSystemType());
    } catch (IOException ioe) {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        ftp = null;
        throw ioe;
    }
    return ftp;
}

From source file:org.apache.tools.ant.taskdefs.optional.net2.FTP2.java

/**
 * Runs the task./*  www .ja v a  2  s . com*/
 *
 * @throws BuildException if the task fails or is not configured
 *         correctly.
 */
@Override
public void execute() throws BuildException {
    checkAttributes();

    FTPClient ftp = null;

    try {
        log("Opening FTP connection to " + server, Project.MSG_VERBOSE);

        ftp = new FTPClient();
        if (this.isConfigurationSet) {
            ftp = FTPConfigurator.configure(ftp, this);
        }

        ftp.setRemoteVerificationEnabled(enableRemoteVerification);

        if (this.proxyServer != null) {

            // Connect through an FTP proxy.

            // Get FTP proxy credentials (optional).
            String proxyUserId;
            char[] proxyPassword;
            {
                PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.proxyServer, this.proxyPort,
                        this.proxyUserid, this.proxyPassword, RequestorType.PROXY);
                if (pa == null) {
                    proxyUserId = null;
                    proxyPassword = null;
                } else {
                    proxyUserId = pa.getUserName();
                    if (proxyUserId == null)
                        throw new BuildException("Proxy user ID missing");
                    proxyPassword = pa.getPassword();
                    if (proxyPassword == null)
                        throw new BuildException("Proxy password missing");
                }
            }

            // Get remote FTP server credentials (mandatory).
            String serverUserId;
            char[] serverPassword;
            {
                PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.server, this.port, this.userid,
                        this.password, RequestorType.SERVER);
                if (pa == null)
                    throw new BuildException("User ID and password missing");
                serverUserId = pa.getUserName();
                if (serverUserId == null)
                    throw new BuildException("User ID missing");
                serverPassword = pa.getPassword();
                if (serverPassword == null)
                    throw new BuildException("Password missing");
            }

            // Connect to the FTP proxy.
            this.log("Opening FTP connection to proxy server \"" + this.proxyServer + "\" on port "
                    + this.proxyPort, Project.MSG_VERBOSE);
            ftp.connect(this.proxyServer, this.proxyPort);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("FTP connection to proxy server failed: " + ftp.getReplyString());
            }
            this.log("connected to proxy server", Project.MSG_VERBOSE);

            // Authenticate with the FTP proxy (optional).
            if (proxyUserId != null) {
                this.log("logging in to FTP proxy server", Project.MSG_VERBOSE);
                if (!ftp.login(proxyUserId, new String(proxyPassword))) {
                    throw new BuildException("Could not login to FTP proxy server");
                }
            }

            // Log in to the remote FTP server.
            this.log("logging in to FTP server", Project.MSG_VERBOSE);
            String userid2 = serverUserId + '@' + this.server;
            if (this.port != FTP2.DEFAULT_FTP_PORT)
                userid2 += ":" + this.port;
            if (this.account == null ? !ftp.login(userid2, new String(serverPassword))
                    : !ftp.login(userid2, new String(serverPassword), this.account))
                throw new BuildException("Could not login to FTP server");
            this.log("login succeeded", Project.MSG_VERBOSE);
        } else {

            // Direct connection to remote FTP server.

            // Get remote FTP server credentials (mandatory).
            String serverUserId;
            char[] serverPassword;
            {
                PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.server, this.port, this.userid,
                        this.password, RequestorType.SERVER);
                if (pa == null)
                    throw new BuildException("User ID and password missing");
                serverUserId = pa.getUserName();
                if (serverUserId == null)
                    throw new BuildException("User ID missing");
                serverPassword = pa.getPassword();
                if (serverPassword == null)
                    throw new BuildException("Password missing");
            }

            // Connect to the remote FTP server.
            this.log("Opening FTP connection to " + this.server, Project.MSG_VERBOSE);
            ftp.connect(this.server, this.port);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("FTP connection failed: " + ftp.getReplyString());
            }
            this.log("connected", Project.MSG_VERBOSE);

            // Log in to the remote FTP server.
            this.log("logging in to FTP server", Project.MSG_VERBOSE);
            if (this.account == null ? !ftp.login(serverUserId, new String(serverPassword))
                    : !ftp.login(serverUserId, new String(serverPassword), this.account))
                throw new BuildException("Could not login to FTP server");
            this.log("login succeeded", Project.MSG_VERBOSE);
        }

        if (binary) {
            ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not set transfer type: " + ftp.getReplyString());
            }
        } else {
            ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not set transfer type: " + ftp.getReplyString());
            }
        }

        if (passive) {
            log("entering passive mode", Project.MSG_VERBOSE);
            ftp.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString());
            }
        }

        // If an initial command was configured then send it.
        // Some FTP servers offer different modes of operation,
        // E.G. switching between a UNIX file system mode and
        // a legacy file system.
        if (this.initialSiteCommand != null) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                @Override
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP2.this.initialSiteCommand);
                }
            }, "initial site command: " + this.initialSiteCommand);
        }

        // For a unix ftp server you can set the default mask for all files
        // created.

        if (umask != null) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                @Override
                public void execute() throws IOException {
                    doSiteCommand(lftp, "umask " + umask);
                }
            }, "umask " + umask);
        }

        // If the action is MK_DIR, then the specified remote
        // directory is the directory to create.

        if (action == MK_DIR) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                @Override
                public void execute() throws IOException {
                    makeRemoteDir(lftp, remotedir);
                }
            }, remotedir);
        } else if (action == SITE_CMD) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                @Override
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP2.this.siteCommand);
                }
            }, "Site Command: " + this.siteCommand);
        } else {
            if (remotedir != null) {
                log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE);
                ftp.changeWorkingDirectory(remotedir);
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString());
                }
            }
            if (newerOnly && timeDiffAuto) {
                // in this case we want to find how much time span there is between local
                // and remote
                timeDiffMillis = getTimeDiff(ftp);
            }
            log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]);
            transferFiles(ftp);
        }

    } catch (IOException ex) {
        throw new BuildException("error during FTP transfer: " + ex, ex);
    } finally {
        if (ftp != null && ftp.isConnected()) {
            try {
                log("disconnecting", Project.MSG_VERBOSE);
                ftp.logout();
                ftp.disconnect();
            } catch (IOException ex) {
                // ignore it
            }
        }
    }
}

From source file:org.blue.star.plugins.check_ftp.java

public boolean execute_check() {
    /* Declare variables */
    FTPClient ftp = new FTPClient();
    File filename = null;/*  w  w  w. ja  v  a2  s . c o  m*/
    FileChannel channel;
    InputStream is;
    OutputStream os;
    int reply;

    if (super.verbose > 0)
        verbose = true;

    /* Configure client to meet our requirements */
    ftp.setDefaultPort(port);
    ftp.setDefaultTimeout(timeout);

    if (verbose) {
        System.out.println("Using FTP Server: " + hostname);
        System.out.println("Using FTP Port: " + port);
        System.out.println("Using Timeout of: " + timeout);
    }

    if (passive) {
        ftp.enterLocalPassiveMode();
        if (verbose)
            System.out.println("Using Passive Mode");
    }

    try {
        filename = new File(file);
        channel = new RandomAccessFile(filename, "rw").getChannel();

        if (verbose)
            System.out.println("Attempting FTP Connection to " + hostname);
        ftp.connect(hostname);
        reply = ftp.getReplyCode();

        /* Test to see if we actually managed to connect */
        if (!FTPReply.isPositiveCompletion(reply)) {
            if (verbose)
                System.out.println("FTP Connection to " + hostname + " failed");
            check_state = common_h.STATE_CRITICAL;
            check_message = ftp.getReplyString();
            filename.delete();
            ftp.disconnect();
            return true;
        }

        /* Try and login if we're using username/password */
        if (username != null && password != null) {
            if (verbose)
                System.out.println("Attempting to log in into FTP Server " + hostname);

            if (!ftp.login(username, password)) {
                if (verbose)
                    System.out.println("Unable to log in to FTP Server " + hostname);
                check_state = common_h.STATE_CRITICAL;
                check_message = ftp.getReplyString();
                ftp.disconnect();
                filename.delete();
                return true;
            }
        }

        if (verbose)
            System.out.println("Attempting to change to required directory");
        /* Try and change to the given directory */
        if (!ftp.changeWorkingDirectory(directory)) {
            if (verbose)
                System.out.println("Required directory cannot be found!");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        if (verbose)
            System.out.println("Attempting to retrieve specified file!");
        /* Try to get Stream on Remote File! */
        is = ftp.retrieveFileStream(file);

        if (is == null) {
            if (verbose)
                System.out.println("Unable to locate required file.");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* OutputStream */
        os = Channels.newOutputStream(channel);

        /* Create the buffer */
        byte[] buf = new byte[4096];

        if (verbose)
            System.out.println("Beginning File transfer...");
        for (int len = -1; (len = is.read(buf)) != -1;)
            os.write(buf, 0, len);

        if (verbose) {
            System.out.println("...transfer complete.");
            System.out.println("Attempting to finalise Command");
        }

        /* Finalise the transfer details */
        if (!ftp.completePendingCommand()) {
            if (verbose)
                System.out.println("Unable to finalise command");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* Clean up */
        if (verbose)
            System.out.println("Check Completed.");
        check_state = common_h.STATE_OK;
        check_message = ftp.getReplyString();

        /* Close out things */
        is.close();
        os.close();
        channel.close();
        filename.delete();

    } catch (IOException e) {
        check_state = common_h.STATE_CRITICAL;
        check_message = e.getMessage();
        if (filename != null)
            filename.delete();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();

            } catch (Exception e) {
            }
        }
    }

    return true;
}

From source file:org.codice.alliance.nsili.source.NsiliSource.java

/**
 * Uses FTPClient to obtain the IOR string from the provided URL via FTP.
 *//* w w  w. jav a  2  s  .co m*/
private void getIorStringFromFtpSource() {
    URI uri = null;
    try {
        uri = new URI(iorUrl);
    } catch (URISyntaxException e) {
        LOGGER.error("{} : Invalid URL specified for IOR string: {} {}", id, iorUrl, e.getMessage());
        LOGGER.debug("{} : Invalid URL specified for IOR string: {}", id, iorUrl, e);
    }

    FTPClient ftpClient = new FTPClient();
    try {
        if (uri.getPort() > 0) {
            ftpClient.connect(uri.getHost(), uri.getPort());
        } else {
            ftpClient.connect(uri.getHost());
        }

        if (!ftpClient.login(serverUsername, serverPassword)) {
            LOGGER.error("{} : FTP server log in unsuccessful.", id);
        } else {
            int timeoutMsec = clientTimeout * 1000;
            ftpClient.setConnectTimeout(timeoutMsec);
            ftpClient.setControlKeepAliveReplyTimeout(timeoutMsec);
            ftpClient.setDataTimeout(timeoutMsec);

            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            InputStream inputStream = ftpClient.retrieveFileStream(uri.getPath());

            iorString = IOUtils.toString(inputStream, StandardCharsets.ISO_8859_1.name());
            //Remove leading/trailing whitespace as the CORBA init can't handle that.
            iorString = iorString.trim();
        }
    } catch (Exception e) {
        LOGGER.warn("{} : Error retrieving IOR file for {}. {}", id, iorUrl, e.getMessage());
        LOGGER.debug("{} : Error retrieving IOR file for {}.", id, iorUrl, e);
    }
}

From source file:org.compiere.model.MMediaServer.java

/**
 *    (Re-)Deploy all media//  w  w w  .  ja v  a 2s . c o m
 *    @param media array of media to deploy
 *    @return true if deployed
 */
public boolean deploy(MMedia[] media) {
    // Check whether the host is our example localhost, we will not deploy locally, but this is no error
    if (this.getIP_Address().equals("127.0.0.1") || this.getName().equals("localhost")) {
        log.warning("You have not defined your own server, we will not really deploy to localhost!");
        return true;
    }

    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(getIP_Address());
        if (ftp.login(getUserName(), getPassword()))
            log.info("Connected to " + getIP_Address() + " as " + getUserName());
        else {
            log.warning("Could NOT connect to " + getIP_Address() + " as " + getUserName());
            return false;
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Could NOT connect to " + getIP_Address() + " as " + getUserName(), e);
        return false;
    }

    boolean success = true;
    String cmd = null;
    //   List the files in the directory
    try {
        cmd = "cwd";
        ftp.changeWorkingDirectory(getFolder());
        //
        cmd = "list";
        String[] fileNames = ftp.listNames();
        log.log(Level.FINE, "Number of files in " + getFolder() + ": " + fileNames.length);

        /*
        FTPFile[] files = ftp.listFiles();
        log.config("Number of files in " + getFolder() + ": " + files.length);
        for (int i = 0; i < files.length; i++)
           log.fine(files[i].getTimestamp() + " \t" + files[i].getName());*/
        //
        cmd = "bin";
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //
        for (int i = 0; i < media.length; i++) {
            if (!media[i].isSummary()) {
                log.log(Level.INFO, " Deploying Media Item:" + media[i].get_ID() + media[i].getExtension());
                MImage thisImage = media[i].getImage();

                // Open the file and output streams
                byte[] buffer = thisImage.getData();
                ByteArrayInputStream is = new ByteArrayInputStream(buffer);

                String fileName = media[i].get_ID() + media[i].getExtension();
                cmd = "put " + fileName;
                ftp.storeFile(fileName, is);
                is.close();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
        success = false;
    }
    //   Logout from the FTP Server and disconnect
    try {
        cmd = "logout";
        ftp.logout();
        cmd = "disconnect";
        ftp.disconnect();
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
    }
    ftp = null;
    return success;
}

From source file:org.drftpd.tests.ConnectionStressTest.java

public void run() {
    try {//from   ww w.  ja v  a  2 s.  c  o m
        FTPClient c = new FTPClient();
        c.configure(ftpConfig);

        logger.debug("Trying to connect");
        c.connect("127.0.0.1", 21211);
        logger.debug("Connected");

        c.setSoTimeout(5000);

        if (!FTPReply.isPositiveCompletion(c.getReplyCode())) {
            logger.debug("Houston, we have a problem. D/C");
            c.disconnect();
            throw new Exception();
        }

        if (c.login("drftpd", "drftpd")) {
            logger.debug("Logged-in, now waiting 5 secs and kill the thread.");
            _sc.addSuccess();
            Thread.sleep(5000);
            c.disconnect();
        } else {
            logger.debug("Login failed, D/C!");
            throw new Exception();
        }
    } catch (Exception e) {
        logger.debug(e, e);
        _sc.addFailure();
    }

    logger.debug("exiting");
}

From source file:org.ecoinformatics.datamanager.download.DownloadHandler.java

/**
 * Gets content from given source and writes it to DataStorageInterface 
 * to store them. This method will be called by run()
 * //  w  ww  .  j  av a  2 s  . co  m
 * @param resourceName  the URL to the source data to be retrieved
 */
protected boolean getContentFromSource(String resourceName) {
    boolean successFlag = false;
    QualityCheck onlineURLsQualityCheck = null;
    boolean onlineURLsException = false; // used to determine status of onlineURLs quality check

    if (resourceName != null) {
        resourceName = resourceName.trim();
    }

    if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://")
            || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) {
        // get the data from a URL
        int responseCode = 0;
        String responseMessage = null;

        try {
            URL url = new URL(resourceName);
            boolean isFTP = false;

            if (entity != null) {
                String contentType = null;

                // Find the right MIME type and set it as content type
                if (resourceName.startsWith("http")) {
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("HEAD");
                    httpURLConnection.connect();
                    contentType = httpURLConnection.getContentType();
                    responseCode = httpURLConnection.getResponseCode();
                    responseMessage = httpURLConnection.getResponseMessage();
                } else if (resourceName.startsWith("file")) {
                    URLConnection urlConnection = url.openConnection();
                    urlConnection.connect();
                    contentType = urlConnection.getContentType();
                } else { // FTP
                    isFTP = true;
                    contentType = "application/octet-stream";
                }

                entity.setUrlContentType(contentType);
            }

            if (!isFTP) { // HTTP(S) or FILE
                InputStream filestream = url.openStream();

                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    filestream.close();
                }
            } else { // FTP
                String[] urlParts = resourceName.split("/");
                String address = urlParts[2];
                String dir = "/";
                for (int i = 3; i < urlParts.length - 1; i++) {
                    dir += urlParts[i] + "/";
                }
                String fileName = urlParts[urlParts.length - 1];
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(address);
                ftpClient.login(ANONYMOUS, anonymousFtpPasswd);
                ftpClient.changeWorkingDirectory(dir);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking
                InputStream filestream = ftpClient.retrieveFileStream(fileName);
                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    try {
                        filestream.close();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(String
                                .format("Error closing local file '%s': %s", resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }

                // logout and disconnect if FTP session
                if (resourceName.startsWith("ftp") && ftpClient != null) {
                    try {
                        ftpClient.enterLocalActiveMode();
                        ftpClient.logout();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(
                                String.format("Error disconnecting from FTP with resource '%s': %s",
                                        resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }
            }
        } catch (MalformedURLException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage));
        } catch (IOException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            if (responseCode > 0) {
                eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage);
            }
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is not reachable: %s", resourceName, eMessage));
        }

        // Initialize the "Online URLs are live" quality check
        String qualityCheckIdentifier = "onlineURLs";
        QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier);
        onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate);

        if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) {
            String resourceNameEscaped = embedInCDATA(resourceName);

            if (!onlineURLsException) {
                onlineURLsQualityCheck.setStatus(Status.valid);
                onlineURLsQualityCheck.setFound("true");
                onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped);
            } else {
                onlineURLsQualityCheck.setFailedStatus();
                onlineURLsQualityCheck.setFound("false");
                String explanation = "Failed to access URL: " + resourceNameEscaped;
                explanation = explanation + "; " + embedInCDATA(exception.getMessage());
                onlineURLsQualityCheck.setExplanation(explanation);
            }

            entity.addQualityCheck(onlineURLsQualityCheck);
        }

        return successFlag;
    } else if (resourceName != null && resourceName.startsWith("ecogrid://")) {
        // get the docid from url
        int start = resourceName.indexOf("/", 11) + 1;
        //log.debug("start: " + start);
        int end = resourceName.indexOf("/", start);

        if (end == -1) {
            end = resourceName.length();
        }

        //log.debug("end: " + end);
        String ecogridIdentifier = resourceName.substring(start, end);
        // pass this docid and get data item
        //System.out.println("the endpoint is "+ECOGRIDENDPOINT);
        //System.out.println("The identifier is "+ecogridIdentifier);
        //return false;
        return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier);
    } else if (resourceName != null && resourceName.startsWith("srb://")) {
        // get srb docid from the url
        String srbIdentifier = transformSRBurlToDocid(resourceName);
        // reset endpoint for srb (This is hack we need to figure ou
        // elegent way to do this
        //mEndPoint = Config.getValue("//ecogridService/srb/endPoint");
        // pass this docid and get data item
        //log.debug("before get srb data");
        return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier);
    } else {
        successFlag = false;
        return successFlag;
    }
}

From source file:org.fabric3.binding.ftp.runtime.FtpTargetInterceptor.java

public Message invoke(Message msg) {

    FTPClient ftpClient = new FTPClient();
    ftpClient.setSocketFactory(factory);
    try {//from   w w w  . ja v a  2  s. c o m
        if (timeout > 0) {
            ftpClient.setDefaultTimeout(timeout);
            ftpClient.setDataTimeout(timeout);
        }
        monitor.onConnect(hostAddress, port);
        ftpClient.connect(hostAddress, port);
        monitor.onResponse(ftpClient.getReplyString());
        String type = msg.getWorkContext().getHeader(String.class, FtpConstants.HEADER_CONTENT_TYPE);
        if (type != null && type.equalsIgnoreCase(FtpConstants.BINARY_TYPE)) {
            monitor.onCommand("TYPE I");
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        } else if (type != null && type.equalsIgnoreCase(FtpConstants.TEXT_TYPE)) {
            monitor.onCommand("TYPE A");
            ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        }

        /*if (!ftpClient.login(security.getUser(), security.getPassword())) {
        throw new ServiceUnavailableException("Invalid credentials");
        }*/
        // TODO Fix above
        monitor.onAuthenticate();
        ftpClient.login(security.getUser(), security.getPassword());
        monitor.onResponse(ftpClient.getReplyString());

        Object[] args = (Object[]) msg.getBody();
        String fileName = (String) args[0];
        String remoteFileLocation = fileName;
        InputStream data = (InputStream) args[1];

        if (active) {
            monitor.onCommand("ACTV");
            ftpClient.enterLocalActiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        } else {
            monitor.onCommand("PASV");
            ftpClient.enterLocalPassiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        }
        if (commands != null) {
            for (String command : commands) {
                monitor.onCommand(command);
                ftpClient.sendCommand(command);
                monitor.onResponse(ftpClient.getReplyString());
            }
        }

        if (remotePath != null && remotePath.length() > 0) {
            remoteFileLocation = remotePath.endsWith("/") ? remotePath + fileName : remotePath + "/" + fileName;
        }

        String remoteTmpFileLocation = remoteFileLocation;
        if (tmpFileSuffix != null && tmpFileSuffix.length() > 0) {
            remoteTmpFileLocation += tmpFileSuffix;
        }

        monitor.onCommand("STOR " + remoteFileLocation);
        if (!ftpClient.storeFile(remoteTmpFileLocation, data)) {
            throw new ServiceUnavailableException("Unable to upload data. Response sent from server: "
                    + ftpClient.getReplyString() + " ,remoteFileLocation:" + remoteFileLocation);
        }
        monitor.onResponse(ftpClient.getReplyString());

        //Rename file back to original name if temporary file suffix was used while transmission.
        if (!remoteTmpFileLocation.equals(remoteFileLocation)) {
            ftpClient.rename(remoteTmpFileLocation, remoteFileLocation);
        }
    } catch (IOException e) {
        throw new ServiceUnavailableException(e);
    }
    // reset the message to return an empty response
    msg.reset();
    return msg;
}

From source file:org.geon.XMLToADN.java

private String process(String xmlString) {

    Map metadata = new HashMap();

    // Extracting user input (name/value pairs) into a hashmap.
    int nameStartInd = xmlString.toLowerCase().indexOf("<name>");
    while (nameStartInd != -1) {
        int nameEndInd = xmlString.toLowerCase().indexOf("</name>");
        String name = xmlString.substring(nameStartInd + 6, nameEndInd);
        xmlString = xmlString.substring(nameEndInd + 7);
        int valueStartInd = xmlString.toLowerCase().indexOf("<value>");
        int valueEndInd = xmlString.toLowerCase().indexOf("</value>");
        String value = xmlString.substring(valueStartInd + 7, valueEndInd);
        xmlString = xmlString.substring(valueEndInd + 8);
        metadata.put(name, value);/*from  ww  w . ja  va  2  s  . co m*/
        nameStartInd = xmlString.toLowerCase().indexOf("<name>");
    }

    String errMsg = "";

    String title = (String) metadata.get("title");
    String subjectss = (String) metadata.get("subjects");
    String keywords = (String) metadata.get("keywords");
    String permission = (String) metadata.get("permission");
    String description = (String) metadata.get("description");

    String personOrOrg1 = (String) metadata.get("person1");
    String role1 = (String) metadata.get("role1");
    String nametitle1 = (String) metadata.get("nametitle1");
    String firstname1 = (String) metadata.get("firstname1");
    String middlename1 = (String) metadata.get("middlename1");
    String lastname1 = (String) metadata.get("lastname1");
    String org1 = (String) metadata.get("org1");

    String email1 = (String) metadata.get("email1");
    String homepage1 = (String) metadata.get("homepage1");

    // handle spatial coverage
    // String min_altitude = (String) metadata.get("min_altitude");
    // String max_altitude = (String) metadata.get("max_altitude");

    String hrizontal = (String) metadata.get("hrizontal");
    String projection = (String) metadata.get("projection");
    String coordinate = (String) metadata.get("coordinate");

    // handle temporal coverage
    String time = (String) metadata.get("time");

    String geologic_time = (String) metadata.get("geologic_time");
    String begin_age = (String) metadata.get("begin_age");
    String end_age = (String) metadata.get("end_age");

    // handle present coverage
    String begin_date = (String) metadata.get("begindate");
    String end_date = (String) metadata.get("enddate");

    String t = time.trim();

    StringTokenizer stb = !time.equals("present") ? null : new StringTokenizer(begin_date, "/");

    int bm = !time.equals("present") ? 0 : Integer.parseInt(stb.nextToken());
    int bd = !time.equals("present") ? 0 : Integer.parseInt(stb.nextToken());
    int by = !time.equals("present") ? 0 : Integer.parseInt(stb.nextToken());

    StringTokenizer ste = !t.equals("present") ? null : new StringTokenizer(end_date, "/");

    int em;
    if (!t.equals("present")) {
        em = 0;
    } else {
        em = Integer.parseInt(ste.nextToken());
    }

    int ed;
    if (!t.equals("present")) {
        ed = 0;
    } else {
        ed = Integer.parseInt(ste.nextToken());
    }

    int ey;
    if (!t.equals("present")) {
        ey = 0;
    } else {
        ey = Integer.parseInt(ste.nextToken());
    }

    String begin_hour = (String) metadata.get("begin_hour");
    String end_hour = (String) metadata.get("end_hour");
    String begin_min = (String) metadata.get("begin_min");
    String end_min = (String) metadata.get("end_min");
    String begin_sec = (String) metadata.get("begin_sec");
    String end_sec = (String) metadata.get("end_sec");

    int bHour = Integer.parseInt(begin_hour);
    int bMin = Integer.parseInt(begin_min);
    int bSec = Integer.parseInt(begin_sec);

    int eHour = Integer.parseInt(end_hour);
    int eMin = Integer.parseInt(end_min);
    int eSec = Integer.parseInt(end_sec);

    String begin_month;
    String begin_day;
    String begin_year;

    String end_month;
    String end_day;
    String end_year;

    boolean earlier = true;

    if ((by < ey) || (by == ey && bm < em) || (by == ey && bm == em && bd < ed)
            || (by == ey && bm == em && bd == ed && bHour < eHour)
            || (by == ey && bm == em && bd == ed && bHour == eHour && bMin < eMin)
            || (by == ey && bm == em && bd == ed && bHour == eHour && bMin == eMin && bSec <= eSec)) {

        // begin date and time is earlier
        begin_month = Integer.toString(bm);
        begin_day = Integer.toString(bd);
        begin_year = Integer.toString(by);

        end_month = Integer.toString(em);
        end_day = Integer.toString(ed);
        end_year = Integer.toString(ey);

    } else {

        earlier = false;

        begin_month = Integer.toString(em);
        begin_day = Integer.toString(ed);
        begin_year = Integer.toString(ey);

        end_month = Integer.toString(bm);
        end_day = Integer.toString(bd);
        end_year = Integer.toString(by);

        String tmp = begin_hour;
        begin_hour = end_hour;
        end_hour = tmp;

        tmp = begin_min;
        begin_min = end_min;
        end_min = tmp;

        tmp = begin_sec;
        begin_sec = end_sec;
        end_sec = tmp;

    }

    String time_choice;
    if (by >= 0 && ey >= 0) {
        time_choice = "AD";
    } else if (by < 0 && ey < 0) {
        time_choice = "BC";
    } else {
        time_choice = "direct";
    }

    String bc_begin_year = earlier ? Integer.toString(-by) : Integer.toString(-ey);
    String bc_end_year = earlier ? Integer.toString(-ey) : Integer.toString(-by);

    String d_begin_year = earlier ? Integer.toString(-by) : Integer.toString(-ey);
    String d_end_year = earlier ? Integer.toString(ey) : Integer.toString(by);

    try {
        ObjectFactory factory = new ObjectFactory();

        ADNmetadataType itemRecord = (ADNmetadataType) factory
                .newInstance(Class.forName("org.dlese.adn.ItemRecord"));

        // //////////////////////////////////////////////////////////
        // //
        // // general
        // //
        // /////////////////////////////////////////////////////////
        GeneralType general = (GeneralType) factory.newInstance(Class.forName("org.dlese.adn.GeneralType"));
        general.setTitle(title);
        general.setDescription(description);
        general.setLanguage("en");

        // subjects
        SubjectsType subjects = (SubjectsType) factory.newInstance(Class.forName("org.dlese.adn.SubjectsType"));
        general.setSubjects(subjects);
        subjects.getSubject().add(subjectss);

        // keywords
        if (keywords != null) {
            KeywordsType keywordsType = (KeywordsType) factory
                    .newInstance(Class.forName("org.dlese.adn.KeywordsType"));

            general.setKeywords(keywordsType);
            StringTokenizer st = new StringTokenizer(keywords, ",");
            while (st.hasMoreTokens()) {
                String tmp = st.nextToken().trim();
                KeywordType keyword = (KeywordType) factory
                        .newInstance(Class.forName("org.dlese.adn.KeywordType"));
                keyword.setValue(tmp);
                keywordsType.getKeyword().add(keyword);
            }
        }
        // lifecycle
        LifecycleType lifecycle = (LifecycleType) factory
                .newInstance(Class.forName("org.dlese.adn.LifecycleType"));

        // set the first contributor
        ContributorsLifecycleType contributors = (ContributorsLifecycleType) factory
                .newInstance(Class.forName("org.dlese.adn.ContributorsLifecycleType"));
        lifecycle.setContributors(contributors);

        ContributorLifecycleType author = (ContributorLifecycleType) factory
                .newInstance(Class.forName("org.dlese.adn.ContributorLifecycleType"));
        author.setRole(role1);

        if (personOrOrg1.equals("Person")) {
            PersonType person = (PersonType) factory.newInstance(Class.forName("org.dlese.adn.PersonType"));
            person.setNameTitle(nametitle1);
            person.setNameFirst(firstname1);
            person.setNameMiddle(middlename1);
            person.setNameLast(lastname1);
            person.setInstName(org1);
            person.setEmailPrimary(email1);
            author.setPerson(person);

            contributors.getContributor().add(author);
        } else {
            OrganizationType org = (OrganizationType) factory
                    .newInstance(Class.forName("org.dlese.adn.OrganizationType"));
            org.setInstName(org1);
            contributors.getContributor().add(org);
        }

        // //////////////////////////////////////////////////////////
        // //
        // // metametadata
        // //
        // /////////////////////////////////////////////////////////
        MetaMetadataType metaMetadata = (MetaMetadataType) factory
                .newInstance(Class.forName("org.dlese.adn.MetaMetadataType"));
        CatalogEntriesType catalogEntries = (CatalogEntriesType) factory
                .newInstance(Class.forName("org.dlese.adn.CatalogEntriesType"));

        CatalogType catalog = (CatalogType) factory.newInstance(Class.forName("org.dlese.adn.CatalogType"));
        catalog.setValue("shapefile");

        // get unique id
        // UUIDGenerator ug = UUIDGenerator.getInstance();
        // UUID uuid = ug.generateTimeBasedUUID();

        UUIDGen uuidgen = new UUIDGen();
        String uuid = uuidgen.generateUUID();

        catalog.setEntry("GEON-" + uuid);
        catalogEntries.getCatalog().add(catalog);
        metaMetadata.setCatalogEntries(catalogEntries);

        DateInfoType dateInfo = (DateInfoType) factory.newInstance(Class.forName("org.dlese.adn.DateInfoType"));
        Calendar now = Calendar.getInstance();
        // dateInfo.setCreated(now.get(Calendar.YEAR)+"-"+now.get(Calendar.MONTH)+"-"+now.get(Calendar.DAY_OF_MONTH));
        dateInfo.setCreated(now);
        dateInfo.setValue("Registered");
        metaMetadata.setDateInfo(dateInfo);

        StatusOfType statusOf = (StatusOfType) factory.newInstance(Class.forName("org.dlese.adn.StatusOfType"));
        statusOf.setStatus("Submitted");
        statusOf.setValue("Submitted");
        metaMetadata.setStatusOf(statusOf);

        metaMetadata.setLanguage("en");
        metaMetadata.setCopyright("No");
        metaMetadata.setScheme("No scheme");

        TermsOfUseType termsOfUse = (TermsOfUseType) factory
                .newInstance(Class.forName("org.dlese.adn.TermsOfUseType"));
        termsOfUse.setValue("Terms of use consistent with GEON policy.");
        metaMetadata.setTermsOfUse(termsOfUse);

        // //////////////////////////////////////////////////////////
        // //
        // // technical
        // //
        // /////////////////////////////////////////////////////////
        TechnicalType technical = (TechnicalType) factory
                .newInstance(Class.forName("org.dlese.adn.TechnicalType"));
        OnlineType online = (OnlineType) factory.newInstance(Class.forName("org.dlese.adn.OnlineType"));
        online.setPrimaryURL("http://www.geongrid.org");

        RequirementsType requirements = (RequirementsType) factory
                .newInstance(Class.forName("org.dlese.adn.RequirementsType"));
        online.setRequirements(requirements);

        RequirementType requirement = (RequirementType) factory
                .newInstance(Class.forName("org.dlese.adn.RequirementType"));
        requirement.setReqType("DLESE:General:No specific technical requirements");
        requirements.getRequirement().add(requirement);

        technical.setOnline(online);

        // //////////////////////////////////////////////////////////
        // //
        // // right
        // //
        // /////////////////////////////////////////////////////////
        RightsType rights = (RightsType) factory.newInstance(Class.forName("org.dlese.adn.RightsType"));

        rights.setDescription(permission);
        rights.setCost("DLESE:No");

        // //////////////////////////////////////////////////////////
        // //
        // // relation
        // //
        // /////////////////////////////////////////////////////////
        RelationsType relations = (RelationsType) factory
                .newInstance(Class.forName("org.dlese.adn.RelationsType"));

        // //////////////////////////////////////////////////////////
        // //
        // // spatial coverage
        // //
        // /////////////////////////////////////////////////////////
        GeospatialCoveragesType geospatialCoverages = (GeospatialCoveragesType) factory
                .newInstance(Class.forName("org.dlese.adn.GeospatialCoveragesType"));

        GeospatialCoverageType geospatialCoverage = (GeospatialCoverageType) factory
                .newInstance(Class.forName("org.dlese.adn.GeospatialCoverageType"));

        BodyType body = (BodyType) factory.newInstance(Class.forName("org.dlese.adn.BodyType"));
        body.setPlanet("Earth");
        geospatialCoverage.setBody(body);

        geospatialCoverage.setGeodeticDatumGlobalOrHorz(hrizontal);

        ProjectionType proj = (ProjectionType) factory
                .newInstance(Class.forName("org.dlese.adn.ProjectionType"));
        proj.setType(projection);
        proj.setValue("Some projections here");
        geospatialCoverage.setProjection(proj);

        CoordinateSystemType coord = (CoordinateSystemType) factory
                .newInstance(Class.forName("org.dlese.adn.CoordinateSystemType"));
        coord.setType(coordinate);
        coord.setValue("Some cordinate system here");
        geospatialCoverage.setCoordinateSystem(coord);

        BoundBoxType box = (BoundBoxType) factory.newInstance(Class.forName("org.dlese.adn.BoundBoxType"));
        box.setBbSrcName("Cataloger supplied");

        /*
         * VertType vert =
         * (VertType)factory.newInstance(Class.forName("org.dlese.adn.VertType"
         * )); VertMinMaxType min =
         * (VertMinMaxType)factory.newInstance(Class
         * .forName("org.dlese.adn.VertMinMaxType"));
         * min.setUnits("centimeters (cm)"); min.setValue(new
         * BigDecimal(min_altitude[0]));
         * 
         * VertMinMaxType max =
         * (VertMinMaxType)factory.newInstance(Class.forName
         * ("org.dlese.adn.VertMinMaxType"));
         * max.setUnits("centimeters (cm)"); max.setValue(new
         * BigDecimal(max_altitude[0]));
         * 
         * vert.setVertMin(min); vert.setVertMax(max);
         * vert.setGeodeticDatumGlobalOrVert("DLESE:CGD28-CDN");
         * vert.setVertBase("Datum level");
         * 
         * box.setBbVert(vert);
         */

        geospatialCoverage.setBoundBox(box);
        // geospatialCoverage.setDetGeos();

        geospatialCoverages.getGeospatialCoverage().add(geospatialCoverage);

        // //////////////////////////////////////////////////////////
        // //
        // // temporal coverage
        // //
        // /////////////////////////////////////////////////////////
        TemporalCoveragesType temporalCoverages = (TemporalCoveragesType) factory
                .newInstance(Class.forName("org.dlese.adn.TemporalCoveragesType"));
        TimeAndPeriodType timeAndPeriod = (TimeAndPeriodType) factory
                .newInstance(Class.forName("org.dlese.adn.TimeAndPeriodType"));
        temporalCoverages.getTimeAndPeriod().add(timeAndPeriod);

        // set time directly into relativeTime
        TimeInfoType timeInfo = (TimeInfoType) factory.newInstance(Class.forName("org.dlese.adn.TimeInfoType"));

        timeAndPeriod.setTimeInfo(timeInfo);

        if (time.equals("notpresent")) {
            if (geologic_time.equals("other")) {

                TimeRelativeType timeRelative = (TimeRelativeType) factory
                        .newInstance(Class.forName("org.dlese.adn.TimeRelativeType"));
                timeInfo.setTimeRelative(timeRelative);

                RelativeType begin = (RelativeType) factory
                        .newInstance(Class.forName("org.dlese.adn.RelativeType"));
                timeRelative.setBegin(begin);
                begin.setValue(new BigDecimal(begin_age));
                begin.setUnits("ma");

                RelativeType end = (RelativeType) factory
                        .newInstance(Class.forName("org.dlese.adn.RelativeType"));
                timeRelative.setEnd(end);
                end.setValue(new BigDecimal(end_age));
                end.setUnits("ma");

            } else {

                TimeRelativeType timeRelative = (TimeRelativeType) factory
                        .newInstance(Class.forName("org.dlese.adn.TimeRelativeType"));
                timeInfo.setTimeRelative(timeRelative);

                RelativeType begin = (RelativeType) factory
                        .newInstance(Class.forName("org.dlese.adn.RelativeType"));
                timeRelative.setBegin(begin);
                begin.setValue(new BigDecimal(0));
                begin.setUnits("ma");

                RelativeType end = (RelativeType) factory
                        .newInstance(Class.forName("org.dlese.adn.RelativeType"));
                timeRelative.setEnd(end);
                end.setValue(new BigDecimal(0));
                end.setUnits("ma");

                // set time to periods
                PeriodsType periods = (PeriodsType) factory
                        .newInstance(Class.forName("org.dlese.adn.PeriodsType"));
                timeAndPeriod.setPeriods(periods);

                PeriodType period = (PeriodType) factory.newInstance(Class.forName("org.dlese.adn.PeriodType"));
                periods.getPeriod().add(period);
                period.setName(geologic_time);
                period.setSource("USGS-Geologic-Time-Scale");

            }
        } else if (time.equals("present")) {

            // set time directly into timeAD or timeBC
            if (time_choice.equals("AD")) {

                TimeADType timeAD = (TimeADType) factory.newInstance(Class.forName("org.dlese.adn.TimeADType"));
                timeInfo.setTimeAD(timeAD);

                Calendar begin = Calendar.getInstance();
                begin.clear();

                begin.add(Calendar.YEAR, Integer.parseInt(begin_year) - 1970);
                begin.add(Calendar.MONTH, Integer.parseInt(begin_month) - 1);
                begin.add(Calendar.DAY_OF_MONTH, Integer.parseInt(begin_day) - 1);

                Calendar bt = Calendar.getInstance();
                bt.clear();

                bt.add(Calendar.HOUR, Integer.parseInt(begin_hour));
                bt.add(Calendar.MINUTE, Integer.parseInt(begin_min));
                bt.add(Calendar.SECOND, Integer.parseInt(begin_sec));

                Calendar end = Calendar.getInstance();
                end.clear();
                end.add(Calendar.YEAR, Integer.parseInt(end_year) - 1970);
                end.add(Calendar.MONTH, Integer.parseInt(end_month) - 1);
                end.add(Calendar.DAY_OF_MONTH, Integer.parseInt(end_day) - 1);

                Calendar et = Calendar.getInstance();
                et.clear();

                et.add(Calendar.HOUR, Integer.parseInt(end_hour));
                et.add(Calendar.MINUTE, Integer.parseInt(end_min));
                et.add(Calendar.SECOND, Integer.parseInt(end_sec));

                ADType tmp = (ADType) factory.newInstance(Class.forName("org.dlese.adn.ADType"));
                tmp.setDate(begin);
                tmp.setTime(bt);
                tmp.setValue("");
                timeAD.setBegin(tmp);

                tmp = (ADType) factory.newInstance(Class.forName("org.dlese.adn.ADType"));
                tmp.setDate(end);
                tmp.setTime(et);
                tmp.setValue("");
                timeAD.setEnd(tmp);

            } else if (time_choice.equals("BC")) {

                TimeBCType timeBC = (TimeBCType) factory.newInstance(Class.forName("org.dlese.adn.TimeBCType"));
                timeInfo.setTimeBC(timeBC);

                timeBC.setBegin(bc_begin_year);
                timeBC.setEnd(bc_end_year);

            } else if (time_choice.equals("direct")) {

                TimeRelativeType timeRelative = (TimeRelativeType) factory
                        .newInstance(Class.forName("org.dlese.adn.TimeRelativeType"));
                timeInfo.setTimeRelative(timeRelative);

                RelativeType begin = (RelativeType) factory
                        .newInstance(Class.forName("org.dlese.adn.RelativeType"));
                timeRelative.setBegin(begin);
                begin.setValue(new BigDecimal("-" + d_begin_year));
                begin.setUnits("year");

                RelativeType end = (RelativeType) factory
                        .newInstance(Class.forName("org.dlese.adn.RelativeType"));
                timeRelative.setEnd(end);
                end.setValue(new BigDecimal(d_end_year));
                end.setUnits("year");

            }
        }

        // handle object in space
        ObjectsInSpaceType objectsInSpace = (ObjectsInSpaceType) factory
                .newInstance(Class.forName("org.dlese.adn.ObjectsInSpaceType"));

        itemRecord.setGeneral(general);
        itemRecord.setLifecycle(lifecycle);
        itemRecord.setMetaMetadata(metaMetadata);
        itemRecord.setRights(rights);
        itemRecord.setTechnical(technical);
        // itemRecord.setRelations(relations);
        itemRecord.setGeospatialCoverages(geospatialCoverages);
        if (!time.equals("any")) {
            itemRecord.setTemporalCoverages(temporalCoverages);
        }
        itemRecord.setObjectsInSpace(objectsInSpace);

        // marshall
        JAXBContext jc = JAXBContext.newInstance("org.dlese.adn");
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        // create and save target

        // save into a directory
        File dir = new File("adn/" + uuid); // TODO: remove adn folder once
        // all the files have been
        // removed.
        dir.mkdirs();
        dirPath = dir.getAbsolutePath();

        // unzip the uploaded file
        String shpFile = shpURL;
        String unzipFileName = "";
        if (shpFile.trim().startsWith("http://")) {
            URL shpURL = new URL(shpFile);
            HttpURLConnection huc = (HttpURLConnection) shpURL.openConnection();
            huc.connect();
            InputStream in = huc.getInputStream();
            File zip = new File(dir, "tmp.zip");
            FileOutputStream out = new FileOutputStream(zip);
            byte[] buffer = new byte[1024];
            int count = in.read(buffer);
            while (count > 0) {
                out.write(buffer, 0, count);
                count = in.read(buffer);
            }
            huc.disconnect();
            out.close();
            unzipFileName = unzip(dir, zip); // Unzipping the ftpped file to
            // dir.
            zip.delete(); // the zip file is no longer necessary.
        } else if (shpFile.trim().startsWith("ftp://")) {
            shpFile = shpFile.substring(6);
            String username = "anonymous";
            String password = "geon@geongrid.org";
            int index = shpFile.indexOf("/");
            String hostname = shpFile.substring(0, index);
            String filename = shpFile.substring(index);
            org.apache.commons.net.ftp.FTPClient f = new org.apache.commons.net.ftp.FTPClient();
            f.connect(hostname);
            f.login(username, password);
            f.setFileType(FTP.BINARY_FILE_TYPE);
            File zip = new File(dir, "tmp.zip");
            FileOutputStream fos = new FileOutputStream(zip);
            f.retrieveFile(filename, fos);
            f.disconnect();
            fos.close();
            unzipFileName = unzip(dir, zip); // Unzipping the ftpped file to
            // dir.
            zip.delete(); // the zip file is no longer necessary.

        } else { // file is local..
            java.io.File zip = new java.io.File(shpFile);
            unzipFileName = unzip(dir, zip);
        }

        if (!unzipFileName.equals("")) {
            // calculate the binding box and set the adn schema
            shpfis = new FileInputStream(dirPath + "/" + unzipFileName + ".shp");
            Shapefile shape = new Shapefile(shpfis);
            double[] bounds = shape.getBounds();

            box.setWestCoord(new BigDecimal(bounds[0]));
            box.setNorthCoord(new BigDecimal(bounds[1]));
            box.setEastCoord(new BigDecimal(bounds[2]));
            box.setSouthCoord(new BigDecimal(bounds[3]));

            shpfis.close();
            // Object x = (Object) shape;

            // shape = new Shapefile();

            /*
             * File shp = new File(dir, unzipFileName + ".shp"); File shx =
             * new File(dir, unzipFileName + ".shx"); File dbf = new
             * File(dir, unzipFileName + ".dbf");
             * 
             * 
             * shp.delete(); shx.delete(); dbf.delete(); //dir.delete();
             */
        }
        /*
         * // calculate the schema and ask for more explanation DBase db =
         * new DBase(dirName); db.openTable(fileName); String [] columns =
         * db.getColumnNames(); ArrayList list = new ArrayList(); for (int
         * i=0; i<columns.length; i++) { list.add(columns[i]); }
         */// save its metadata
        File adn = new File(dir, uuid + ".adn");
        FileOutputStream fos = new FileOutputStream(adn);
        m.marshal(itemRecord, fos);
        fos.close();

        /*
         * } catch (Exception e) {
         * 
         * try { PrintWriter pw = new PrintWriter(new
         * FileWriter("/home/jaeger/log.txt", true)); e.printStackTrace(pw);
         * pw.flush(); } catch (Exception ex) {}
         * 
         * throw new JspException(e.getMessage()); } return SKIP_BODY; }
         * 
         * 
         * 
         * private String label(String string) { return
         * "<table width=90% cellpadding=1 cellspacing=0 border=0>\n"+
         * "<tr><td bgcolor=Gainsboro>\n"+
         * "<font face=\"arial,sans-serif\" size=-1 color=#777777>\n"+
         * "&nbsp; <b>"+string+"</b>\n"+ "</font>\n"+ "</td></tr>\n"+
         * "</table>\n"; }
         * 
         * 
         * private String message(String key, String val) { return
         * "    <tr>\n" +
         * "        <td align=right width=150><div class=label><b>"
         * +key+":</b></div></td>\n" +
         * "        <td align=left>"+val+"</td>\n" + "    </tr>\n"; }
         * 
         * 
         * private String messagePadding(String key, String val) { return
         * "    <tr>\n" +
         * "        <td align=right width=150><div class=label>&nbsp;&nbsp;&nbsp;"
         * +key+":</div></td>\n" + "        <td align=left>"+val+"</td>\n" +
         * "    </tr>\n"; }
         */
        return adn.getAbsolutePath();
    } catch (ClassNotFoundException cnfex) {
        cnfex.printStackTrace();
        _deleteFiles();
    } catch (JAXBException jex) {
        jex.printStackTrace();
        _deleteFiles();
    } catch (FileNotFoundException fnex) {
        fnex.printStackTrace();
        _deleteFiles();
    } catch (IOException ioex) {
        ioex.printStackTrace();
        _deleteFiles();
    } catch (ShapefileException shex) {
        shex.printStackTrace();
        _deleteFiles();
    } catch (Exception ex) {
        ex.printStackTrace();
        _deleteFiles();
    }
    return "";

}

From source file:org.gitools.datasources.obo.OBOStream.java

public OBOStream(URL baseUrl) throws IOException {
    this.baseUrl = baseUrl;

    // Workaround for FTP problem connecting ftp.geneontology.org with URL.openStream()
    if (baseUrl.getProtocol().equalsIgnoreCase("ftp")) {
        FTPClient ftp = new FTPClient();
        if (baseUrl.getPort() != -1) {
            ftp.connect(baseUrl.getHost(), baseUrl.getPort());
        } else {/*from   w  w  w  .ja  va2s . c  om*/
            ftp.connect(baseUrl.getHost());
        }
        ftp.login("anonymous", "");
        ftp.enterLocalPassiveMode();
        ftp.setControlKeepAliveTimeout(60);
        InputStream is = ftp.retrieveFileStream(baseUrl.getPath());
        this.reader = new BufferedReader(new InputStreamReader(is));
    } else {
        this.reader = new BufferedReader(new InputStreamReader(baseUrl.openStream()));
    }

    this.linePos = 0;
}