Example usage for java.io IOException getCause

List of usage examples for java.io IOException getCause

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.myjeeva.poi.demo.Excel2JavaDemo.java

/**
 * @param args//from  w  ww.j  a  va  2  s.  c om
 * @throws FileNotFoundException
 */
public static void main(String[] args) throws FileNotFoundException {
    String SAMPLE_PERSON_DATA_FILE_PATH = "src/main/resources/Sample-Person-Data.xlsx";

    // Input File initialize
    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // Excel Cell Mapping
    Map<String, String> cellMapping = new HashMap<String, String>();
    cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary");
    cellMapping.put("A", "personId");
    cellMapping.put("B", "name");
    cellMapping.put("C", "height");
    cellMapping.put("D", "emailId");
    cellMapping.put("E", "dob");
    cellMapping.put("F", "salary");

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;
    try {

        ExcelWorkSheetHandler<PersonVO> workSheetHandler = new ExcelWorkSheetHandler<PersonVO>(PersonVO.class,
                cellMapping);

        pkg = OPCPackage.open(inputStream);
        ExcelReader excelReader = new ExcelReader(pkg, workSheetHandler);
        excelReader.process();

        if (workSheetHandler.getValueList().isEmpty()) {
            // No data present
            LOG.error("sHandler.getValueList() is empty");
        } else {

            LOG.info(workSheetHandler.getValueList().size()
                    + " no. of records read from given excel worksheet successfully.");

            // Displaying data ead from Excel file
            displayPersonList(workSheetHandler.getValueList());
        }

    } catch (RuntimeException are) {
        LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
        LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (null != pkg) {
                pkg.close();
            }
        } catch (IOException e) {
            // just ignore IO exception
        }
    }
}

From source file:uk.ac.abdn.liftsharing.batch.io.test.ExcelWorkSheetRowCallbackHandlerTest.java

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

    String SAMPLE_PERSON_DATA_FILE_PATH = "D:\\Sample-Person-Data.xlsx";

    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;//w  ww  .  j a  va2  s.  c  o  m
    try {
        ExcelWorkSheetRowCallbackHandler sheetRowCallbackHandler = new ExcelWorkSheetRowCallbackHandler(
                new ExcelRowContentCallback() {

                    @Override
                    public void processRow(int rowNum, Map<String, String> map) {

                        // Do any custom row processing here, such as save
                        // to database
                        // Convert map values, as necessary, to dates or
                        // parse as currency, etc
                        System.out.println("rowNum=" + rowNum + ", map=" + map);

                    }

                });

        pkg = OPCPackage.open(inputStream);

        ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
            private int sheetNumber = 0;

            @Override
            public void startSheet(int sheetNum) {
                this.sheetNumber = sheetNum;

            }

            @Override
            public void endSheet() {
                System.out.println("Processing completed for sheet number=" + sheetNumber);
            }
        };

        System.out.println("Constructor: pkg, sheetRowCallbackHandler, sheetCallback");
        ExcelReader example1 = new ExcelReader(pkg, sheetRowCallbackHandler, sheetCallback);
        example1.process();

        System.out.println("\nConstructor: filePath, sheetRowCallbackHandler, sheetCallback");
        ExcelReader example2 = new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, sheetRowCallbackHandler,
                sheetCallback);
        example2.process();

        System.out.println("\nConstructor: file, sheetRowCallbackHandler, sheetCallback");
        ExcelReader example3 = new ExcelReader(file, sheetRowCallbackHandler, null);
        example3.process();

    } catch (RuntimeException are) {
        LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
        LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (null != pkg) {
                pkg.close();
            }
        } catch (IOException e) {
            // just ignore IO exception
        }
    }
}

From source file:com.myjeeva.poi.ExcelWorkSheetRowCallbackHandlerTest.java

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

    String SAMPLE_PERSON_DATA_FILE_PATH = "src/test/resources/Sample-Person-Data.xlsx";

    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;//from   w  w w  .jav a 2s  . c o m
    try {
        ExcelWorkSheetRowCallbackHandler sheetRowCallbackHandler = new ExcelWorkSheetRowCallbackHandler(
                new ExcelRowContentCallback() {

                    @Override
                    public void processRow(int rowNum, Map<String, String> map) {

                        // Do any custom row processing here, such as save
                        // to database
                        // Convert map values, as necessary, to dates or
                        // parse as currency, etc
                        System.out.println("rowNum=" + rowNum + ", map=" + map);

                    }

                });

        pkg = OPCPackage.open(inputStream);

        ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
            private int sheetNumber = 0;

            @Override
            public void startSheet(int sheetNum, String sheetName) {
                this.sheetNumber = sheetNum;
                System.out.println("Started processing sheet number=" + sheetNumber + " and Sheet Name is '"
                        + sheetName + "'");
            }

            @Override
            public void endSheet() {
                System.out.println("Processing completed for sheet number=" + sheetNumber);
            }
        };

        System.out.println("Constructor: pkg, sheetRowCallbackHandler, sheetCallback");
        ExcelReader example1 = new ExcelReader(pkg, sheetRowCallbackHandler, sheetCallback);
        example1.process();

        System.out.println("\nConstructor: filePath, sheetRowCallbackHandler, sheetCallback");
        ExcelReader example2 = new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, sheetRowCallbackHandler,
                sheetCallback);
        example2.process();

        System.out.println("\nConstructor: file, sheetRowCallbackHandler, sheetCallback");
        ExcelReader example3 = new ExcelReader(file, sheetRowCallbackHandler, null);
        example3.process();

    } catch (RuntimeException are) {
        LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
        LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (null != pkg) {
                pkg.close();
            }
        } catch (IOException e) {
            // just ignore IO exception
        }
    }
}

