Example usage for java.io IOException getMessage

List of usage examples for java.io IOException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:au.edu.unsw.cse.soc.federatedcloud.user.CloudBaseUserInterface.java

public static void main(String[] args) {
    CloudBaseUserInterface interfaze = new CloudBaseUserInterface();

    String command;/*from  ww w .jav a2  s .com*/
    try {
        command = args[0];
        if ("init".equals(command)) {
            String appName = args[1];
            try {
                String appAttributes = args[2];
                interfaze.initCloudBase(appName, appAttributes);
            } catch (ArrayIndexOutOfBoundsException aie) {
                log.warn("No attributes specified.");
                interfaze.initCloudBase(appName);
            }

        } else if ("deploy".equals(command)) {
            String resourceName = args[1];
            String resourceMetaData = args[2];
            interfaze.deployResource(resourceName, resourceMetaData);
        } else if ("undeploy".equals(command)) {
            String resourceName = args[1];
            interfaze.undeployResource(resourceName);
        } else {
            System.err.println("Command: " + command + " is not specified.");
        }
    } catch (ArrayIndexOutOfBoundsException ex) {
        System.err.println("please specify a command.");
        log.error(ex.getMessage(), ex);
    } catch (IOException e) {
        System.err.println(e.getMessage());
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

}

From source file:main.java.com.google.api.services.samples.youtube.cmdline.YouTubeSample.java

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

    Properties properties = new Properties();
    try {/*from   w w  w.j a v  a 2s.com*/
        InputStream in = YouTubeSample.class.getResourceAsStream("" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest arg0) throws IOException {
            // TODO Auto-generated method stub

        }
    }).setApplicationName("youtubeTest").build();

    YouTube.Videos.List videos = youtube.videos().list("snippet");

    String apiKey = properties.getProperty("youtube.apikey");
    videos.setKey(apiKey);
    videos.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
    videos.setChart("mostPopular");

    VideoListResponse response = videos.execute();

    java.util.List<Video> videoList = response.getItems();

    if (videoList != null) {
        prettyPrint(videoList.iterator());
    } else {
        System.out.println("There were  no results!");
    }

}

From source file:iaj.linkit.App.java

/**
 * Application entry method.//from   w  ww  .  ja v  a  2s  . co m
 *
 * @param args Command line arguments.
 */
public static void main(final String[] args) {
    final Configuration config = new Configuration();
    final CmdLineParser parser = new CmdLineParser(config);

    try {
        parser.parseArgument(args);

        final File f = (config.getPaths().size() > 0) ? new File(config.getPaths().get(0)).getCanonicalFile()
                : new File(DIR_CURRENT).getCanonicalFile();
        if (!f.exists()) {
            System.err.println("No such path: " + f.getCanonicalFile());
            System.exit(1);
        } else if (!f.canRead()) {
            System.err.println("Can't read path.");
            System.exit(1);
        } else if (f.isDirectory()) {
            handleFiles(config.isRecursive(), f.listFiles());
        } else {
            handleFiles(config.isRecursive(), f);
        }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    } catch (final CmdLineException e) {
        System.err.println(e.getMessage());
        System.err.println("lu [options...] [paths...]"); //$NON-NLS-1$
        parser.printUsage(System.err);
        System.exit(1);
    }
}

From source file:de.tudarmstadt.ukp.argumentation.data.roomfordebate.DataFetcher.java

public static void main(String[] args) throws Exception {
    File crawledPagesFolder = new File(args[0]);
    if (!crawledPagesFolder.exists()) {
        crawledPagesFolder.mkdirs();//from w  w w  .  j ava  2 s  . co  m
    }

    File outputFolder = new File(args[1]);
    if (!outputFolder.exists()) {
        outputFolder.mkdirs();
    }

    // read links from text file
    final String urlsResourceName = "roomfordebate-urls.txt";

    InputStream urlsStream = DataFetcher.class.getClassLoader().getResourceAsStream(urlsResourceName);

    if (urlsStream == null) {
        throw new IOException("Cannot find resource " + urlsResourceName + " on the classpath");
    }

    // read list of urls
    List<String> urls = new ArrayList<>();
    LineIterator iterator = IOUtils.lineIterator(urlsStream, "utf-8");
    while (iterator.hasNext()) {
        // ignore commented url (line starts with #)
        String line = iterator.nextLine();
        if (!line.startsWith("#") && !line.trim().isEmpty()) {
            urls.add(line.trim());
        }
    }

    // download all
    crawlPages(urls, crawledPagesFolder);

    List<File> files = new ArrayList<>(FileUtils.listFiles(crawledPagesFolder, null, false));
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    int idCounter = 0;

    for (File file : files) {
        NYTimesCommentsScraper commentsScraper = new NYTimesCommentsScraper();
        NYTimesArticleExtractor extractor = new NYTimesArticleExtractor();

        String html = FileUtils.readFileToString(file, "utf-8");

        idCounter++;
        File outputFileArticle = new File(outputFolder, String.format("Cx%03d.txt", idCounter));
        File outputFileComments = new File(outputFolder, String.format("Dx%03d.txt", idCounter));

        try {
            List<Comment> comments = commentsScraper.extractComments(html);
            Article article = extractor.extractArticle(html);

            saveArticleToText(article, outputFileArticle);
            System.out.println("Saved to " + outputFileArticle);

            saveCommentsToText(comments, outputFileComments, article);
            System.out.println("Saved to " + outputFileComments);
        } catch (IOException ex) {
            System.err.println(file.getName() + "\n" + ex.getMessage());
        }
    }
}

