Example usage for java.io IOException printStackTrace

List of usage examples for java.io IOException printStackTrace

Introduction

In this page you can find the example usage for java.io IOException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:fm.last.irccat.IRCCat.java

public static void main(String[] args) throws Exception {
    try {/* w  w w  .j a  v a2 s.  c  o m*/
        if (args.length == 0) {
            System.out.println("first param should be config file");
            System.exit(-1);
        }
        XMLConfiguration c = null;
        try {
            c = new XMLConfiguration(args[0]);
        } catch (ConfigurationException cex) {
            System.err.println("Configuration error, check config file");
            cex.printStackTrace();
            System.exit(1);
        }

        IRCCat bot = new IRCCat(c);

        // listen for stuff and send it to irc:
        ServerSocket serverSocket = null;
        InetAddress inet = null;
        try {
            if (bot.getCatIP() != null)
                inet = InetAddress.getByName(bot.getCatIP());
        } catch (UnknownHostException ex) {
            System.out.println("Could not resolve config cat.ip, fix your config");
            ex.printStackTrace();
            System.exit(2);
        }

        try {
            serverSocket = new ServerSocket(bot.getCatPort(), 0, inet);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + bot.getCatPort());
            System.exit(1);
        }

        System.out.println("Listening on " + bot.getCatIP() + " : " + bot.getCatPort());

        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                // System.out.println("Connection on catport from: "
                // + clientSocket.getInetAddress().toString());
                CatHandler handler = new CatHandler(clientSocket, bot);
                handler.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:fr.bmartel.protocol.google.main.LaunchOauthApiServer.java

/**
 * The main method.//w  ww .  j a  v  a2  s .  c  om
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    webPath = "";
    clientId = "";
    clientSecret = "";

    if (args.length == 3) {

        for (int i = 0; i < 3; i++) {
            if (args[i].toLowerCase().startsWith("webpath="))
                webPath = args[i].substring(args[i].indexOf("webpath=") + "webpath=".length() + 1,
                        args[i].length());
            if (args[i].toLowerCase().startsWith("clientid="))
                clientId = args[i].substring(args[i].indexOf("clientid=") + "clientid=".length() + 1,
                        args[i].length());
            if (args[i].toLowerCase().startsWith("clientsecret="))
                clientSecret = args[i].substring(
                        args[i].indexOf("clientsecret=") + "clientsecret=".length() + 1, args[i].length());
        }

        if (webPath.equals("")) {
            printHelp("Error web path is missing");
            return;
        } else if (clientId.equals("")) {
            printHelp("Error client Id is missing");
            return;
        } else if (clientSecret.equals("")) {
            printHelp("Error client secret is missing");
            return;
        }
    } else {
        printHelp("");
        return;
    }
    // start http server
    HttpServer server = new HttpServer(SERVER_PORT);

    websocketServer = new WebsocketServer(WEBSOCKET_SERVER_PORT);

    websocketServer.addServerEventListener(new IClientEventListener() {

        @SuppressWarnings("unchecked")
        @Override
        public void onMessageReceivedFromClient(final IWebsocketClient client, String message) {

            JSONObject obj = (JSONObject) JSONValue.parse(message);

            if (obj != null && obj.containsKey(JsonConstants.API_ACTION)) {

                System.out.println("[API] > " + obj.toJSONString());

                String action = obj.get(JsonConstants.API_ACTION).toString();

                if (action != null) {
                    if (action.equals(JsonConstants.API_REGISTRATION_STATE)) {

                        JSONObject registrationResponse = new JSONObject();

                        if (calendarNotifManager != null
                                && calendarNotifManager.getOauthRegistration() != null) {

                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE,
                                    calendarNotifManager.getOauthRegistration().getDeviceCode());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE,
                                    calendarNotifManager.getOauthRegistration().getExpiringBefore());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL,
                                    calendarNotifManager.getOauthRegistration().getInterval());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE,
                                    calendarNotifManager.getOauthRegistration().getUserCode());
                            registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL,
                                    calendarNotifManager.getOauthRegistration().getVerificationUrl());

                        }

                        System.out.println("[API] < " + registrationResponse.toJSONString());
                        client.sendMessage(registrationResponse.toJSONString());

                    } else if (action.equals(JsonConstants.API_TOKEN_STATE)) {

                        JSONObject requestTokenResponse = new JSONObject();

                        if (calendarNotifManager != null && calendarNotifManager.getCurrentToken() != null) {

                            requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN,
                                    calendarNotifManager.getCurrentToken().getAccessToken());
                            requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE,
                                    calendarNotifManager.getCurrentToken().getTokenType());
                            requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN,
                                    calendarNotifManager.getCurrentToken().getExpiresIn());

                        }
                        System.out.println("[API] < " + requestTokenResponse.toJSONString());
                        client.sendMessage(requestTokenResponse.toJSONString());

                    } else if (action.equals(JsonConstants.API_REGISTRATION)) {

                        calendarNotifManager = new CalendarNotifManager(clientId, clientSecret);

                        calendarNotifManager.requestDeviceAuth(new IOauthDeviceResponseListener() {

                            @Override
                            public void onResponseReceived(OauthForDeviceResponse response) {
                                if (response != null) {
                                    JSONObject registrationResponse = new JSONObject();
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_DEVICE_CODE,
                                            response.getDeviceCode());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRING_BEFORE,
                                            response.getExpiringBefore());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_INTERVAL,
                                            response.getInterval());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_USERCODE,
                                            response.getUserCode());
                                    registrationResponse.put(JsonConstants.GOOGLE_OAUTH_VERIFICATION_URL,
                                            response.getVerificationUrl());

                                    System.out.println("[API] < " + registrationResponse.toJSONString());

                                    client.sendMessage(registrationResponse.toJSONString());
                                }
                            }
                        });
                    } else if (action.equals(JsonConstants.API_REQUEST_TOKEN)) {

                        if (calendarNotifManager != null) {
                            calendarNotifManager.requestToken(new IRequestTokenListener() {

                                @Override
                                public void onRequestTokenReceived(OauthToken token) {
                                    if (token != null) {
                                        JSONObject requestTokenResponse = new JSONObject();
                                        requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_ACCESS_TOKEN,
                                                token.getAccessToken());
                                        requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_TOKEN_TYPE,
                                                token.getTokenType());
                                        requestTokenResponse.put(JsonConstants.GOOGLE_OAUTH_EXPIRE_IN,
                                                token.getExpiresIn());

                                        System.out.println("[API] < " + requestTokenResponse.toJSONString());

                                        client.sendMessage(requestTokenResponse.toJSONString());
                                    }
                                }

                                @Override
                                public void onRequestTokenError(String description) {
                                    String response = "{\"error\":\"request token error\",\"error_description\":\""
                                            + description + "\"}";

                                    System.out.println("[API] < " + response);

                                    client.sendMessage(response);
                                }
                            });
                        }
                    } else if (action.equals(JsonConstants.API_REVOKE_TOKEN)) {

                        if (calendarNotifManager != null) {
                            calendarNotifManager.revokeToken(new IRevokeTokenListener() {

                                @Override
                                public void onSuccess() {

                                    System.out.println("[API] < " + "{\"revokeToken\":\"success\"}");

                                    client.sendMessage("{\"revokeToken\":\"success\"}");
                                }

                                @Override
                                public void onError(String description) {

                                    String response = "{\"error\":\"request token error\",\"error_description\":\""
                                            + description + "\"}";

                                    System.out.println("[API] < " + response);

                                    client.sendMessage(response);
                                }
                            });
                        }
                    } else if (action.equals(JsonConstants.API_USER_PROFILE)) {
                        if (calendarNotifManager != null) {
                            calendarNotifManager.getUserProfileManager()
                                    .getUserProfile(new IUserProfileListener() {

                                        @Override
                                        public void onSuccess(UserProfile userProfile) {
                                            if (userProfile != null) {
                                                JSONObject userProfileResponse = new JSONObject();
                                                userProfileResponse.put(JsonConstants.GOOGLE_API_PROFILE_GENDER,
                                                        userProfile.getGender());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_DISPLAY_NAME,
                                                        userProfile.getDisplayName());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_FAMILY_NAME,
                                                        userProfile.getFamilyName());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_GIVEN_NAME,
                                                        userProfile.getGivenName());
                                                userProfileResponse.put(
                                                        JsonConstants.GOOGLE_API_PROFILE_LANGUAGE,
                                                        userProfile.getLanguage());

                                                System.out.println(
                                                        "[API] < " + userProfileResponse.toJSONString());

                                                client.sendMessage(userProfileResponse.toJSONString());
                                            }
                                        }

                                        @Override
                                        public void onError(String description) {

                                            String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                    + description + "\"}";

                                            System.out.println("[API] < " + response);

                                            client.sendMessage(response);
                                        }
                                    });
                        }
                    } else if (action.equals(JsonConstants.API_CREATE_EVENT)
                            && obj.containsKey(JsonConstants.API_DATE_BEGIN)
                            && obj.containsKey(JsonConstants.API_DATE_END)
                            && obj.containsKey(JsonConstants.API_SUMMARY)) {

                        String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString();
                        String dateEnd = obj.get(JsonConstants.API_DATE_END).toString();
                        String summary = obj.get(JsonConstants.API_SUMMARY).toString();

                        if (calendarNotifManager != null) {

                            calendarNotifManager.getCalendarManager().createEvent(dateBegin, dateEnd, summary,
                                    new ICreateEventListener() {

                                        @Override
                                        public void onError(String description) {

                                            String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                    + description + "\"}";

                                            System.out.println("[API] < " + response);

                                            client.sendMessage(
                                                    "{\"error\":\"request token error\",\"error_description\":\""
                                                            + description + "\"}");
                                        }

                                        @Override
                                        public void onCreateSuccess(String id) {

                                            String response = "{\"createEvent\":\"success\",\"eventId\":\"" + id
                                                    + "\"}";

                                            System.out.println("[API] < " + response);

                                            client.sendMessage(response);
                                        }
                                    });
                        }
                    } else if (action.equals(JsonConstants.API_DELETE_EVENT)
                            && obj.containsKey(JsonConstants.API_EVENT_ID)) {

                        final String eventId = obj.get(JsonConstants.API_EVENT_ID).toString();

                        calendarNotifManager.getCalendarManager().deleteEvent(eventId,
                                new IDeleteEventListener() {

                                    @Override
                                    public void onSuccess() {

                                        String response = "{\"deleteEvent\":\"success\",\"eventId\":\""
                                                + eventId + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }

                                    @Override
                                    public void onError(String description) {

                                        String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                + description + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }
                                });

                    } else if (action.equals(JsonConstants.API_GET_EVENTS)
                            && obj.containsKey(JsonConstants.API_DATE_BEGIN)
                            && obj.containsKey(JsonConstants.API_DATE_END) && obj.containsKey("searchText")
                            && calendarNotifManager != null) {

                        String dateBegin = obj.get(JsonConstants.API_DATE_BEGIN).toString();
                        String dateEnd = obj.get(JsonConstants.API_DATE_END).toString();
                        String searchText = obj.get(JsonConstants.API_SEARCH_TEXT).toString();

                        calendarNotifManager.getCalendarManager().getEventList(dateBegin, dateEnd, searchText,
                                new IEventListListener() {

                                    @Override
                                    public void onEventListReceived(List<CalendarEvents> calendarEventList) {

                                        String response = "{\"eventList\":" + CalendarUtils
                                                .convertCalendarListToJsonArray(calendarEventList)
                                                .toJSONString() + "}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }

                                    @Override
                                    public void onError(String description) {

                                        String response = "{\"error\":\"request token error\",\"error_description\":\""
                                                + description + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }
                                });

                    } else if (action.equals(JsonConstants.API_SUBSCRIBE_EVENT)
                            && obj.containsKey(JsonConstants.API_EVENT_ID)
                            && obj.containsKey(JsonConstants.API_TIME_ABOUT_TO_START)) {

                        String eventId = obj.get(JsonConstants.API_EVENT_ID).toString();
                        int timeAboutToStart = Integer
                                .parseInt(obj.get(JsonConstants.API_TIME_ABOUT_TO_START).toString());

                        calendarNotifManager.getNotificationManager().subscribeEvent(eventId, timeAboutToStart,
                                new IEventListener() {

                                    @Override
                                    public void onEventStart(String eventId, String summary) {

                                        String response = "{\"subscribedEvent\":\"" + eventId
                                                + "\",\"eventType\":\"started\",\"summary\":\"" + summary
                                                + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }

                                    @Override
                                    public void onEventAboutToStart(String eventId, String summary) {

                                        String response = "{\"subscribedEvent\":\"" + eventId
                                                + "\",\"eventType\":\"aboutToStart\",\"summary\":\"" + summary
                                                + "\"}";

                                        System.out.println("[API] < " + response);

                                        client.sendMessage(response);
                                    }
                                });

                    } else if (action.equals(JsonConstants.API_UNSUBSCRIBE_EVENT)
                            && obj.containsKey(JsonConstants.API_EVENT_ID)) {
                        String eventId = obj.get(JsonConstants.API_EVENT_ID).toString();

                        calendarNotifManager.getNotificationManager().unsubscribeEvent(eventId);
                    } else {
                        System.out.println("[API] Error api target is inconsistent");
                    }
                }
            }
        }

        @Override
        public void onClientConnection(IWebsocketClient client) {
            System.out.println("Websocket client connected");
        }

        @Override
        public void onClientClose(IWebsocketClient client) {
            System.out.println("Websocket client disconnected");
        }
    });

    Runnable websocketTask = new Runnable() {

        @Override
        public void run() {
            websocketServer.start();
        }
    };

    Thread thread = new Thread(websocketTask, "WEBSOCKET_THREAD");

    thread.start();

    server.addServerEventListener(new IHttpServerEventListener() {

        @Override
        public void onHttpFrameReceived(IHttpFrame httpFrame, HttpStates receptionStates,
                IHttpStream httpStream) {

            // check if http frame is OK
            if (receptionStates == HttpStates.HTTP_FRAME_OK) {

                // you can check here http frame type (response or request
                // frame)
                if (httpFrame.isHttpRequestFrame()) {

                    // we want to send a message to client for http GET
                    // request on page with uri /index
                    if (httpFrame.getMethod().equals("GET") && httpFrame.getUri().equals("/gcalendar")) {

                        String defaultPage = "";
                        try {
                            defaultPage = FileUtils.readFile(webPath + "/index.html", "UTF-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // return default html page for this HTTP Server
                        httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK,
                                new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes())
                                        .toString().getBytes());

                    } else if (httpFrame.getMethod().equals("GET")
                            && (httpFrame.getUri().endsWith(".css") || httpFrame.getUri().endsWith(".js"))) {

                        String defaultPage = "";
                        try {
                            defaultPage = FileUtils.readFile(webPath + httpFrame.getUri(), "UTF-8");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // return default html page for this HTTP Server
                        httpStream.writeHttpFrame(new HttpResponseFrame(StatusCodeList.OK,
                                new HttpVersion(1, 1), new HashMap<String, String>(), defaultPage.getBytes())
                                        .toString().getBytes());
                    }
                }
            }
        }
    });

    server.start();
    thread.interrupt();

}

From source file:eu.planets_project.tb.gui.backing.exp.ExpTypeMigrate.java

public static void main(String args[]) {

    Properties p = System.getProperties();

    ByteArrayOutputStream byos = new ByteArrayOutputStream();
    try {/* www .  ja v  a  2s. c o  m*/
        p.storeToXML(byos, "Automatically generated for PLANETS Service ", "UTF-8");
        String res = byos.toString("UTF-8");
        System.out.println(res);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // This.
    List<String> pl = new ArrayList<String>();
    for (Object key : p.keySet()) {
        pl.add((String) key);
    }
    Collections.sort(pl);

    //
    for (String key : pl) {
        System.out.println(key + " = " + p.getProperty(key));
    }

    /*
     * http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ThreadMXBean.html#getCurrentThreadCpuTime()
     * 
     * http://www.java-forums.org/new-java/5303-how-determine-cpu-usage-using-java.html
     * 
     */

    ThreadMXBean TMB = ManagementFactory.getThreadMXBean();
    int mscale = 1000000;
    long time = 0, time2 = 0;
    long cput = 0, cput2 = 0;
    double cpuperc = -1;

    //Begin loop.
    for (int i = 0; i < 10; i++) {

        if (TMB.isThreadCpuTimeSupported()) {
            if (!TMB.isThreadCpuTimeEnabled()) {
                TMB.setThreadCpuTimeEnabled(true);
            }

            //                if(new Date().getTime() * mscale - time > 1000000000) //Reset once per second
            //                {
            System.out.println("Resetting...");
            time = System.currentTimeMillis() * mscale;
            cput = TMB.getCurrentThreadCpuTime();
            //                cput = TMB.getCurrentThreadUserTime();
            //                }

        }

        //Do cpu intensive stuff
        for (int k = 0; k < 10; k++) {
            for (int j = 0; j < 100000; j++) {
                double a = Math.pow(i, j);
                double b = a / j + Math.random();
                a = b * Math.random();
                b = a * Math.random();
            }

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        if (TMB.isThreadCpuTimeSupported()) {
            //                if(new Date().getTime() * mscale - time != 0) {
            cput2 = TMB.getCurrentThreadCpuTime();
            System.out.println("cpu: " + (cput2 - cput) / (1000.0 * mscale));
            //                cput2 = TMB.getCurrentThreadUserTime();

            time2 = System.currentTimeMillis() * mscale;
            System.out.println("time: " + (time2 - time) / (1000.0 * mscale));

            cpuperc = 100.0 * (cput2 - cput) / (double) (time2 - time);
            System.out.println("cpu perc = " + cpuperc);
            //                }
        }
        //End Loop
    }
    System.out.println("Done.");
}

From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException, Exception {
    // MY CODE/*from w w w  .  j  ava 2  s.  c  om*/
    if (crypto(Collections.unmodifiableList(Arrays.asList(args)))) {
        return;
    }
    ;
    // MY CODE -- END

    boolean storeFile = false, binaryTransfer = true, error = false, listFiles = false, listNames = false,
            hidden = false;
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        }
        // Always use binary transfer 
        //            else if (args[base].equals("-b")) {
        //                binaryTransfer = true;
        //            }
        else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);
            // MY CODE
            byte[] bytes = IOUtils.toByteArray(input);
            InputStream encrypted = new ByteArrayInputStream(cryptor.encrypt(bytes));
            // MY CODE -- END
            ftp.storeFile(remote, encrypted);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            // MY CODE
            ByteArrayOutputStream remoteFile = new ByteArrayOutputStream();
            //InputStream byteIn = new ByteArrayInputStream(buf);
            ftp.retrieveFile(remote, remoteFile);
            remoteFile.flush();
            Optional<byte[]> opt = cryptor.decrypt(remoteFile.toByteArray());
            if (opt.isPresent()) {
                output.write(opt.get());
            }
            remoteFile.close();
            // MY CODE -- END
            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

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

