gpt4 book ai didi

java - 为java应用程序的执行保留一个计数器

转载 作者:行者123 更新时间:2023-12-01 05:08:50 24 4
gpt4 key购买 nike

这是场景:

我正在运行一个 Java 应用程序,它调用 REST 接口(interface),并以整数形式返回一些变量状态(基本上是 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();

}

}

}

最佳答案

这是您想要的草图。有许多库可以减少“样板文件”的数量(例如 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. */ }

}

}
}

关于java - 为java应用程序的执行保留一个计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12321837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com