From source file:com.ok2c.lightmtp.examples.LocalMailClientTransportExample.java

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

    String text1 = "From: root\r\n" + "To: testuser1\r\n" + "Subject: test message 1\r\n" + "\r\n"
            + "This is a short test message 1\r\n";
    String text2 = "From: root\r\n" + "To: testuser1, testuser2\r\n" + "Subject: test message 2\r\n" + "\r\n"
            + "This is a short test message 2\r\n";
    String text3 = "From: root\r\n" + "To: testuser1, testuser2, testuser3\r\n" + "Subject: test message 3\r\n"
            + "\r\n" + "This is a short test message 3\r\n";

    DeliveryRequest request1 = new BasicDeliveryRequest("root", Arrays.asList("testuser1"),
            new ByteArraySource(text1.getBytes("US-ASCII")));

    DeliveryRequest request2 = new BasicDeliveryRequest("root", Arrays.asList("testuser1", "testuser2"),
            new ByteArraySource(text2.getBytes("US-ASCII")));

    DeliveryRequest request3 = new BasicDeliveryRequest("root",
            Arrays.asList("testuser1", "testuser2", "testuser3"),
            new ByteArraySource(text3.getBytes("US-ASCII")));

    Queue<DeliveryRequest> queue = new ConcurrentLinkedQueue<DeliveryRequest>();
    queue.add(request1);/*w ww  . j  a v  a  2 s  .  c o  m*/
    queue.add(request2);
    queue.add(request3);

    CountDownLatch messageCount = new CountDownLatch(queue.size());

    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).build();

    MailClientTransport mua = new LocalMailClientTransport(config);
    mua.start(new MyDeliveryRequestHandler(messageCount));

    SessionEndpoint endpoint = new SessionEndpoint(new InetSocketAddress("localhost", 2525));

    SessionRequest sessionRequest = mua.connect(endpoint, queue, null);
    sessionRequest.waitFor();

    IOSession iosession = sessionRequest.getSession();
    if (iosession != null) {
        messageCount.await();
    } else {
        IOException ex = sessionRequest.getException();
        if (ex != null) {
            System.out.println("Connection failed: " + ex.getMessage());
        }
    }

    System.out.println("Shutting down I/O reactor");
    try {
        mua.shutdown();
    } catch (IOException ex) {
        mua.forceShutdown();
    }
    System.out.println("Done");
}

From source file:com.liferay.nativity.test.TestDriver.java

public static void main(String[] args) {
    _intitializeLogging();/* w  ww .j ava2s  . c  o  m*/

    List<String> items = new ArrayList<String>();

    items.add("ONE");

    NativityMessage message = new NativityMessage("BLAH", items);

    try {
        _logger.debug(_objectMapper.writeValueAsString(message));
    } catch (JsonProcessingException jpe) {
        _logger.error(jpe.getMessage(), jpe);
    }

    _logger.debug("main");

    NativityControl nativityControl = NativityControlUtil.getNativityControl();

    FileIconControl fileIconControl = FileIconControlUtil.getFileIconControl(nativityControl,
            new TestFileIconControlCallback());

    ContextMenuControlUtil.getContextMenuControl(nativityControl, new TestContextMenuControlCallback());

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

    nativityControl.connect();

    String read = "";
    boolean stop = false;

    try {
        while (!stop) {
            _list = !_list;

            _logger.debug("Loop start...");

            _logger.debug("_enableFileIcons");
            _enableFileIcons(fileIconControl);

            _logger.debug("_registerFileIcon");
            _registerFileIcon(fileIconControl);

            _logger.debug("_setFilterPath");
            _setFilterPath(nativityControl);

            _logger.debug("_setSystemFolder");
            _setSystemFolder(nativityControl);

            _logger.debug("_updateFileIcon");
            _updateFileIcon(fileIconControl);

            _logger.debug("_clearFileIcon");
            _clearFileIcon(fileIconControl);

            _logger.debug("Ready?");

            if (bufferedReader.ready()) {
                _logger.debug("Reading...");

                read = bufferedReader.readLine();

                _logger.debug("Read {}", read);

                if (read.length() > 0) {
                    stop = true;
                }

                _logger.debug("Stopping {}", stop);
            }
        }
    } catch (IOException e) {
        _logger.error(e.getMessage(), e);
    }

    _logger.debug("Done");
}

