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:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * testing/*from w ww. jav  a  2 s.  co m*/
 *
 * @param args urls to test
 */
public static void main(final String[] args) {
    String url = null;
    // prepare Parts
    //        final Map<String,ContentBody> newparts = new LinkedHashMap<String,ContentBody>();
    //        try {
    //            newparts.put("foo", new StringBody("FooBar"));
    //            newparts.put("bar", new StringBody("BarFoo"));
    //        } catch (final UnsupportedEncodingException e) {
    //            System.out.println(e.getStackTrace());
    //        }
    final HTTPClient client = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent);
    client.setRedirecting(false);
    // Get some
    for (final String arg : args) {
        url = arg;
        if (!url.toUpperCase().startsWith("HTTP://")) {
            url = "http://" + url;
        }
        try {
            System.out.println(UTF8.String(client.GETbytes(url, null, null, true)));
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
    // Head some
    //      try {
    //         client.HEADResponse(url);
    //      } catch (final IOException e) {
    //         e.printStackTrace();
    //      }
    for (final Header header : client.getHttpResponse().getAllHeaders()) {
        System.out.println("Header " + header.getName() + " : " + header.getValue());
        //         for (HeaderElement element: header.getElements())
        //            System.out.println("Element " + element.getName() + " : " + element.getValue());
    }
    //        System.out.println(client.getHttpResponse().getLocale());
    System.out.println(client.getHttpResponse().getProtocolVersion());
    System.out.println(client.getHttpResponse().getStatusLine());
    // Post some
    //      try {
    //         System.out.println(UTF8.String(client.POSTbytes(url, newparts)));
    //      } catch (final IOException e1) {
    //         e1.printStackTrace();
    //      }
    // Close out connection manager
    try {
        HTTPClient.closeConnectionManager();
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:IndexService.IndexServer.java

public static void main(String[] args) {
    File stop = new File("/tmp/.indexstop");
    File running = new File("/tmp/.indexrunning");
    if (args != null && args.length > 0 && args[0].equals("stop")) {
        try {/*from w  ww  . j  a  v a  2  s  .  com*/
            stop.createNewFile();
            running.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    if (running.exists() && (System.currentTimeMillis() - running.lastModified() < 15000)) {
        long time = running.lastModified();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (running.lastModified() == time) {
            running.delete();
        } else {
            return;
        }
    }

    if (stop.exists()) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (stop.exists())
            stop.delete();
    }

    Configuration conf = new Configuration();
    IndexServer server = new IndexServer(conf);
    if (args != null && args.length > 0 && args[0].equals("test")) {
        server.testmode = true;
    }
    server.start();
    try {
        running.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    new UserCmdProc(server).start();

    while (true) {
        stop = new File("/tmp/.indexstop");
        if (stop.exists()) {
            server.close();
            running.delete();
            stop.delete();
            break;
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        running.setLastModified(System.currentTimeMillis());

    }
}

From source file:jk.kamoru.test.IMAPMail.java

public static void main(String[] args) {
    /*        if (args.length < 3)
            {//from  ww  w.j  a  va2 s .com
    System.err.println(
        "Usage: IMAPMail <imap server hostname> <username> <password> [TLS]");
    System.exit(1);
            }
    */
    String server = "imap.handysoft.co.kr";
    String username = "namjk24@handysoft.co.kr";
    String password = "22222";

    String proto = (args.length > 3) ? args[3] : null;

    IMAPClient imap;

    if (proto != null) {
        System.out.println("Using secure protocol: " + proto);
        imap = new IMAPSClient(proto, true); // implicit
        // enable the next line to only check if the server certificate has expired (does not check chain):
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        // OR enable the next line if the server uses a self-signed certificate (no checks)
        //            ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
    } else {
        imap = new IMAPClient();
    }
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

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

    File imap_log_file = new File("IMAMP-UNSEEN");
    try {
        System.out.println(imap_log_file.getAbsolutePath());
        PrintStream ps = new PrintStream(imap_log_file);
        // suppress login details
        imap.addProtocolCommandListener(new PrintCommandListener(ps, true));
    } catch (FileNotFoundException e1) {
        imap.addProtocolCommandListener(new PrintCommandListener(System.out, true));
    }

    try {
        imap.connect(server);
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    try {
        if (!imap.login(username, password)) {
            System.err.println("Could not login to server. Check password.");
            imap.disconnect();
            System.exit(3);
        }

        imap.setSoTimeout(6000);

        //            imap.capability();

        //            imap.select("inbox");

        //            imap.examine("inbox");

        imap.status("inbox", new String[] { "UNSEEN" });

        //            imap.logout();
        imap.disconnect();

        List<String> imap_log = FileUtils.readLines(imap_log_file);
        for (int i = 0; i < imap_log.size(); i++) {
            System.out.println(i + ":" + imap_log.get(i));
        }
        String unseenText = imap_log.get(4);
        unseenText = unseenText.substring(unseenText.indexOf('(') + 1, unseenText.indexOf(')'));
        int unseenCount = Integer.parseInt(unseenText.split(" ")[1]);

        System.out.println(unseenCount);
        //imap_log.indexOf("UNSEEN ")
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    }
}

From source file:de.ipbhalle.metfrag.main.CommandLineTool.java

/**
 * @param args//w  ww  . ja v a 2s  . c om
 * @throws Exception 
 */
public static void main(String[] args) {

    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();

    options.addOption("d", "database", true, "database: " + Databases.getString() + " (default: kegg)");
    options.addOption("l", "localdb", true,
            "use a local database together with a settings file for candidate search (default: not used) note: only usable if pubchem database is selected (-d)");
    options.addOption("a", "mzabs", true,
            "allowed absolute (Da) mass deviation of fragment and peak masses (default: 0.01)");
    options.addOption("p", "mzppm", true,
            "allowed relative (ppm) mass deviation of fragment and peak masses (default: 10)");
    options.addOption("s", "searchppm", true,
            "relative (ppm) mass deviation used for candidate search in given compound database (-d) (default: 10; not used by default if sdf database is selected (-d))\n");
    options.addOption("n", "exactmass", true,
            "neutral mass of measured compound used for candidate search in database (-d) (mandatory)");
    options.addOption("b", "biological", false,
            "only consider compounds including CHNOPS atoms (not used by default)");
    options.addOption("i", "databaseids", true,
            "database ids of compounds used for in silico fragmentation (separated by ,) (not used by default; not used if sdf database is selected (-d)) note: given ids must be valid ids of given database (-d)");
    options.addOption("t", "treedepth", true,
            "treedepth used for in silico fragmentation (default: 2) note: high values result in high computation time");
    options.addOption("M", "mode", true,
            "mode used for measured ms/ms spectrum:\n" + Modes.getString() + "(default: 3)");
    options.addOption("f", "formula", true,
            "molecular formula of measured compound used for candidate search in database (-d) (not used by default; not used if sdf database is selected (-d))");
    options.addOption("B", "breakrings", false,
            "allow splitting of aromatic rings of candidate structures during in silico fragmentation (not used by default)");
    options.addOption("F", "storefragments", false,
            "store in silico generated fragments of candidate molecules (not used by default)");
    options.addOption("R", "resultspath", true, "directory where result files are stored (default: /tmp)");
    options.addOption("L", "sdffile", true,
            "location of the local sdf file (mandatory if sdf database (-d) is selected)");
    options.addOption("h", "help", false, "print help");
    options.addOption("D", "spectrumfile", true,
            "file containing peak data (mandatory) note: commandline options overwrite parameters given in the spectrum data file");
    options.addOption("T", "threads", true,
            "number of threads used for fragment calculation (default: number of available cpu cores)");
    options.addOption("c", "chemspidertoken", true,
            "Token for ChemSpider database search (not used by default; only necessary (mandatory) if ChemSpider database (-d) is selected)");
    options.addOption("v", "verbose", false,
            "get more output information during the processing (not used by default)");
    options.addOption("S", "samplename", true,
            "name of the sample measured (mandatory) note: result files are stored with given value");
    options.addOption("P", "saveparameters", false, "save used parameters (not used by default)");
    options.addOption("e", "printexamplespecfile", false,
            "print an example spectrum data file (not used by default)");
    options.addOption("C", "charge", true,
            "charge used in combination with mode (-M):\n" + Charges.getString() + " (default: 1)");
    options.addOption("r", "range", true,
            "range of candidates that will be processed: N (first N), M-N (from M to N), M- (from M), -N (till N); if N is greater than the number of candidates it will be set accordingly");

    // parse the command line arguments
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e1) {
        System.out.println(e1.getMessage());
        System.out.println("Error: Could not parse option parameters.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }

    if (line == null) {
        System.out.println("Error: Could not parse option parameters.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }
    if (checkInitialParamsPresent(line, options))
        System.exit(0);

    if (!checkSpectrumFile(line)) {
        System.out.println("Error: Option parameters are not set correctly.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }
    if (!parseSpectrumFile(spectrumfile)) {
        System.out.println("Error: Could not correctly parse the spectrum data file.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }

    int successfulSet = setParameters(line, options);
    if (successfulSet == 2)
        System.exit(0);
    if (successfulSet != 0) {
        System.out.println("Error: Option parameters are not set correctly.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }

    boolean successfulChecked = true;
    if (successfulSet == 0)
        successfulChecked = checkParameters();
    if (saveParametersIsSet) {
        try {
            BufferedWriter bwriter = new BufferedWriter(new FileWriter(new File(
                    resultspath + System.getProperty("file.separator") + "parameters_" + sampleName + ".txt")));
            bwriter.write(getParameters());
            bwriter.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        boolean isPositive = true;
        if (charge.getValue() == 2)
            isPositive = false;
        spec = new WrapperSpectrum(peaksString, mode.getValueWithOffset(), exactMass.getValue(), isPositive);
    } catch (Exception e) {
        System.out.println("Error: Could not parse spectrum correctly. Check the given peak list.");
        System.exit(1);
    }

    if (!successfulChecked) {
        System.out.println("Error: Option parameters are not set correctly.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }

    List<MetFragResult> results = null;
    String pathToStoreFrags = "";
    if (storeFragments)
        pathToStoreFrags = resultspath;
    //run metfrag when all checks were successful

    if (usesdf) {
        try {
            if (verbose) {
                System.out.println("start fragmenter with local database");
                System.out.println("using database " + database);
            }
            results = MetFrag.startConvenienceSDF(spec, mzabs.getValue(), mzppm.getValue(),
                    searchppm.getValue(), true, breakRings, treeDepth.getValue(), true, true, true, false,
                    Integer.MAX_VALUE, true, sdfFile, "", null, searchppmIsSet, pathToStoreFrags,
                    numberThreads.getValue(), verbose, sampleName, onlyBiologicalCompounds);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
            System.out.println("Error: Could not perform in silico fragmentation step.");
            System.exit(1);
        }
    } else {
        try {
            if (verbose) {
                if (!localdbIsSet)
                    System.out.println("start fragmenter with web database");
                else
                    System.out.println("start fragmenter with local database");
                System.out.println("using database " + database);
            }
            results = MetFrag.startConvenience(database, databaseIDs, formula, exactMass.getValue(), spec,
                    useProxy, mzabs.getValue(), mzppm.getValue(), searchppm.getValue(), true, breakRings,
                    treeDepth.getValue(), true, false, true, false, startindex.getValue(), endindex.getValue(),
                    true, pathToStoreFrags, numberThreads.getValue(), chemSpiderToken, verbose, sampleName,
                    localdb, onlyBiologicalCompounds, dblink, dbuser, dbpass, uniquebyinchi);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error: " + e.getMessage());
            System.out.println("Error: Could not perform in silico fragmentation step.");
            System.exit(1);
        }
    }

    saveResults(results);

}

From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxParser.java

public static void main(String[] args) {

    // Ensure we have a path to the binary file
    if (args.length != 1) {
        logger.info("Please provide the path to a file containing a binary LOOP packet.");
        System.exit(1);/*from  w w w  .j  a  va 2 s .  com*/
    } else {
        try {
            // open and read the file
            File packetFile = new File(args[0]);
            FileInputStream fis = new FileInputStream(packetFile);
            FileChannel fileChannel = fis.getChannel();
            ByteBuffer inBuffer = ByteBuffer.allocateDirect(8192);
            ByteBuffer packetBuffer = ByteBuffer.allocateDirect(8192);

            while (fileChannel.read(inBuffer) != -1 || inBuffer.position() > 0) {
                inBuffer.flip();
                packetBuffer.put(inBuffer.get());
                inBuffer.compact();
            }
            fileChannel.close();
            fis.close();
            packetBuffer.put(inBuffer.get());

            // create an instance of the parser, and report the field contents after parsing
            DavisWxParser davisWxParser = new DavisWxParser(packetBuffer);

            // Set up a simple logger that logs to the console
            PropertyConfigurator.configure(davisWxParser.getLogConfigurationFile());

            logger.info("loopID:                         " + davisWxParser.getLoopID());
            logger.info("barTrend:                       " + davisWxParser.getBarTrend());
            logger.info("barTrendAsString:               " + davisWxParser.getBarTrendAsString());
            logger.info("packetType:                     " + davisWxParser.getPacketType());
            logger.info("nextRecord:                     " + davisWxParser.getNextRecord());
            logger.info("barometer:                      " + davisWxParser.getBarometer());
            logger.info("insideTemperature:              " + davisWxParser.getInsideTemperature());
            logger.info("insideHumidity:                 " + davisWxParser.getInsideHumidity());
            logger.info("outsideTemperature:             " + davisWxParser.getOutsideTemperature());
            logger.info("windSpeed:                      " + davisWxParser.getWindSpeed());
            logger.info("tenMinuteAverageWindSpeed:      " + davisWxParser.getTenMinuteAverageWindSpeed());
            logger.info("windDirection:                  " + davisWxParser.getWindDirection());
            logger.info(
                    "extraTemperatures:              " + Arrays.toString(davisWxParser.getExtraTemperatures()));
            logger.info(
                    "soilTemperatures:               " + Arrays.toString(davisWxParser.getSoilTemperatures()));
            logger.info(
                    "leafTemperatures:               " + Arrays.toString(davisWxParser.getLeafTemperatures()));
            logger.info("outsideHumidity:                " + davisWxParser.getOutsideHumidity());
            logger.info(
                    "extraHumidities:                " + Arrays.toString(davisWxParser.getExtraHumidities()));
            logger.info("rainRate:                       " + davisWxParser.getRainRate());
            logger.info("uvRadiation:                    " + davisWxParser.getUvRadiation());
            logger.info("solarRadiation:                 " + davisWxParser.getSolarRadiation());
            logger.info("stormRain:                      " + davisWxParser.getStormRain());
            logger.info("currentStormStartDate:          " + davisWxParser.getCurrentStormStartDate());
            logger.info("dailyRain:                      " + davisWxParser.getDailyRain());
            logger.info("monthlyRain:                    " + davisWxParser.getMonthlyRain());
            logger.info("yearlyRain:                     " + davisWxParser.getYearlyRain());
            logger.info("dailyEvapoTranspiration:        " + davisWxParser.getDailyEvapoTranspiration());
            logger.info("monthlyEvapoTranspiration:      " + davisWxParser.getMonthlyEvapoTranspiration());
            logger.info("yearlyEvapoTranspiration:       " + davisWxParser.getYearlyEvapoTranspiration());
            logger.info("soilMoistures:                  " + Arrays.toString(davisWxParser.getSoilMoistures()));
            logger.info("leafWetnesses:                  " + Arrays.toString(davisWxParser.getLeafWetnesses()));
            logger.info("insideAlarm:                    " + davisWxParser.getInsideAlarm());
            logger.info("rainAlarm:                      " + davisWxParser.getRainAlarm());
            logger.info("outsideAlarms:                  " + davisWxParser.getOutsideAlarms());
            logger.info("extraTemperatureHumidityAlarms: " + davisWxParser.getExtraTemperatureHumidityAlarms());
            logger.info("soilLeafAlarms:                 " + davisWxParser.getSoilLeafAlarms());
            logger.info("transmitterBatteryStatus:       " + davisWxParser.getTransmitterBatteryStatus());
            logger.info("consoleBatteryVoltage:          " + davisWxParser.getConsoleBatteryVoltage());
            logger.info("forecastIconValues:             " + davisWxParser.getForecastAsString());
            logger.info("forecastRuleNumber:             " + davisWxParser.getForecastRuleNumberAsString());
            logger.info("timeOfSunrise:                  " + davisWxParser.getTimeOfSunrise());
            logger.info("timeOfSunset:                   " + davisWxParser.getTimeOfSunset());
            logger.info("recordDelimiter:                " + davisWxParser.getRecordDelimiterAsHexString());
            logger.info("crcChecksum:                    " + davisWxParser.getCrcChecksum());

        } catch (java.io.FileNotFoundException fnfe) {
            fnfe.printStackTrace();

        } catch (java.io.IOException ioe) {
            ioe.printStackTrace();

        }

    }
}

From source file:edu.illinois.cs.cogcomp.datalessclassification.ta.W2VDatalessAnnotator.java

/**
 * @param args config: config file path testFile: Test File
 *//*from  w w w  .j  a  v a2  s. co  m*/
public static void main(String[] args) {
    CommandLine cmd = ESADatalessAnnotator.getCMDOpts(args);

    ResourceManager rm;

    try {
        String configFile = cmd.getOptionValue("config", "config/project.properties");
        ResourceManager nonDefaultRm = new ResourceManager(configFile);

        rm = new W2VDatalessConfigurator().getConfig(nonDefaultRm);
    } catch (IOException e) {
        rm = new W2VDatalessConfigurator().getDefaultConfig();
    }

    String testFile = cmd.getOptionValue("testFile", "data/graphicsTestDocument.txt");

    StringBuilder sb = new StringBuilder();

    String line;

    try (BufferedReader br = new BufferedReader(new FileReader(new File(testFile)))) {
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(" ");
        }

        String text = sb.toString().trim();

        TokenizerTextAnnotationBuilder taBuilder = new TokenizerTextAnnotationBuilder(new StatefulTokenizer());
        TextAnnotation ta = taBuilder.createTextAnnotation(text);

        W2VDatalessAnnotator datalessAnnotator = new W2VDatalessAnnotator(rm);
        datalessAnnotator.addView(ta);

        List<Constituent> annots = ta.getView(ViewNames.DATALESS_W2V).getConstituents();

        System.out.println("Predicted LabelIDs:");

        for (Constituent annot : annots) {
            System.out.println(annot.getLabel());
        }

        Map<String, String> labelNameMap = DatalessAnnotatorUtils
                .getLabelNameMap(rm.getString(DatalessConfigurator.LabelName_Path.key));

        System.out.println("Predicted Labels:");

        for (Constituent annot : annots) {
            System.out.println(labelNameMap.get(annot.getLabel()));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        logger.error("Test File not found at " + testFile + " ... exiting");
        System.exit(-1);
    } catch (AnnotatorException e) {
        e.printStackTrace();
        logger.error("Error Annotating the Test Document with the Dataless View ... exiting");
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("IO Error while reading the test file ... exiting");
        System.exit(-1);
    }
}

From source file:edu.illinois.cs.cogcomp.datalessclassification.ta.ESADatalessAnnotator.java

/**
 * @param args config: config file path testFile: Test File
 *///from  www.  ja  v a 2 s.c  o m
public static void main(String[] args) {
    CommandLine cmd = getCMDOpts(args);

    ResourceManager rm;

    try {
        String configFile = cmd.getOptionValue("config", "config/project.properties");
        ResourceManager nonDefaultRm = new ResourceManager(configFile);

        rm = new ESADatalessConfigurator().getConfig(nonDefaultRm);
    } catch (IOException e) {
        rm = new ESADatalessConfigurator().getDefaultConfig();
    }

    String testFile = cmd.getOptionValue("testFile", "data/graphicsTestDocument.txt");

    StringBuilder sb = new StringBuilder();

    String line;

    try (BufferedReader br = new BufferedReader(new FileReader(new File(testFile)))) {
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(" ");
        }

        String text = sb.toString().trim();

        TokenizerTextAnnotationBuilder taBuilder = new TokenizerTextAnnotationBuilder(new StatefulTokenizer());
        TextAnnotation ta = taBuilder.createTextAnnotation(text);

        ESADatalessAnnotator datalessAnnotator = new ESADatalessAnnotator(rm);
        datalessAnnotator.addView(ta);

        List<Constituent> annots = ta.getView(ViewNames.DATALESS_ESA).getConstituents();

        System.out.println("Predicted LabelIDs:");
        for (Constituent annot : annots) {
            System.out.println(annot.getLabel());
        }

        Map<String, String> labelNameMap = DatalessAnnotatorUtils
                .getLabelNameMap(rm.getString(DatalessConfigurator.LabelName_Path.key));

        System.out.println("Predicted Labels:");

        for (Constituent annot : annots) {
            System.out.println(labelNameMap.get(annot.getLabel()));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        logger.error("Test File not found at " + testFile + " ... exiting");
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("IO Error while reading the test file ... exiting");
        System.exit(-1);
    } catch (AnnotatorException e) {
        e.printStackTrace();
        logger.error("Error Annotating the Test Document with the Dataless View ... exiting");
        System.exit(-1);
    }
}

From source file:net.recommenders.plista.client.Client.java

/**
 * This method starts the server//  w ww  .  j  a v a2s .  c  o  m
 *
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    final Properties properties = new Properties();
    String fileName = "";
    String recommenderClass = null;
    String handlerClass = null;

    if (args.length < 3) {
        fileName = System.getProperty("propertyFile");
    } else {
        fileName = args[0];
        recommenderClass = args[1];
        handlerClass = args[2];
    }
    // load the team properties
    try {
        properties.load(new FileInputStream(fileName));
    } catch (IOException e) {
        logger.error(e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    Recommender recommender = null;
    recommenderClass = (recommenderClass != null ? recommenderClass
            : properties.getProperty("plista.recommender"));
    System.out.println(recommenderClass);
    lognum = Integer.parseInt(properties.getProperty("plista.lognum"));
    try {
        final Class<?> transformClass = Class.forName(recommenderClass);
        recommender = (Recommender) transformClass.newInstance();
    } catch (Exception e) {
        logger.error(e.getMessage());
        throw new IllegalArgumentException("No recommender specified or recommender not available.");
    }
    // configure log4j
    /*if (args.length >= 4 && args[3] != null) {
    PropertyConfigurator.configure(args[0]);
         } else {
    PropertyConfigurator.configure("log4j.properties");
         }*/
    // set up and start server

    AbstractHandler handler = null;
    handlerClass = (handlerClass != null ? handlerClass : properties.getProperty("plista.handler"));
    System.out.println(handlerClass);
    try {
        final Class<?> transformClass = Class.forName(handlerClass);
        handler = (AbstractHandler) transformClass.getConstructor(Properties.class, Recommender.class)
                .newInstance(properties, recommender);
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        throw new IllegalArgumentException("No handler specified or handler not available.");
    }
    final Server server = new Server(Integer.parseInt(properties.getProperty("plista.port", "8080")));

    server.setHandler(handler);
    logger.debug("Serverport " + server.getConnectors()[0].getPort());

    server.start();
    server.join();
}

From source file:luisjosediez.Ejercicio2.java

/**
 * @param args the command line arguments
 *//*from   w ww  .  j  a v  a  2 s . com*/
public static void main(String[] args) {
    // TODO code application logic here
    System.out.println("Introduce la direccin de un servidor ftp: ");
    FTPClient cliente = new FTPClient();
    String servFTP = cadena();
    String clave = "";
    System.out.println("Introduce usuario (vaco para conexin annima): ");
    String usuario = cadena();
    String opcion;
    if (usuario.equals("")) {
        clave = "";
    } else {
        System.out.println("Introduce contrasea: ");
        clave = cadena();
    }
    try {
        cliente.setPassiveNatWorkaround(false);
        cliente.connect(servFTP, 21);
        boolean login = cliente.login(usuario, clave);
        if (login) {
            System.out.println("Conexin ok");
        } else {
            System.out.println("Login incorrecto");
            cliente.disconnect();
            System.exit(1);
        }
        do {

            System.out.println("Orden [exit para salir]: ");
            opcion = cadena();
            if (opcion.equals("ls")) {
                FTPFile[] files = cliente.listFiles();
                String tipos[] = { "Fichero", "Directorio", "Enlace" };
                for (int i = 0; i < files.length; i++) {
                    System.out.println("\t" + files[i].getName() + "\t=> " + tipos[files[i].getType()]);
                }
            } else if (opcion.startsWith("cd ")) {
                try {
                    cliente.changeWorkingDirectory(opcion.substring(3));
                } catch (IOException e) {
                }
            } else if (opcion.equals("help")) {
                System.out.println(
                        "Puede ejecutar los comandos 'exit', 'ls', 'cd', 'get' y 'upload'. Para ms detalles utilice 'help <comando>'.");
            } else if (opcion.startsWith("help ")) {
                if (opcion.endsWith(" get")) {
                    System.out.println(
                            "Permite descargar un archivo concreto. Uso: 'get <rutaArchivoADescargar>'.");
                } else if (opcion.endsWith(" ls")) {
                    System.out.println("Lista los ficheros y directorios en la ubicacin actual. Uso: 'ls'.");
                } else if (opcion.endsWith(" cd")) {
                    System.out.println("Permite cambiar la ubicacin actual. Uso: 'cd <rutaDestino>'.");
                } else if (opcion.endsWith(" put")) {
                    System.out.println(
                            "Permite subir un archivo al directorio actual. Uso: 'put <rutaArchivoASubir>'.");
                }
            } else if (opcion.startsWith("get ")) {
                try {
                    System.out.println("Indique la carpeta de descarga: ");
                    try (FileOutputStream fos = new FileOutputStream(cadena() + opcion.substring(4))) {
                        cliente.retrieveFile(opcion.substring(4), fos);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                }
            } else if (opcion.startsWith("put ")) {
                try {
                    try {

                        System.out.println(opcion.substring(4));

                        File local = new File(opcion.substring(4));

                        System.out.println(local.getName());

                        InputStream is = new FileInputStream(opcion.substring(4));

                        OutputStream os = cliente.storeFileStream(local.getName());

                        byte[] bytesIn = new byte[4096];

                        int read = 0;

                        while ((read = is.read(bytesIn)) != -1) {

                            os.write(bytesIn, 0, read);

                        }

                        is.close();
                        os.close();

                        boolean completed = cliente.completePendingCommand();

                        if (completed) {
                            System.out.println("The file is uploaded successfully.");
                        }

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

        } while (!(opcion.equals("exit")));

        boolean logout = cliente.logout();
        if (logout)
            System.out.println("Logout...");
        else
            System.out.println("Logout incorrecto");

        cliente.disconnect();

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

From source file:ZipCompare.java

public static void main(String[] args) {
    if (args.length != 2) {
        System.out.println("Usage: zipcompare [file1] [file2]");
        System.exit(1);// w  ww . j  a  va  2s .c  om
    }

    ZipFile file1;
    try {
        file1 = new ZipFile(args[0]);
    } catch (IOException e) {
        System.out.println("Could not open zip file " + args[0] + ": " + e);
        System.exit(1);
        return;
    }

    ZipFile file2;
    try {
        file2 = new ZipFile(args[1]);
    } catch (IOException e) {
        System.out.println("Could not open zip file " + args[0] + ": " + e);
        System.exit(1);
        return;
    }

    System.out.println("Comparing " + args[0] + " with " + args[1] + ":");

    Set set1 = new LinkedHashSet();
    for (Enumeration e = file1.entries(); e.hasMoreElements();)
        set1.add(((ZipEntry) e.nextElement()).getName());

    Set set2 = new LinkedHashSet();
    for (Enumeration e = file2.entries(); e.hasMoreElements();)
        set2.add(((ZipEntry) e.nextElement()).getName());

    int errcount = 0;
    int filecount = 0;
    for (Iterator i = set1.iterator(); i.hasNext();) {
        String name = (String) i.next();
        if (!set2.contains(name)) {
            System.out.println(name + " not found in " + args[1]);
            errcount += 1;
            continue;
        }
        try {
            set2.remove(name);
            if (!streamsEqual(file1.getInputStream(file1.getEntry(name)),
                    file2.getInputStream(file2.getEntry(name)))) {
                System.out.println(name + " does not match");
                errcount += 1;
                continue;
            }
        } catch (Exception e) {
            System.out.println(name + ": IO Error " + e);
            e.printStackTrace();
            errcount += 1;
            continue;
        }
        filecount += 1;
    }
    for (Iterator i = set2.iterator(); i.hasNext();) {
        String name = (String) i.next();
        System.out.println(name + " not found in " + args[0]);
        errcount += 1;
    }
    System.out.println(filecount + " entries matched");
    if (errcount > 0) {
        System.out.println(errcount + " entries did not match");
        System.exit(1);
    }
    System.exit(0);
}