public static void main(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;//from   w  ww.  jav  a  2 s .  c o m
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false, mdtm = false, saveUnparseable = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;
    String encoding = null;
    String serverTimeZoneId = null;
    String displayTimeZoneId = null;
    String serverType = null;
    String defaultDateFormat = null;
    String recentDateFormat = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-E")) {
            encoding = args[++base];
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-m")) {
            mdtm = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-S")) {
            serverType = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-U")) {
            saveUnparseable = true;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-y")) {
            defaultDateFormat = args[++base];
        } else if (args[base].equals("-Y")) {
            recentDateFormat = args[++base];
        } else if (args[base].equals("-Z")) {
            serverTimeZoneId = args[++base];
        } else if (args[base].equals("-z")) {
            displayTimeZoneId = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String[] parts = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        if (args.length > 0) {
            System.err.println("Actual Parameters: " + Arrays.toString(args));
        }
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String[] parts = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String[] prot = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (encoding != null) {
        ftp.setControlEncoding(encoding);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    final FTPClientConfig config;
    if (serverType != null) {
        config = new FTPClientConfig(serverType);
    } else {
        config = new FTPClientConfig();
    }
    config.setUnparseableEntries(saveUnparseable);
    if (defaultDateFormat != null) {
        config.setDefaultDateFormatStr(defaultDateFormat);
    }
    if (recentDateFormat != null) {
        config.setRecentDateFormatStr(recentDateFormat);
    }
    ftp.configure(config);

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to
        // verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should
            // default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        }
        // Allow multiple list types for single invocation
        else if (listFiles || mlsd || mdtm || mlst || listNames) {
            if (mlsd) {
                for (FTPFile f : ftp.mlistDir(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
            if (mdtm) {
                FTPFile f = ftp.mdtmFile(remote);
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString(displayTimeZoneId));
            }
            if (mlst) {
                FTPFile f = ftp.mlistFile(remote);
                if (f != null) {
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
            if (listNames) {
                for (String s : ftp.listNames(remote)) {
                    System.out.println(s);
                }
            }
            // Do this last because it changes the client
            if (listFiles) {
                if (lenient || serverTimeZoneId != null) {
                    config.setLenientFutureDates(lenient);
                    if (serverTimeZoneId != null) {
                        config.setServerTimeZoneId(serverTimeZoneId);
                    }
                    ftp.configure(config);
                }

                for (FTPFile f : ftp.listFiles(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    // Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                // Command listener has already printed the output
                // for(String s : com.xzr.practice.util.ftp.getReplyStrings()) {
                // System.out.println(s);
                // }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:demo.FTP.FTPClientExample.java

public static void main(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;/* w ww . j a v a 2 s. c o m*/
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false, mdtm = false, saveUnparseable = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;
    String encoding = null;
    String serverTimeZoneId = null;
    String displayTimeZoneId = null;
    String serverType = null;
    String defaultDateFormat = null;
    String recentDateFormat = null;

    int base = 0;
    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-E")) {
            encoding = args[++base];
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-m")) {
            mdtm = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
            System.out.println("protocal:" + protocol);
        } else if (args[base].equals("-S")) {
            serverType = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-U")) {
            saveUnparseable = true;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-y")) {
            defaultDateFormat = args[++base];
        } else if (args[base].equals("-Y")) {
            recentDateFormat = args[++base];
        } else if (args[base].equals("-Z")) {
            serverTimeZoneId = args[++base];
        } else if (args[base].equals("-z")) {
            displayTimeZoneId = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }
    if (remain < minParams) // server, user, pass, remote, local [protocol]
    {
        if (args.length > 0) {
            System.err.println("Actual Parameters: " + Arrays.toString(args));
        }
        System.err.println(USAGE);
        System.exit(1);
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
        System.out.println("server:" + server);
        System.out.println("port:" + port);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
        System.out.println("username:" + username);
        System.out.println("password:" + password);
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (encoding != null) {
        ftp.setControlEncoding(encoding);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    final FTPClientConfig config;
    if (serverType != null) {
        config = new FTPClientConfig(serverType);
    } else {
        config = new FTPClientConfig();
    }
    config.setUnparseableEntries(saveUnparseable);
    if (defaultDateFormat != null) {
        config.setDefaultDateFormatStr(defaultDateFormat);
    }
    if (recentDateFormat != null) {
        config.setRecentDateFormatStr(recentDateFormat);
    }
    ftp.configure(config);

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        }
        // Allow multiple list types for single invocation
        else if (listFiles || mlsd || mdtm || mlst || listNames) {
            if (mlsd) {
                for (FTPFile f : ftp.mlistDir(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
            if (mdtm) {
                FTPFile f = ftp.mdtmFile(remote);
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString(displayTimeZoneId));
            }
            if (mlst) {
                FTPFile f = ftp.mlistFile(remote);
                if (f != null) {
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
            if (listNames) {
                for (String s : ftp.listNames(remote)) {
                    System.out.println(s);
                }
            }
            // Do this last because it changes the client
            if (listFiles) {
                if (lenient || serverTimeZoneId != null) {
                    config.setLenientFutureDates(lenient);
                    if (serverTimeZoneId != null) {
                        config.setServerTimeZoneId(serverTimeZoneId);
                    }
                    ftp.configure(config);
                }

                for (FTPFile f : ftp.listFiles(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString(displayTimeZoneId));
                }
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    System.exit(error ? 1 : 0);
}

From source file:com.ls.zencat.ZenCat.java

public static void main(String[] args) throws Exception {
    try {//  w w w. j  ava2 s .  c o m
        if (args.length == 0) {
            System.out.println("first param should be config file");
            System.exit(-1);
        }
        XMLConfiguration c = null;
        try {
            c = new XMLConfiguration(args[0]);
        } catch (ConfigurationException cex) {
            System.err.println("Configuration error, check config file");
            cex.printStackTrace();
            System.exit(1);
        }

        ZenCat bot = new ZenCat(c);

        // listen for stuff and send it to irc:
        ServerSocket serverSocket = null;
        InetAddress inet = null;
        try {
            if (bot.getCatIP() != null)
                inet = InetAddress.getByName(bot.getCatIP());
        } catch (UnknownHostException ex) {
            System.out.println("Could not resolve config cat.ip, fix your config");
            ex.printStackTrace();
            System.exit(2);
        }

        try {
            serverSocket = new ServerSocket(bot.getCatPort(), 0, inet);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + bot.getCatPort());
            System.exit(1);
        }

        System.out.println("Listening on " + bot.getCatIP() + " : " + bot.getCatPort());

        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                // System.out.println("Connection on catport from: "
                // + clientSocket.getInetAddress().toString());
                CatHandler handler = new CatHandler(clientSocket, bot);
                handler.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:de.codesourcery.jasm16.utils.ASTInspector.java

public static void main(final String[] args) throws IOException {

    SwingUtilities.invokeLater(new Runnable() {

        @Override/*from   www  . j  a  v  a 2 s .  c  o m*/
        public void run() {
            try {
                new ASTInspector().run(args);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:com.google.api.ads.adwords.awreporting.AwReporting.java

/**
 * Main method.//from   ww w  .ja v a2  s  .c  o  m
 *
 * @param args the command line arguments.
 */
public static void main(String args[]) {

    // Proxy
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Options options = createCommandLineOptions();

    boolean errors = false;
    String propertiesPath = null;

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(options, args);

        // Print full help and quit
        if (cmdLine.hasOption("help")) {
            printHelpMessage(options);
            printSamplePropertiesFile();
            System.exit(0);
        }

        setLogLevel(cmdLine);

        if (cmdLine.hasOption("file")) {
            propertiesPath = cmdLine.getOptionValue("file");
        } else {
            LOGGER.error("Missing required option: 'file'");
            System.exit(0);
        }
        LOGGER.info("Using properties file: " + propertiesPath);

        Set<Long> accountIdsSet = Sets.newHashSet();
        if (cmdLine.hasOption("accountIdsFile")) {
            String accountsFileName = cmdLine.getOptionValue("accountIdsFile");
            addAccountsFromFile(accountIdsSet, accountsFileName);
        }

        boolean forceOnFileProcessor = false;
        if (cmdLine.hasOption("onFileReport")) {
            if (!cmdLine.hasOption("csvReportFile") || !cmdLine.hasOption("startDate")
                    || !cmdLine.hasOption("endDate")) {
                LOGGER.error("Missing one or more of the required options: "
                        + "'csvReportFile', 'startDate' or 'endDate'");
                System.exit(0);
            }
            forceOnFileProcessor = true;
        }
        Properties properties = initApplicationContextAndProperties(propertiesPath, forceOnFileProcessor);

        LOGGER.debug("Creating ReportProcessor bean...");
        ReportProcessor processor = createReportProcessor();
        LOGGER.debug("... success.");

        String mccAccountId = properties.getProperty("mccAccountId").replaceAll("-", "");

        if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) {
            // Generate Reports
            String dateStart = cmdLine.getOptionValue("startDate");
            String dateEnd = cmdLine.getOptionValue("endDate");

            if (cmdLine.hasOption("onFileReport")) {

                String reportTypeName = cmdLine.getOptionValue("onFileReport");
                String csvReportFile = cmdLine.getOptionValue("csvReportFile");

                File csvFile = new File(csvReportFile);
                if (!csvFile.exists()) {
                    LOGGER.error("Could not find CSV file: " + csvReportFile);
                    System.exit(0);
                }

                ReportProcessorOnFile onFileProcessor = (ReportProcessorOnFile) processor;
                List<File> localFiles = new ArrayList<File>();
                localFiles.add(csvFile);

                LOGGER.info(
                        "Starting report processing for dateStart: " + dateStart + " and dateEnd: " + dateEnd);
                onFileProcessor.processInputFiles(mccAccountId, reportTypeName, localFiles, dateStart, dateEnd,
                        ReportDefinitionDateRangeType.CUSTOM_DATE);

            } else {
                LOGGER.info(
                        "Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd);

                processor.generateReportsForMCC(mccAccountId, ReportDefinitionDateRangeType.CUSTOM_DATE,
                        dateStart, dateEnd, accountIdsSet, properties, null, null);
            }
        } else if (cmdLine.hasOption("dateRange")) {

            ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType
                    .fromValue(cmdLine.getOptionValue("dateRange"));

            LOGGER.info("Starting report download for dateRange: " + dateRangeType.name());

            processor.generateReportsForMCC(mccAccountId, dateRangeType, null, null, accountIdsSet, properties,
                    null, null);

        } else {
            errors = true;
            LOGGER.error("Configuration incomplete. Missing options for command line.");
        }

    } catch (IOException e) {
        errors = true;

        if (e.getMessage().contains("Insufficient Permission")) {
            LOGGER.error("Insufficient Permission error accessing the API" + e.getMessage());
        } else {
            LOGGER.error("File not found: " + e.getMessage());
        }

    } catch (ParseException e) {
        errors = true;
        System.err.println("Error parsing the values for the command line options: " + e.getMessage());
    } catch (Exception e) {
        errors = true;
        LOGGER.error("Unexpected error accessing the API: " + e.getMessage());
        e.printStackTrace();
    }

    if (errors) {
        System.exit(1);
    } else {
        System.exit(0);
    }
}

From source file:lemontree.modulenetwork.RunCli.java

/**
 * Parse command line options and run LeMoNe 
 * /*  ww w.j a  va 2s  .c o m*/
 * @param args command-line arguments string
 *            
 */
public static void main(String[] args) {

    // set dummy values for those parameters, they'll be filled later
    String task = null;
    String gene_file = null;
    String data_file = null;
    String reg_file = null;
    String tree_file = null;
    String output_file = null;
    String range = null;
    int num_steps = 0;
    int burn_in = 0;
    int sample_steps = 0;
    String cluster_file = null;
    String go_annot_file = null;
    String go_ref_file = null;
    String top_regulators = null;
    String map_file = null;
    String go_ontology_file = null;
    String draw_experiment_color = null;

    // set default values for those parameters, users can override them
    double alpha = 0.1;
    double beta = 0.1;
    double mu = 0.0;
    double lambda = 0.1;
    double score_gain = 0.0;
    int init_num_clust = 0;
    int num_runs = 1;
    boolean use_bayesian_score = true;
    int num_reg = 10;
    double beta_reg = 20;
    String go_p_value = "0.05";
    String go_namespace = "biological_process";
    boolean use_global_mean = false;
    boolean use_regulator_mean = false;
    int cut_level = 0;
    double min_weight = 0.25;
    int min_clust_size = 10;
    int min_clust_score = 2;
    Boolean node_clustering = true;
    boolean draw_experiment_names = true;

    // create the different options
    Options opts = new Options();
    opts.addOption("task", true, "task to perform");
    opts.addOption("gene_file", true, "gene file");
    opts.addOption("data_file", true, "data file (genes)");
    opts.addOption("reg_file", true, "regulators file");
    opts.addOption("tree_file", true, "tree file");
    opts.addOption("output_file", true, "output file name");
    opts.addOption("num_steps", true, "number of steps (Gibbs sampler)");
    opts.addOption("burn_in", true, "number of burn-in steps (Gibbs sampler)");
    opts.addOption("sample_steps", true, "sample steps interval (Gibbs sampler)");
    opts.addOption("cluster_file", true, "cluster file name");
    opts.addOption("num_clust", true, "number of clusters");
    opts.addOption("alpha", true, "alpha0 parameter value");
    opts.addOption("beta", true, "beta0 parameter value");
    opts.addOption("mu", true, "mu0 parameter value");
    opts.addOption("lambda", true, "lambda0 parameter value");
    opts.addOption("score_gain", true, "score gain cutoff value");
    opts.addOption("init_num_clust", true, "initial number of clusters (Gibbs sampler)");
    opts.addOption("num_runs", true, "number of runs (Gibbs sampler)");
    opts.addOption("num_reg", true, "maximum number of regulators assigned for each node");
    opts.addOption("beta_reg", true, "beta parameter value for regulators assignment");
    opts.addOption("num_split", true, "number of splits for the module set");
    opts.addOption("prefix", true, "java command prefix for the split option command line");
    opts.addOption("range", true, "module set range for the assignment of the regulators");
    opts.addOption("go_annot_file", true, "GO custom annotation file");
    opts.addOption("go_ontology_file", true, "GO ontology file name");
    opts.addOption("go_ref_file", true, "GO refence gene list file name");
    opts.addOption("go_p_value", true, "GO p-value cutoff");
    opts.addOption("go_namespace", true, "GO namespace");
    opts.addOption("go_annot_def", false, "GO annotation file flag");
    opts.addOption("matlab", false, "Matlab format for output files");
    opts.addOption("help", false, "help");
    opts.addOption("h", false, "help");
    opts.addOption("top_regulators", true, "Top regulators file name");
    opts.addOption("use_global_mean", false, "Use global mean for the figures");
    opts.addOption("use_regulator_mean", false, "Use regulator mean for the figures");
    opts.addOption("all_regulators", false, "Print all regulators");
    opts.addOption("map_file", true, "Gene names map file");
    opts.addOption("cut_level", true, "Regulation tree cut level");
    opts.addOption("min_weight", true, "Tight clusters minimum weight");
    opts.addOption("min_clust_size", true, "Tight clusters minimum cluster size");
    opts.addOption("min_clust_score", true, "Tight clusters minimum cluster score");
    opts.addOption("node_clustering", true, "Perform node clustering (true) or edge clustering (false)");
    opts.addOption("draw_experiment_names", true, "Draw experiment names in the figures");
    opts.addOption("draw_experiment_color", true, "Draw experiment color codes in the figures");

    // build a parser object and parse the command line (!)
    CommandLineParser parser = new PosixParser();
    try {

        CommandLine cmd = parser.parse(opts, args);
        if (cmd.hasOption("min_weight"))
            min_weight = Double.parseDouble(cmd.getOptionValue("min_weight"));

        if (cmd.hasOption("min_clust_size"))
            min_clust_size = Integer.parseInt(cmd.getOptionValue("min_clust_size"));

        if (cmd.hasOption("min_clust_score"))
            min_clust_score = Integer.parseInt(cmd.getOptionValue("min_clust_score"));

        if (cmd.hasOption("task"))
            task = cmd.getOptionValue("task");

        if (cmd.hasOption("data_file"))
            data_file = cmd.getOptionValue("data_file");

        if (cmd.hasOption("tree_file"))
            tree_file = cmd.getOptionValue("tree_file");

        if (cmd.hasOption("gene_file"))
            gene_file = cmd.getOptionValue("gene_file");

        if (cmd.hasOption("reg_file"))
            reg_file = cmd.getOptionValue("reg_file");

        if (cmd.hasOption("output_file"))
            output_file = cmd.getOptionValue("output_file");

        if (cmd.hasOption("cluster_file"))
            cluster_file = cmd.getOptionValue("cluster_file");

        if (cmd.hasOption("alpha"))
            alpha = Double.parseDouble(cmd.getOptionValue("alpha"));

        if (cmd.hasOption("beta"))
            beta = Double.parseDouble(cmd.getOptionValue("beta"));

        if (cmd.hasOption("lambda"))
            lambda = Double.parseDouble(cmd.getOptionValue("lambda"));

        if (cmd.hasOption("mu"))
            mu = Double.parseDouble(cmd.getOptionValue("mu"));

        if (cmd.hasOption("score_gain"))
            score_gain = Double.parseDouble(cmd.getOptionValue("score_gain"));

        if (cmd.hasOption("num_steps"))
            num_steps = Integer.parseInt(cmd.getOptionValue("num_steps"));

        if (cmd.hasOption("burn_in"))
            burn_in = Integer.parseInt(cmd.getOptionValue("burn_in"));

        if (cmd.hasOption("sample_steps"))
            sample_steps = Integer.parseInt(cmd.getOptionValue("sample_steps"));

        if (cmd.hasOption("init_num_clust"))
            init_num_clust = Integer.parseInt(cmd.getOptionValue("init_num_clust"));

        if (cmd.hasOption("num_reg"))
            num_reg = Integer.parseInt(cmd.getOptionValue("num_reg"));

        if (cmd.hasOption("beta_reg"))
            beta_reg = Double.parseDouble(cmd.getOptionValue("beta_reg"));

        if (cmd.hasOption("range"))
            range = cmd.getOptionValue("range");

        if (cmd.hasOption("go_annot_file"))
            go_annot_file = cmd.getOptionValue("go_annot_file");

        if (cmd.hasOption("go_ontology_file"))
            go_ontology_file = cmd.getOptionValue("go_ontology_file");

        if (cmd.hasOption("go_ref_file"))
            go_ref_file = cmd.getOptionValue("go_ref_file");

        if (cmd.hasOption("go_p_value"))
            go_p_value = cmd.getOptionValue("go_p_value");

        if (cmd.hasOption("go_namespace"))
            go_namespace = cmd.getOptionValue("go_namespace");

        if (cmd.hasOption("top_regulators"))
            top_regulators = cmd.getOptionValue("top_regulators");

        if (cmd.hasOption("use_global_mean"))
            use_global_mean = true;

        if (cmd.hasOption("use_regulator_mean"))
            use_regulator_mean = true;

        if (cmd.hasOption("map_file"))
            map_file = cmd.getOptionValue("map_file");

        if (cmd.hasOption("cut_level"))
            cut_level = Integer.parseInt(cmd.getOptionValue("cut_level"));

        if (cmd.hasOption("node_clustering"))
            if (cmd.getOptionValue("node_clustering").equalsIgnoreCase("false"))
                node_clustering = false;

        if (cmd.hasOption("draw_experiment_names"))
            if (cmd.getOptionValue("draw_experiment_names").equalsIgnoreCase("false"))
                draw_experiment_names = false;

        if (cmd.hasOption("draw_experiment_color"))
            draw_experiment_color = cmd.getOptionValue("draw_experiment_color");

    } catch (ParseException exp) {
        System.out.println("Error while parsing command line:");
        System.out.println();
        exp.printStackTrace();
        System.exit(1);
    }

    // print header
    printBanner();

    // something has to be done, we need a task to be set
    if (task == null)
        Die("Error: task option must be set.");

    // ---------------------------------------------------------------
    // ganesh task: 2-way clustering of genes using the gibbs sampler
    // ---------------------------------------------------------------
    if (task.equalsIgnoreCase("ganesh")) {

        // those parameters must be set
        if (data_file == null)
            Die("Error: data_file option must be set.");
        if (output_file == null)
            Die("Error: output_file option must be set.");

        // set default values if the user did not change them
        if (num_runs == 0)
            num_runs = 1;
        if (num_steps == 0)
            num_steps = 100;
        if (burn_in == 0)
            burn_in = 50;
        if (sample_steps == 0)
            sample_steps = 100;

        System.out.println("Parameters");
        System.out.println("----------");
        System.out.println("task:               " + task);
        System.out.println("data_file:          " + data_file);
        System.out.println("gene_file:          " + gene_file);
        System.out.println("output_file:        " + output_file);
        System.out.println("lambda:             " + lambda);
        System.out.println("mu:                 " + mu);
        System.out.println("alpha:              " + alpha);
        System.out.println("beta:               " + beta);
        System.out.println("num_steps:          " + num_steps);
        System.out.println("burn_in:            " + burn_in);
        System.out.println("sample_steps:       " + sample_steps);
        System.out.println("score_gain:         " + score_gain);

        // Create ModuleNetwork object
        ModuleNetwork M = new ModuleNetwork();
        M.setNormalGammaPriors(lambda, mu, alpha, beta);
        M.readExpressionMatrix(data_file, gene_file);
        M.setNormalGammaPriors(lambda, mu, alpha, beta);
        // Gibbs sample different module sets with one tree per module
        M.gibbsSamplerGenes(init_num_clust, num_runs, num_steps, burn_in, sample_steps, score_gain,
                use_bayesian_score);
        // write results to text file
        M.writeClusters(output_file);
    }
    //-------------------------------------------------------------------------------------
    // tight_clusters task: node clustering to produce tight clusters
    //-------------------------------------------------------------------------------------
    else if (task.equalsIgnoreCase("tight_clusters")) {

        if (data_file == null)
            Die("Error: data_file option must be set.");
        if (cluster_file == null)
            Die("Error: cluster_file option must be set.");
        if (output_file == null)
            Die("Error: output_file option must be set.");

        System.out.println("Parameters");
        System.out.println("----------");
        System.out.println("task:               " + task);
        System.out.println("data_file:          " + data_file);
        System.out.println("cluster_file:       " + cluster_file);
        System.out.println("output_file:        " + output_file);
        System.out.println("node_clustering:    " + node_clustering);
        System.out.println("min_weight:         " + min_weight);
        System.out.println("min_clust_size:     " + min_clust_size);
        System.out.println("min_clust_score:    " + min_clust_score);
        System.out.println();

        ModuleNetwork M = new ModuleNetwork();
        M.readExpressionMatrix(data_file, null);
        M.readMultipleClusters(cluster_file);

        // find tight clusters with node clustering algorithm
        CentroidClustering cc = new CentroidClustering(M, node_clustering, min_weight, min_clust_size,
                min_clust_score);
        cc.doCentroidClustering();
        cc.printClusters(output_file);

    }
    //-------------------------------------------------------------------------------------
    // regulators task: learn regulation programs (gibbs sampling exp. + assign regulators)
    //-------------------------------------------------------------------------------------
    else if (task.equalsIgnoreCase("regulators")) {

        // those parameters must be set
        if (data_file == null)
            Die("Error: data_file option must be set.");
        if (reg_file == null)
            Die("Error: reg_file option must be set.");
        if (cluster_file == null)
            Die("Error: cluster_file option must be set.");
        if (output_file == null)
            Die("Error: output_file option must be set.");

        // set default values if the user did not change them
        if (num_steps == 0)
            num_steps = 1100;
        if (burn_in == 0)
            burn_in = 100;
        if (sample_steps == 0)
            sample_steps = 100;

        System.out.println("Parameters");
        System.out.println("----------");
        System.out.println("task:               " + task);
        System.out.println("data_file:          " + data_file);
        System.out.println("reg_file:           " + reg_file);
        System.out.println("cluster_file:       " + cluster_file);
        System.out.println("output_file:        " + output_file);
        System.out.println("lambda:             " + lambda);
        System.out.println("mu:                 " + mu);
        System.out.println("alpha:              " + alpha);
        System.out.println("beta:               " + beta);
        System.out.println("num_runs:           " + num_runs);
        System.out.println("num_steps:          " + num_steps);
        System.out.println("burn_in:            " + burn_in);
        System.out.println("sample_steps:       " + sample_steps);
        System.out.println("score_gain:         " + score_gain);
        System.out.println("num_reg:            " + num_reg);

        // create module network object
        ModuleNetwork M = new ModuleNetwork();
        M.setNormalGammaPriors(lambda, mu, alpha, beta);
        M.readExpressionMatrix(data_file, null);
        M.readClusters(cluster_file);
        M.readRegulators(reg_file);
        M.initStatisticsAndScore();
        M.setDataMeanAndSDFromModuleset();

        // cluster experiments using the gibbs sampler
        M.gibbsSamplerExpts(num_runs, num_steps, burn_in, sample_steps, score_gain, use_bayesian_score);
        // assign regulators
        M.assignRegulatorsNoAcyclStoch(beta_reg, num_reg);
        // write results as text file with all regulators, top 1%, random regulators and regulations trees as xml
        M.printRegulators(output_file + ".allreg.txt", true, false);
        M.printRegulators(output_file + ".topreg.txt", false, false);
        M.printRandomRegulators(output_file + ".randomreg.txt", false);
        M.writeRegTreeXML(output_file + ".xml.gz");
    }
    //----------------------------------------------------------
    // experiments task: cluster conditions using gibbs sampling 
    //----------------------------------------------------------
    else if (task.equalsIgnoreCase("experiments")) {

        // those parameters must be set
        if (data_file == null)
            Die("Error: data_file option must be set.");
        if (cluster_file == null)
            Die("Error: cluster_file option must be set.");
        if (output_file == null)
            Die("Error: output_file option must be set.");

        // set default values if the user did not change them
        if (num_steps == 0)
            num_steps = 1100;
        if (burn_in == 0)
            burn_in = 100;
        if (sample_steps == 0)
            sample_steps = 100;

        System.out.println("Parameters");
        System.out.println("----------");
        System.out.println("task:               " + task);
        System.out.println("data_file:          " + data_file);
        System.out.println("cluster_file:       " + cluster_file);
        System.out.println("output_file:        " + output_file);
        System.out.println("lambda:             " + lambda);
        System.out.println("mu:                 " + mu);
        System.out.println("alpha:              " + alpha);
        System.out.println("beta:               " + beta);
        System.out.println("num_steps:          " + num_steps);
        System.out.println("burn_in:            " + burn_in);
        System.out.println("sample_steps:       " + sample_steps);
        System.out.println("score_gain:         " + score_gain);

        // read data and clusters
        ModuleNetwork M = new ModuleNetwork();
        M.setNormalGammaPriors(lambda, mu, alpha, beta);
        M.readExpressionMatrix(data_file, null);
        M.readClusters(cluster_file);
        M.initStatisticsAndScore();

        // cluster experiments using the gibbs sampler
        M.gibbsSamplerExpts(num_runs, num_steps, burn_in, sample_steps, score_gain, use_bayesian_score);

        // write results as xml file
        M.writeRegTreeXML(output_file);
    }
    //---------------------------------------------------------------
    // split_reg task: assign regulators for a given range of modules
    //---------------------------------------------------------------
    else if (task.equalsIgnoreCase("split_reg")) {

        // those parameters must be set
        if (data_file == null)
            Die("Error: data_file option must be set.");
        if (reg_file == null)
            Die("Error: reg_file option must be set.");
        if (cluster_file == null)
            Die("Error: cluster_file option must be set.");
        if (tree_file == null)
            Die("Error: tree_file option must be set.");
        if (output_file == null)
            Die("Error: output_file option must be set.");
        if (range == null)
            Die("Error: range option must be set.");

        System.out.println("Parameters");
        System.out.println("----------");
        System.out.println("task:               " + task);
        System.out.println("data_file:          " + data_file);
        System.out.println("reg_file:           " + reg_file);
        System.out.println("cluster_file:       " + cluster_file);
        System.out.println("output_file:        " + output_file);
        System.out.println("num_reg:            " + num_reg);
        System.out.println("beta_reg:           " + beta_reg);
        System.out.println("range:              " + range);

        ModuleNetwork M = new ModuleNetwork();
        M.setNormalGammaPriors(lambda, mu, alpha, beta);
        M.readExpressionMatrix(data_file, null);
        M.readClusters(cluster_file);
        M.readRegulators(reg_file);
        M.initStatisticsAndScore();
        M.readRegTreeXML(tree_file);

        String[] val = range.split(":");
        int start_module = Integer.parseInt(val[0]);
        int stop_module = Integer.parseInt(val[1]);

        // assign regulators
        M.assignRegulatorsNoAcyclStoch(beta_reg, num_reg, start_module, stop_module);

        // write results
        M.printRegulators(output_file + ".allreg.txt", true, false);
        M.printRandomRegulators(output_file + ".randomreg.txt", false);
        M.writeRegTreeXML(output_file + ".xml.gz");
    }
    //----------------------------------------------------------------------------
    // go_annotation task: GO annotation of a cluster file
    //----------------------------------------------------------------------------
    else if (task.equalsIgnoreCase("go_annotation")) {

        // those parameters must be set
        if (cluster_file == null)
            Die("Error: cluster_file parameter must be set.");
        if (output_file == null)
            Die("Error: output_file option must be set.");
        if (go_annot_file == null)
            Die("Error: go_annot_file option must be set.");
        if (go_ontology_file == null)
            Die("Error: go_ontology_file option must be set.");
        if (go_ref_file == null)
            Die("Error: go_ref_file option must be set.");

        System.out.println("Parameters");
        System.out.println("----------");
        System.out.println("task:               " + task);
        System.out.println("cluster_file:       " + cluster_file);
        System.out.println("output_file:        " + output_file);
        System.out.println("go_annot_file:      " + go_annot_file);
        System.out.println("go_ontology_file:   " + go_ontology_file);
        System.out.println("go_ref_file:        " + go_ref_file);
        System.out.println("go_p_value:         " + go_p_value);
        System.out.println("go_namespace:       " + go_namespace);
        System.out.println("map_file            " + map_file);

        BiNGO b = new BiNGO(go_annot_file, go_ontology_file, go_p_value, go_namespace);

        try {
            b.GOstats(cluster_file, go_ref_file, output_file, map_file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //----------------------------------------------------------------------------
    // figures task: create eps figures for each module
    //----------------------------------------------------------------------------
    else if (task.equalsIgnoreCase("figures")) {

        // those parameters must be set
        if (top_regulators == null)
            Die("Error: top_regulators option must be set.");
        if (data_file == null)
            Die("Error: data_file option must be set.");
        if (reg_file == null)
            Die("Error: reg_file option must be set.");
        if (cluster_file == null)
            Die("Error: cluster_file option must be set.");
        if (tree_file == null)
            Die("Error: tree_file option must be set.");

        System.out.println("Parameters");
        System.out.println("----------");
        System.out.println("task:                  " + task);
        System.out.println("data_file:             " + data_file);
        System.out.println("reg_file:              " + reg_file);
        System.out.println("cluster_file:          " + cluster_file);
        System.out.println("tree_file:             " + tree_file);
        System.out.println("top_regulators:        " + top_regulators);
        System.out.println("use_regulator_mean:    " + use_regulator_mean);
        System.out.println("use_global_mean:       " + use_global_mean);
        System.out.println("map_file:              " + map_file);
        System.out.println("cut_level:             " + cut_level);
        System.out.println("draw_experiment_names: " + draw_experiment_names);
        System.out.println("draw_experiment_color: " + draw_experiment_color);

        ModuleNetwork M = new ModuleNetwork();
        //read expression data, genes, clusters and regulators from files
        M.setNormalGammaPriors(lambda, mu, alpha, beta);
        M.readExpressionMatrix(data_file, null);
        M.readClusters(cluster_file);
        M.readRegulators(reg_file);
        M.initStatisticsAndScore();
        M.setDataMeanAndSDFromModuleset();

        // read regulation trees from xml file
        M.readRegTreeXML(tree_file);
        M.setTestSplits();
        // set top regulators for each module
        M.setTopRegulatorClasses(top_regulators);
        // calculate mean and sigma for all modules
        M.setModuleMeanSigma();
        M.checkExperiments();
        // use module mean (default) or global mean for figures
        M.setGlobalMeanForFigures(use_global_mean);
        // use individual regulators mean for figures (default false)
        M.setRegulatorlMeanForFigures(use_regulator_mean);
        if (use_regulator_mean == true)
            M.setRegulatorMeanSigma();
        // change gene names if a map file is given
        if (map_file != null)
            M.changeGeneNames(map_file);
        // cut trees to a certain level
        if (cut_level > 0) {
            for (Module mod : M.moduleSet) {
                for (TreeNode t : mod.hierarchicalTrees) {
                    t.testLevel(cut_level);
                }
            }
        }

        DrawModules dm = new DrawModules(M);

        if (draw_experiment_color != null) {
            M.setExperimentColor(draw_experiment_color);
            dm.enableExperimentColor();
        }

        if (draw_experiment_names == false) {
            dm.unsetDrawExperimentNames();
        }

        dm.drawAllModules();
    }
    //----------------------------------------------------------------------------
    // topdown task: run "old" heuristic algo
    //----------------------------------------------------------------------------
    else if (task.equalsIgnoreCase("topdown")) {
        int maxParents = 3;
        double epsConvergence = 1E-3;
        // Create ModuleNetwork object
        ModuleNetwork M = new ModuleNetwork();
        M.setNormalGammaPriors(lambda, mu, alpha, beta);
        M.readExpressionMatrix(data_file, gene_file);
        M.setNormalGammaPriors(lambda, mu, alpha, beta);
        M.readRegulators(reg_file);
        // Top-down search
        M.heuristicSearchMaxTopDown(maxParents, epsConvergence);
        // write results as xml file
        M.writeRegTreeXML(output_file);
    } else {
        System.out.println("task option '" + task + "' unknown.");
        System.out.println();
    }
}