From source file:com.google.api.services.samples.prediction.cmdline.PredictionSample.java

public static void main(String[] args) {
    try {//from  w w w  .  j av  a  2  s. c om
        // initialize the transport
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        // initialize the data store factory
        dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

        // authorization
        Credential credential = authorize();

        // set up global Prediction instance
        client = new Prediction.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();

        //      System.out.println("Success! Now add code here.");
        train(client);

        String sample = "This version of the simple language";
        predict(client, sample);

    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    System.exit(1);
}

From source file:proxy.NHttpServer.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);//w  w w . jav  a2  s. c o m
    }
    // Document root directory
    File docRoot = new File(args[0]);
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();
    // Create request handler registry
    UriHttpAsyncRequestHandlerMapper reqistry = new UriHttpAsyncRequestHandlerMapper();
    // Register the default handler for all URIs
    reqistry.register("*", new HttpFileHandler(docRoot));
    // Create server-side HTTP protocol handler
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, reqistry) {

        @Override
        public void connected(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection open");
            super.connected(conn);
        }

        @Override
        public void closed(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection closed");
            super.closed(conn);
        }

    };
    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = NHttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    }
    // Create server-side I/O event dispatch
    IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Set I/O reactor defaults
    IOReactorConfig config = IOReactorConfig.custom().setIoThreadCount(1).setSoTimeout(3000)
            .setConnectTimeout(3000).build();
    // Create server-side I/O reactor
    ListeningIOReactor ioReactor = new DefaultListeningIOReactor(config);
    try {
        // Listen of the given port
        ioReactor.listen(new InetSocketAddress(port));
        // Ready to go!
        ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
        System.err.println("Interrupted");
    } catch (IOException e) {
        System.err.println("I/O error: " + e.getMessage());
    }
    System.out.println("Shutdown");
}

From source file:yucatan.communication.server.NHttpServer.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specify document root directory");
        System.exit(1);//from   www.  j ava 2 s  .com
    }
    // Document root directory
    File docRoot = new File(args[0]);
    int port = 8080;
    if (args.length >= 2) {
        port = Integer.parseInt(args[1]);
    }
    // HTTP parameters for the server
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1");
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
            // Use standard server-side protocol interceptors
            new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() });
    // Create request handler registry
    HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry();
    // Register the default handler for all URIs
    reqistry.register("*", new HttpFileHandler(docRoot));
    // Create server-side HTTP protocol handler
    HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, new DefaultConnectionReuseStrategy(),
            reqistry, params) {

        @Override
        public void connected(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection open");
            super.connected(conn);
        }

        @Override
        public void closed(final NHttpServerConnection conn) {
            System.out.println(conn + ": connection closed");
            super.closed(conn);
        }

    };
    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = NHttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params);
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(params);
    }
    // Create server-side I/O event dispatch
    IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
    // Create server-side I/O reactor
    ListeningIOReactor ioReactor = new DefaultListeningIOReactor();
    try {
        // Listen of the given port
        ioReactor.listen(new InetSocketAddress(port));
        // Ready to go!
        ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
        System.err.println("Interrupted");
    } catch (IOException e) {
        System.err.println("I/O error: " + e.getMessage());
    }
    System.out.println("Shutdown");
}

From source file:com.amazonaws.services.kinesis.multilang.MultiLangDaemon.java

/**
 * @param args Accepts a single argument, that argument is a properties file which provides KCL configuration as
 *        well as the name of an executable.
 *///w  w w .j  a  v a2s .c o  m
public static void main(String[] args) {

    if (args.length == 0) {
        printUsage(System.err, "You must provide a properties file");
        System.exit(1);
    }
    MultiLangDaemonConfig config = null;
    try {
        config = new MultiLangDaemonConfig(args[0]);
    } catch (IOException e) {
        printUsage(System.err, "You must provide a properties file");
        System.exit(1);
    } catch (IllegalArgumentException e) {
        printUsage(System.err, e.getMessage());
        System.exit(1);
    }

    ExecutorService executorService = config.getExecutorService();

    // Daemon
    MultiLangDaemon daemon = new MultiLangDaemon(config.getKinesisClientLibConfiguration(),
            config.getRecordProcessorFactory(), executorService);

    Future<Integer> future = executorService.submit(daemon);
    try {
        System.exit(future.get());
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("Encountered an error while running daemon", e);
    }
    System.exit(1);
}