有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在EclipseLuna的maven项目中构建成功后如何运行

如何运行Maven You Tube API示例代码。我在eclipse控制台中得到了这条消息,运行Maven的下一步是什么

[INFO] Scanning for projects...
[INFO] 
[INFO] Using the builder  [INFO] Scanning for projects...
[INFO] 
[INFO] Using the builder   org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a   thread count of 1
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building youtube-api-cmdline-samples 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> maven-eclipse-plugin:2.9:eclipse (default-cli) @ samples >>>
[INFO] 
[INFO] <<< maven-eclipse-plugin:2.9:eclipse (default-cli) @ samples <<<
[INFO] 
[INFO] --- maven-eclipse-plugin:2.9:eclipse (default-cli) @ samples ---
[INFO] Not running eclipse plugin goal for pom project
[INFO] Using Eclipse Workspace: null
[INFO] Adding default classpath container: org.eclipse.jdt.launching.JRE_CONTAINER
[INFO] ------------------------------------------------------------------------   
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.672 s
[INFO] Finished at: 2014-12-12T10:53:45+05:30
[INFO] Final Memory: 7M/17M
[INFO] ------------------------------------------------------------------------

我的pom。xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.api.services.samples.youtube.cmdline</groupId>
<artifactId>samples</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>youtube-api-cmdline-samples</name>
<url>http://maven.apache.org</url>

<properties>
    <project.youtube.version>v3-rev107-1.18.0-rc</project.youtube.version>
    <project.youtube.analytics.version>v1-rev24-1.17.0-rc</project.youtube.analytics.version>
    <project.http.version>1.18.0-rc</project.http.version>
    <project.oauth.version>1.18.0-rc</project.oauth.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<repositories>
    <repository>
        <id>google-api-services</id>
        <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
    </repository>
</repositories>

<dependencies>

    <!-- YouTube Data V3 support -->
    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-youtube</artifactId>
        <version>${project.youtube.version}</version>
    </dependency>

    <!-- Required for any code that makes calls to the Google Analytics API -->
    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-youtubeAnalytics</artifactId>
        <version>${project.youtube.analytics.version}</version>
    </dependency>

    <!-- This dependency is only used for the Topics API sample, which requires the Jackson JSON parser -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.4</version>
    </dependency>

    <dependency>
        <groupId>com.google.http-client</groupId>
        <artifactId>google-http-client-jackson2</artifactId>
        <version>${project.http.version}</version>
    </dependency>

    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-jetty</artifactId>
        <version>${project.oauth.version}</version>
    </dependency>

    <dependency>
        <groupId>com.google.collections</groupId>
        <artifactId>google-collections</artifactId>
        <version>1.0</version>
    </dependency>

</dependencies>

<build>

    <plugins>
        <!-- Forces Maven to use Java 1.6 -->
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>

            <configuration>
                <source>1.7</source>
                <target>1.7</target>
                <packageing>pom</packageing>

                <compilerArgument></compilerArgument>
            </configuration>
        </plugin>
    </plugins>
</build>

</project>

这是我的java代码

/**
 * This example uses the YouTube Data and YouTube Analytics APIs to retrieve
 * YouTube Analytics data. It also uses OAuth 2.0 for authorization.
 *
 * @author Christoph Schwab-Ganser and Jeremy Walker
 */

package com.google.api.services.samples.youtube.cmdline.analytics;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtubeAnalytics.YouTubeAnalytics;
import com.google.api.services.youtubeAnalytics.model.ResultTable;
import com.google.api.services.youtubeAnalytics.model.ResultTable.ColumnHeaders;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.util.List;


 public class YouTubeAnalyticsReports {

/**
 * Define a global instance of the HTTP transport.
 */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

/**
 * Define a global instance of the JSON factory.
 */
private static final JsonFactory JSON_FACTORY = new JacksonFactory();

/**
 * Define a global instance of a Youtube object, which will be used
 * to make YouTube Data API requests.
 */
private static YouTube youtube;

/**
 * Define a global instance of a YoutubeAnalytics object, which will be
 * used to make YouTube Analytics API requests.
 */
private static YouTubeAnalytics analytics;

/**
 * This code authorizes the user, uses the YouTube Data API to retrieve
 * information about the user's YouTube channel, and then fetches and
 * prints statistics for the user's channel using the YouTube Analytics API.
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    // These scopes are required to access information about the
    // authenticated user's YouTube channel as well as Analytics
    // data for that channel.
    List<String> scopes = Lists.newArrayList(
            "https://www.googleapis.com/auth/yt-analytics.readonly",
            "https://www.googleapis.com/auth/youtube.readonly"


    );
   /* System.out.println("scopes "+
            scopes.toString());*/
    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "analyticsreports");

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-analytics-api-report-example")
                .build();

        // This object is used to make YouTube Analytics API requests.
        analytics = new YouTubeAnalytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-analytics-api-report-example")
                .build();

        // Construct a request to retrieve the current user's channel ID.
        YouTube.Channels.List channelRequest = youtube.channels().list("id,snippet");
        channelRequest.setMine(true);
        channelRequest.setFields("items(id,snippet/title)");
        ChannelListResponse channels = channelRequest.execute();

        // List channels associated with the user.
        List<Channel> listOfChannels = channels.getItems();

        // The user's default channel is the first item in the list.
        Channel defaultChannel = listOfChannels.get(0);
        String channelId = defaultChannel.getId();

        PrintStream writer = System.out;
        if (channelId == null) {
            writer.println("No channel found.");
        } else {
            writer.println("Default Channel: " + defaultChannel.getSnippet().getTitle() +
                    " ( " + channelId + " )\n");

            printData(writer, "Views Over Time.", executeViewsOverTimeQuery(analytics, channelId));
            printData(writer, "Top Videos", executeTopVideosQuery(analytics, channelId));
            printData(writer, "Demographics", executeDemographicsQuery(analytics, channelId));
        }
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