From source file:uk.ac.abdn.liftsharing.batch.io.test.ExcelWorkSheetHandlerTest.java

/**
 * @param args/*from w  ww  . ja v a  2  s  .c o m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String SAMPLE_PERSON_DATA_FILE_PATH = "D:\\Sample-Person-Data.xlsx";

    // Input File initialize
    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // Excel Cell Mapping
    Map<String, String> cellMapping = new HashMap<String, String>();
    cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary");
    cellMapping.put("A", "personId");
    cellMapping.put("B", "name");
    cellMapping.put("C", "height");
    cellMapping.put("D", "emailId");
    cellMapping.put("E", "dob");
    cellMapping.put("F", "salary");

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;
    try {

        ExcelWorkSheetHandler<PersonVO> workSheetHandler = new ExcelWorkSheetHandler<PersonVO>(PersonVO.class,
                cellMapping);

        pkg = OPCPackage.open(inputStream);

        ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
            private int sheetNumber = 0;

            @Override
            public void endSheet() {
                System.out.println("Processing completed for sheet number=" + sheetNumber);
            }

            @Override
            public void startSheet(int sheetNum) {
                this.sheetNumber = sheetNum;

            }
        };

        System.out.println("Constructor: pkg, workSheetHandler, sheetCallback");
        ExcelReader example1 = new ExcelReader(pkg, workSheetHandler, sheetCallback);
        example1.process();

        if (workSheetHandler.getValueList().isEmpty()) {
            // No data present
            LOG.error("sHandler.getValueList() is empty");
        } else {

            LOG.info(workSheetHandler.getValueList().size()
                    + " no. of records read from given excel worksheet successfully.");

            // Displaying data ead from Excel file
            displayPersonList(workSheetHandler.getValueList());
        }

        System.out.println("\nConstructor: filePath, workSheetHandler, sheetCallback");
        ExcelReader example2 = new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, workSheetHandler, sheetCallback);
        example2.process();

        System.out.println("\nConstructor: file, workSheetHandler, sheetCallback");
        ExcelReader example3 = new ExcelReader(file, workSheetHandler, null);
        example3.process();

    } catch (RuntimeException are) {
        LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
        LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (null != pkg) {
                pkg.close();
            }
        } catch (IOException e) {
            // just ignore IO exception
        }
    }
}

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 {/* 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:com.myjeeva.poi.ExcelWorkSheetHandlerTest.java

/**
 * @param args//  ww  w  .j  av  a2  s .  co m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String SAMPLE_PERSON_DATA_FILE_PATH = "src/test/resources/Sample-Person-Data.xlsx";

    // Input File initialize
    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // Excel Cell Mapping
    Map<String, String> cellMapping = new HashMap<String, String>();
    cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary");
    cellMapping.put("A", "personId");
    cellMapping.put("B", "name");
    cellMapping.put("C", "height");
    cellMapping.put("D", "emailId");
    cellMapping.put("E", "dob");
    cellMapping.put("F", "salary");

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;
    try {

        ExcelWorkSheetHandler<PersonVO> workSheetHandler = new ExcelWorkSheetHandler<PersonVO>(PersonVO.class,
                cellMapping);

        pkg = OPCPackage.open(inputStream);

        ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
            private int sheetNumber = 0;

            @Override
            public void startSheet(int sheetNum, String sheetName) {
                this.sheetNumber = sheetNum;
                System.out.println("Started processing sheet number=" + sheetNumber + " and Sheet Name is '"
                        + sheetName + "'");
            }

            @Override
            public void endSheet() {
                System.out.println("Processing completed for sheet number=" + sheetNumber);
            }
        };

        System.out.println("Constructor: pkg, workSheetHandler, sheetCallback");
        ExcelReader example1 = new ExcelReader(pkg, workSheetHandler, sheetCallback);
        example1.process();

        if (workSheetHandler.getValueList().isEmpty()) {
            // No data present
            LOG.error("sHandler.getValueList() is empty");
        } else {

            LOG.info(workSheetHandler.getValueList().size()
                    + " no. of records read from given excel worksheet successfully.");

            // Displaying data ead from Excel file
            displayPersonList(workSheetHandler.getValueList());
        }

        System.out.println("\nConstructor: filePath, workSheetHandler, sheetCallback");
        ExcelReader example2 = new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, workSheetHandler, sheetCallback);
        example2.process();

        System.out.println("\nConstructor: file, workSheetHandler, sheetCallback");
        ExcelReader example3 = new ExcelReader(file, workSheetHandler, null);
        example3.process();

    } catch (RuntimeException are) {
        LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
        LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (null != pkg) {
                pkg.close();
            }
        } catch (IOException e) {
            // just ignore IO exception
        }
    }
}

From source file:com.mycompany.javaapplicaton3.ExcelWorkSheetHandlerTest.java

/**
 * @param args//www .j  a v  a 2  s.  c  om
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    String SAMPLE_PERSON_DATA_FILE_PATH = "C:/Users/lprates/Documents/Sample-Person-Data.xlsx";

    // Input File initialize
    File file = new File(SAMPLE_PERSON_DATA_FILE_PATH);
    InputStream inputStream = new FileInputStream(file);

    // Excel Cell Mapping
    Map<String, String> cellMapping = new HashMap<String, String>();
    cellMapping.put("HEADER", "Person Id,Name,Height,Email Address,DOB,Salary");
    cellMapping.put("A", "personId");
    cellMapping.put("B", "name");
    cellMapping.put("C", "height");
    cellMapping.put("D", "emailId");
    cellMapping.put("E", "dob");
    cellMapping.put("F", "salary");

    // The package open is instantaneous, as it should be.
    OPCPackage pkg = null;
    try {

        ExcelWorkSheetHandler<PersonVO> workSheetHandler = new ExcelWorkSheetHandler<PersonVO>(PersonVO.class,
                cellMapping);

        pkg = OPCPackage.open(inputStream);

        ExcelSheetCallback sheetCallback = new ExcelSheetCallback() {
            private int sheetNumber = 0;

            public void startSheet(int sheetNum, String sheetName) {
                this.sheetNumber = sheetNum;
                System.out.println("Started processing sheet number=" + sheetNumber + " and Sheet Name is '"
                        + sheetName + "'");
            }

            @Override
            public void endSheet() {
                System.out.println("Processing completed for sheet number=" + sheetNumber);
            }

            public void startSheet(int sheetNum) {
                System.out.println("Started processing sheet number=" + sheetNum);
            }

        };

        System.out.println("Constructor: pkg, workSheetHandler, sheetCallback");
        ExcelReader example1 = new ExcelReader(pkg, workSheetHandler, sheetCallback);
        example1.process("Lot 1 Data");

        if (workSheetHandler.getValueList().isEmpty()) {
            // No data present
            LOG.error("sHandler.getValueList() is empty");
        } else {

            LOG.info(workSheetHandler.getValueList().size()
                    + " no. of records read from given excel worksheet successfully.");

            // Displaying data ead from Excel file
            displayPersonList(workSheetHandler.getValueList());
        }
        /*
              System.out.println("\nConstructor: filePath, workSheetHandler, sheetCallback");
              ExcelReader example2 =
                  new ExcelReader(SAMPLE_PERSON_DATA_FILE_PATH, workSheetHandler, sheetCallback);
              example2.process();
                
              System.out.println("\nConstructor: file, workSheetHandler, sheetCallback");
              ExcelReader example3 = new ExcelReader(file, workSheetHandler, null);
              example3.process();
        */
    } catch (RuntimeException are) {
        LOG.error(are.getMessage(), are.getCause());
    } catch (InvalidFormatException ife) {
        LOG.error(ife.getMessage(), ife.getCause());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe.getCause());
    } finally {
        IOUtils.closeQuietly(inputStream);
        try {
            if (null != pkg) {
                pkg.close();
            }
        } catch (IOException e) {
            // just ignore IO exception
        }
    }
}

