1

这是场景:

我正在运行一个 Java 应用程序,它调用 REST 接口,并将变量的一些状态作为整数取回(基本上是最后一次成功的构建 #form Teamcity)

现在,由于我从 Jenkins 运行该实用程序,我想比较两个 REST 调用之间的 LastSuccessfulBuild Number。做这个的最好方式是什么 ?这是我在代码方面的内容。

import java.io.File;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.TimeZone;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FileUtils;

public class LastSuccessBuildNum {

    private  final static String getDateTime()
    {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("EST"));
        return df.format(new Date());
    }

    public static void main(String[] args) {

        try {

            Client client = Client.create();
            Properties properties = new Properties();
            File f = File.createTempFile("default", ".properties");

            properties.load(new FileInputStream("config.properties"));

            String currentDir = System.getProperty("user.dir");


            String username = properties.getProperty("username");

            String pass = properties.getProperty("password");
            //System.out.println(pass);
            String buildNumber = properties.getProperty("buildNumber");


            client.addFilter(new HTTPBasicAuthFilter("username", "password"));

            WebResource webResource = client
                    .resource("http://a.b.c.d/teamcity/app/rest/buildTypes/id:bt26/builds/status:SUCCESS/number");
            ClientResponse response = webResource.accept("text/plain").get(
                    ClientResponse.class);

            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatus());
            }

            /**
             * Prepend timestamp to latestBuildNum
             */

            System.out.println(getDateTime());
            String latestBuildNum_1 = response.getEntity(String.class);

            //System.out.println("Output from Server .... \n");

            /** 
             * Save latest build number to a local file
             */
            //System.out.println(latestBuildNum);

            String datelbn = (getDateTime() + "-" + latestBuildNum_1);
            //System.out.println(datelbn);
            //If latestBuildNumberLocal < latestBuildNum, then save to file latestBuildNum
            // Else do nothing
            FileUtils.writeStringToFile(new File("PreMDNSlatestSuccBuildNum.txt"), latestBuildNum_1);
            /**
             * Get Content from the file, which would be the LatestBuildNumber at LAST run.
             * SO the NEXT run, will save the number in a different file.
             * Then we compare the contents of these two files
             * using StringToInt() and compare
             */

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}
4

1 回答 1

0

这是你想要的草图。有许多库可以减少“样板”的数量(例如 Apache Commons IO。Java 7 还整合了异常处理和资源清理。

此外,您还可以对这段代码做更多的事情以使其“准备好生产”(这只是一个草图)。对于初学者,我们应该使用日志库而不是 STDOUT(java.util.logging至少)。

最后,我的示例读取/写入原始 int,但您应该能够以几乎相同的方式读取/写入/解析字符串。

import java.io.*;
import java.util.concurrent.atomic.AtomicInteger;

public class GetLatestBuildNumber {


    private static final AtomicInteger number = new AtomicInteger();
    private static final String FILE_NAME = "latest_build_number.txt";

    public static void main(String[] args) {

        int latest = fetchLatestBuildNumber();
        writeLatestBuildNumber(latest);
        int next = fetchLatestBuildNumber();

        int previous;
        try {

            previous = readLatestBuildNumber();

            System.out.println("previous build number " + previous);
            System.out.println("current build number " + next);

        } catch (IOException ioe) {
            System.out.println("failed to read last build number " +
                        "from file " + FILE_NAME + ": " + ioe);
        } catch (NumberFormatException nfx) {
            System.out.println("failed to parse last build number: " + nfx);
        }

    }

    private static int fetchLatestBuildNumber() {
       return number.getAndIncrement();
    }

    private static void writeLatestBuildNumber(int number) {

        int latestBuildNumber = fetchLatestBuildNumber();
        FileWriter writer = null;
        try {
            writer = new FileWriter(FILE_NAME);
            writer.write(Integer.toString(latestBuildNumber));
        } catch (IOException ex) {
            System.out.println("failed to write build number "
                        + number + ", error: " + ex);
        } finally {
            try {
                if (writer != null) writer.close();
            } catch (IOException e) { /* we tried... */ }
        }

    }

    private static int readLatestBuildNumber() throws IOException  {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(FILE_NAME));
            String number = reader.readLine();
            return Integer.parseInt(number);
        } finally {
            try {
                if (reader != null) reader.close();
            } catch (IOException e) { /* we tried. */ }

        }

    }
}
于 2012-09-07T17:36:17.053 回答