/**
 * Retrieve the views and unique viewers per day for the channel.
 *
 * @param analytics The service object used to access the Analytics API.
 * @param id        The channel ID from which to retrieve data.
 * @return The API response.
 * @throws IOException if an API error occurred.
 */
private static ResultTable executeViewsOverTimeQuery(YouTubeAnalytics analytics,
                                                     String id) throws IOException {

    return analytics.reports()
            .query("channel==" + id,     // channel id
                    "2012-01-01",         // Start date.
                    "2012-01-14",         // End date.
                    "views,uniques")      // Metrics.
            .setDimensions("day")
            .setSort("day")
            .execute();
}

/**
 * Retrieve the channel's 10 most viewed videos in descending order.
 *
 * @param analytics the analytics service object used to access the API.
 * @param id        the string id from which to retrieve data.
 * @return the response from the API.
 * @throws IOException if an API error occurred.
 */
private static ResultTable executeTopVideosQuery(YouTubeAnalytics analytics,
                                                 String id) throws IOException {

    return analytics.reports()
            .query("channel==" + id,                          // channel id
                    "2012-01-01",                              // Start date.
                    "2012-08-14",                              // End date.
                    "views,subscribersGained,subscribersLost") // Metrics.
            .setDimensions("video")
            .setSort("-views")
            .setMaxResults(10)
            .execute();
}

/**
 * Retrieve the demographics report for the channel.
 *
 * @param analytics the analytics service object used to access the API.
 * @param id        the string id from which to retrieve data.
 * @return the response from the API.
 * @throws IOException if an API error occurred.
 */
private static ResultTable executeDemographicsQuery(YouTubeAnalytics analytics,
                                                    String id) throws IOException {
    return analytics.reports()
            .query("channel==" + id,     // channel id
                    "2007-01-01",         // Start date.
                    "2012-08-14",         // End date.
                    "viewerPercentage")   // Metrics.
            .setDimensions("ageGroup,gender")
            .setSort("-viewerPercentage")
            .execute();
}

/**
 * Prints the API response. The channel name is printed along with
 * each column name and all the data in the rows.
 *
 * @param writer  stream to output to
 * @param title   title of the report
 * @param results data returned from the API.
 */
private static void printData(PrintStream writer, String title, ResultTable results) {
    writer.println("Report: " + title);
    if (results.getRows() == null || results.getRows().isEmpty()) {
        writer.println("No results Found.");
    } else {

        // Print column headers.
        for (ColumnHeaders header : results.getColumnHeaders()) {
            writer.printf("%30s", header.getName());
        }
        writer.println();

        // Print actual data.
        for (List<Object> row : results.getRows()) {
            for (int colNum = 0; colNum < results.getColumnHeaders().size(); colNum++) {
                ColumnHeaders header = results.getColumnHeaders().get(colNum);
                Object column = row.get(colNum);
                if ("INTEGER".equals(header.getUnknownKeys().get("dataType"))) {
                    long l = ((BigDecimal) column).longValue();
                    writer.printf("%30d", l);
                } else if ("FLOAT".equals(header.getUnknownKeys().get("dataType"))) {
                    writer.printf("%30f", column);
                } else if ("STRING".equals(header.getUnknownKeys().get("dataType"))) {
                    writer.printf("%30s", column);
                } else {
                    // default output.
                    writer.printf("%30s", column);
                }
            }
            writer.println();
        }
        writer.println();
    }
}

}

共 (2) 个答案

  1. # 1 楼答案

    试试这个,它可能会帮助你理解事物。:)

    在你的pom上。xml

       <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <mainClass>com.some.package.YourMainClass</mainClass>
                    <cleanupDaemonThreads>false</cleanupDaemonThreads>
                </configuration>
            </plugin>
        </plugins>
    

    这就是你如何以

        clean package install exec:java
    

    注意:这是我朋友的密码

    问题:

    你试过把

           <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    //this is where you gonna declare your main class
                    <mainClass>com.google.api.services.samples.youtube.cmdline.analytics.YouTubeAnalyticsReports</mainClass>
                    <cleanupDaemonThreads>false</cleanupDaemonThreads>
                </configuration>
            </plugin>
    

    <plugins></plugins>里面

  2. # 2 楼答案

    首先需要通过运行mvn compile进行编译,然后可以通过mvn exec:java -Dexec.mainClass="PATH_TO_MAIN"运行它

    如果您使用的是Eclipse,则可以向项目中添加某些运行配置。右键单击maven项目,然后单击Run as->Run Configurations然后添加一个新的Maven Build配置。您需要编译和执行,以便添加以下目标:

    compile exec:java -Dexec.mainClass="PATH_TO_CLASS_WITH_MAIN"