From source file:edu.usc.goffish.gopher.impl.Main.java

public static void main(String[] args) {

    Properties properties = new Properties();
    try {/*from w w w .  j  a v a 2s .  c  o m*/
        properties.load(new FileInputStream(CONFIG_FILE));
    } catch (IOException e) {
        String message = "Error while loading Container Configuration from " + CONFIG_FILE + " Cause -"
                + e.getCause();
        log.warning(message);
    }

    if (args.length == 4) {

        PropertiesConfiguration propertiesConfiguration;
        String url = null;

        URI uri = URI.create(args[3]);

        String dataDir = uri.getPath();

        String currentHost = uri.getHost();
        try {

            propertiesConfiguration = new PropertiesConfiguration(dataDir + "/gofs.config");
            propertiesConfiguration.load();
            url = (String) propertiesConfiguration.getString(DataNode.DATANODE_NAMENODE_LOCATION_KEY);

        } catch (ConfigurationException e) {

            String message = " Error while reading gofs-config cause -" + e.getCause();
            handleException(message);
        }

        URI nameNodeUri = URI.create(url);

        INameNode nameNode = new RemoteNameNode(nameNodeUri);
        int partition = -1;
        try {
            for (URI u : nameNode.getDataNodes()) {
                if (URIHelper.isLocalURI(u)) {
                    IDataNode dataNode = DataNode.create(u);
                    IntCollection partitions = dataNode.getLocalPartitions(args[2]);
                    partition = partitions.iterator().nextInt();
                    break;
                }
            }

            if (partition == -1) {
                String message = "Partition not loaded from uri : " + nameNodeUri;
                handleException(message);
            }

            properties.setProperty(GopherInfraHandler.PARTITION, String.valueOf(partition));

        } catch (Exception e) {
            String message = "Error while loading Partitions from " + nameNodeUri + " Cause -" + e.getMessage();
            e.printStackTrace();
            handleException(message);
        }

        properties.setProperty(Constants.STATIC_PELLET_COUNT, String.valueOf(1));
        FloeRuntimeEnvironment environment = FloeRuntimeEnvironment.getEnvironment();
        environment.setSystemConfig(properties);
        properties.setProperty(Constants.CURRET_HOST, currentHost);
        String managerHost = args[0];
        int managerPort = Integer.parseInt(args[1]);

        Container container = environment.getContainer();
        container.setManager(managerHost, managerPort);

        DefaultClientConfig config = new DefaultClientConfig();
        config.getProperties().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);
        config.getFeatures().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true);

        Client c = Client.create(config);

        if (managerHost == null || managerPort == 0) {
            handleException("Manager Host / Port have to be configured in " + args[0]);
        }

        WebResource r = c.resource("http://" + managerHost + ":" + managerPort
                + "/Manager/addContainerInfo/Container=" + container.getContainerInfo().getContainerId()
                + "/Host=" + container.getContainerInfo().getContainerHost());
        c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
        r.post();
        log.log(Level.INFO, "Container started  ");

    } else {

        String message = "Invalid arguments , arg[0]=Manager host, "
                + "arg[1] = mamanger port,arg[2]=graph id,arg[3]=partition uri";

        message += "\n Current Arguments...." + args.length + "\n";
        for (int i = 0; i < args.length; i++) {
            message += "arg " + i + " : " + args[i] + "\n";
        }

        handleException(message);

    }

}

From source file:com.google.api.services.samples.youtube.cmdline.data.Topics.java

/**
 * Execute a search request that starts by calling the Freebase API to
 * retrieve a topic ID matching a user-provided term. Then initialize a
 * YouTube object to search for YouTube videos and call the YouTube Data
 * API's youtube.search.list method to retrieve a list of videos associated
 * with the selected Freebase topic and with another search query term,
 * which the user also enters. Finally, display the titles, video IDs, and
 * thumbnail images for the first five videos in the YouTube Data API
 * response.//w w  w .ja  va2s.c  om
 *
 * @param args This application does not use command line arguments.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Topics.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);
    }

    try {
        // Retrieve a Freebase topic ID based on a user-entered query term.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        // Prompt the user to enter a search query term. This term will be
        // used to retrieve YouTube search results related to the topic
        // selected above.
        String queryTerm = getInputQuery("search");

        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        // Set your developer key from the {{ Google Cloud Console }} for
        // non-authenticated requests. See:
        // {{ https://cloud.google.com/console }}
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

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

/**
 * Execute a search request that starts by calling the Freebase API to
 * retrieve a topic ID matching a user-provided term. Then initialize a
 * YouTube object to search for YouTube videos and call the YouTube Data
 * API's youtube.search.list method to retrieve a list of videos associated
 * with the selected Freebase topic and with another search query term,
 * which the user also enters. Finally, display the titles, video IDs, and
 * thumbnail images for the first five videos in the YouTube Data API
 * response.//from  w  ww. ja v a 2  s  .  c  om
 *
 * @param args This application does not use command line arguments.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Topics.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);
    }

    try {
        // Retrieve a Freebase topic ID based on a user-entered query term.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        // Prompt the user to enter a search query term. This term will be
        // used to retrieve YouTube search results related to the topic
        // selected above.
        String queryTerm = getInputQuery("search");

        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        // Set your developer key from the Google Developers Console for
        // non-authenticated requests. See:
        // https://cloud.google.com/console
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}