proj_name
stringclasses 26
values | relative_path
stringlengths 42
188
| class_name
stringlengths 2
53
| func_name
stringlengths 2
49
| masked_class
stringlengths 68
8.98k
| func_body
stringlengths 56
6.8k
| len_input
int64 27
2k
| len_output
int64 18
1.78k
| total
int64 60
2.05k
| relevant_context
stringclasses 793
values |
---|---|---|---|---|---|---|---|---|---|
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/Audio.java | Audio | init | class Audio {
/**
* keys
*/
private String apiKey;
private List<String> apiKeyList;
/**
* 自定义api host使用builder的方式构造client
*/
@Builder.Default
private String apiHost = Api.DEFAULT_API_HOST;
private Api apiClient;
private OkHttpClient okHttpClient;
/**
* 超时 默认300
*/
@Builder.Default
private long timeout = 300;
/**
* okhttp 代理
*/
@Builder.Default
private Proxy proxy = Proxy.NO_PROXY;
/**
* 初始化
*/
public Audio init() {<FILL_FUNCTION_BODY>}
public AudioResponse transcriptions(File audio,Transcriptions transcriptions){
RequestBody a = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), audio);
MultipartBody.Part aPart = MultipartBody.Part.createFormData("image", audio.getName(), a);
Single<AudioResponse> audioResponse =
this.apiClient.audioTranscriptions(aPart,transcriptions);
return audioResponse.blockingGet();
}
public AudioResponse translations(File audio,Transcriptions transcriptions){
RequestBody a = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), audio);
MultipartBody.Part aPart = MultipartBody.Part.createFormData("image", audio.getName(), a);
Single<AudioResponse> audioResponse =
this.apiClient.audioTranslations(aPart,transcriptions);
return audioResponse.blockingGet();
}
} |
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(chain -> {
Request original = chain.request();
String key = apiKey;
if (apiKeyList != null && !apiKeyList.isEmpty()) {
key = RandomUtil.randomEle(apiKeyList);
}
Request request = original.newBuilder()
.header(Header.AUTHORIZATION.getValue(), "Bearer " + key)
.header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}).addInterceptor(chain -> {
Request original = chain.request();
Response response = chain.proceed(original);
if (!response.isSuccessful()) {
String errorMsg = response.body().string();
log.error("请求异常:{}", errorMsg);
BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class);
if (Objects.nonNull(baseResponse.getError())) {
log.error(baseResponse.getError().getMessage());
throw new ChatException(baseResponse.getError().getMessage());
}
throw new ChatException("error");
}
return response;
});
client.connectTimeout(timeout, TimeUnit.SECONDS);
client.writeTimeout(timeout, TimeUnit.SECONDS);
client.readTimeout(timeout, TimeUnit.SECONDS);
if (Objects.nonNull(proxy)) {
client.proxy(proxy);
}
OkHttpClient httpClient = client.build();
this.okHttpClient = httpClient;
this.apiClient = new Retrofit.Builder()
.baseUrl(this.apiHost)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(JacksonConverterFactory.create())
.build()
.create(Api.class);
return this;
| 440 | 512 | 952 | <no_super_class> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/ChatGPT.java | ChatGPT | init | class ChatGPT {
/**
* keys
*/
private String apiKey;
private List<String> apiKeyList;
/**
* 自定义api host使用builder的方式构造client
*/
@Builder.Default
private String apiHost = Api.DEFAULT_API_HOST;
private Api apiClient;
private OkHttpClient okHttpClient;
/**
* 超时 默认300
*/
@Builder.Default
private long timeout = 300;
/**
* okhttp 代理
*/
@Builder.Default
private Proxy proxy = Proxy.NO_PROXY;
/**
* 初始化:与服务端建立连接,成功后可直接与服务端进行对话
*/
public ChatGPT init() {<FILL_FUNCTION_BODY>}
/**
* 最新版的GPT-3.5 chat completion 更加贴近官方网站的问答模型
*
* @param chatCompletion 问答参数,即咨询的内容
* @return 服务端的问答响应
*/
public ChatCompletionResponse chatCompletion(ChatCompletion chatCompletion) {
Single<ChatCompletionResponse> chatCompletionResponse =
this.apiClient.chatCompletion(chatCompletion);
return chatCompletionResponse.blockingGet();
}
/**
* 支持多个问答参数来与服务端进行对话
*
* @param messages 问答参数,即咨询的内容
* @return 服务端的问答响应
*/
public ChatCompletionResponse chatCompletion(List<Message> messages) {
ChatCompletion chatCompletion = ChatCompletion.builder().messages(messages).build();
return this.chatCompletion(chatCompletion);
}
/**
* 与服务端进行对话
* @param message 问答参数,即咨询的内容
* @return 服务端的问答响应
*/
public String chat(String message) {
ChatCompletion chatCompletion = ChatCompletion.builder()
.messages(Arrays.asList(Message.of(message)))
.build();
ChatCompletionResponse response = this.chatCompletion(chatCompletion);
return response.getChoices().get(0).getMessage().getContent();
}
/**
* 余额查询
*
* @return 余额总金额及明细
*/
public CreditGrantsResponse creditGrants() {
Single<CreditGrantsResponse> creditGrants = this.apiClient.creditGrants();
return creditGrants.blockingGet();
}
/**
* 余额查询
*
* @return 余额总金额
*/
public BigDecimal balance() {
Single<SubscriptionData> subscription = apiClient.subscription();
SubscriptionData subscriptionData = subscription.blockingGet();
BigDecimal total = subscriptionData.getHardLimitUsd();
DateTime start = DateUtil.offsetDay(new Date(), -90);
DateTime end = DateUtil.offsetDay(new Date(), 1);
Single<UseageResponse> usage = apiClient.usage(formatDate(start), formatDate(end));
UseageResponse useageResponse = usage.blockingGet();
BigDecimal used = useageResponse.getTotalUsage().divide(BigDecimal.valueOf(100));
return total.subtract(used);
}
/**
* 新建连接进行余额查询
*
* @return 余额总金额
*/
public static BigDecimal balance(String key) {
ChatGPT chatGPT = ChatGPT.builder()
.apiKey(key)
.build()
.init();
return chatGPT.balance();
}
} |
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(chain -> {
Request original = chain.request();
String key = apiKey;
if (apiKeyList != null && !apiKeyList.isEmpty()) {
key = RandomUtil.randomEle(apiKeyList);
}
Request request = original.newBuilder()
.header(Header.AUTHORIZATION.getValue(), "Bearer " + key)
.header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}).addInterceptor(chain -> {
Request original = chain.request();
Response response = chain.proceed(original);
if (!response.isSuccessful()) {
String errorMsg = response.body().string();
log.error("请求异常:{}", errorMsg);
BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class);
if (Objects.nonNull(baseResponse.getError())) {
log.error(baseResponse.getError().getMessage());
throw new ChatException(baseResponse.getError().getMessage());
}
throw new ChatException("ChatGPT init error!");
}
return response;
});
client.connectTimeout(timeout, TimeUnit.SECONDS);
client.writeTimeout(timeout, TimeUnit.SECONDS);
client.readTimeout(timeout, TimeUnit.SECONDS);
if (Objects.nonNull(proxy)) {
client.proxy(proxy);
}
OkHttpClient httpClient = client.build();
this.okHttpClient = httpClient;
this.apiClient = new Retrofit.Builder()
.baseUrl(this.apiHost)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(JacksonConverterFactory.create())
.build()
.create(Api.class);
return this;
| 965 | 517 | 1,482 | <no_super_class> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/ChatGPTStream.java | ChatGPTStream | streamChatCompletion | class ChatGPTStream {
private String apiKey;
private List<String> apiKeyList;
private OkHttpClient okHttpClient;
/**
* 连接超时
*/
@Builder.Default
private long timeout = 90;
/**
* 网络代理
*/
@Builder.Default
private Proxy proxy = Proxy.NO_PROXY;
/**
* 反向代理
*/
@Builder.Default
private String apiHost = Api.DEFAULT_API_HOST;
/**
* 初始化
*/
public ChatGPTStream init() {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.connectTimeout(timeout, TimeUnit.SECONDS);
client.writeTimeout(timeout, TimeUnit.SECONDS);
client.readTimeout(timeout, TimeUnit.SECONDS);
if (Objects.nonNull(proxy)) {
client.proxy(proxy);
}
okHttpClient = client.build();
return this;
}
/**
* 流式输出
*/
public void streamChatCompletion(ChatCompletion chatCompletion,
EventSourceListener eventSourceListener) {<FILL_FUNCTION_BODY>}
/**
* 流式输出
*/
public void streamChatCompletion(List<Message> messages,
EventSourceListener eventSourceListener) {
ChatCompletion chatCompletion = ChatCompletion.builder()
.messages(messages)
.stream(true)
.build();
streamChatCompletion(chatCompletion, eventSourceListener);
}
} |
chatCompletion.setStream(true);
try {
EventSource.Factory factory = EventSources.createFactory(okHttpClient);
ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(chatCompletion);
String key = apiKey;
if (apiKeyList != null && !apiKeyList.isEmpty()) {
key = RandomUtil.randomEle(apiKeyList);
}
Request request = new Request.Builder()
.url(apiHost + "v1/chat/completions")
.post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()),
requestBody))
.header("Authorization", "Bearer " + key)
.build();
factory.newEventSource(request, eventSourceListener);
} catch (Exception e) {
log.error("请求出错:{}", e);
}
| 414 | 232 | 646 | <no_super_class> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/ConsoleChatGPT.java | ConsoleChatGPT | main | class ConsoleChatGPT {
public static Proxy proxy = Proxy.NO_PROXY;
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
private static BigDecimal getBalance(String key) {
ChatGPT chatGPT = ChatGPT.builder()
.apiKey(key)
.proxy(proxy)
.build()
.init();
return chatGPT.balance();
}
private static void check(String key) {
if (key == null || key.isEmpty()) {
throw new RuntimeException("请输入正确的KEY");
}
}
@SneakyThrows
public static String getInput(String prompt) {
System.out.print(prompt);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<String> lines = new ArrayList<>();
String line;
try {
while ((line = reader.readLine()) != null && !line.isEmpty()) {
lines.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return lines.stream().collect(Collectors.joining("\n"));
}
} |
System.out.println("ChatGPT - Java command-line interface");
System.out.println("Press enter twice to submit your question.");
System.out.println();
System.out.println("按两次回车以提交您的问题!!!");
System.out.println("按两次回车以提交您的问题!!!");
System.out.println("按两次回车以提交您的问题!!!");
System.out.println();
System.out.println("Please enter APIKEY, press Enter twice to submit:");
String key = getInput("请输入APIKEY,按两次回车以提交:\n");
check(key);
// 询问用户是否使用代理 国内需要代理
System.out.println("是否使用代理?(y/n): ");
System.out.println("use proxy?(y/n): ");
String useProxy = getInput("按两次回车以提交:\n");
if (useProxy.equalsIgnoreCase("y")) {
// 输入代理地址
System.out.println("请输入代理类型(http/socks): ");
String type = getInput("按两次回车以提交:\n");
// 输入代理地址
System.out.println("请输入代理IP: ");
String proxyHost = getInput("按两次回车以提交:\n");
// 输入代理端口
System.out.println("请输入代理端口: ");
String portStr = getInput("按两次回车以提交:\n");
Integer proxyPort = Integer.parseInt(portStr);
if (type.equals("http")) {
proxy = Proxys.http(proxyHost, proxyPort);
} else {
proxy = Proxys.socks5(proxyHost, proxyPort);
}
}
// System.out.println("Inquiry balance...");
// System.out.println("查询余额中...");
// BigDecimal balance = getBalance(key);
// System.out.println("API KEY balance: " + balance.toPlainString());
//
// if (!NumberUtil.isGreater(balance, BigDecimal.ZERO)) {
// System.out.println("API KEY 余额不足: ");
// return;
// }
while (true) {
String prompt = getInput("\nYou:\n");
ChatGPTStream chatGPT = ChatGPTStream.builder()
.apiKey(key)
.proxy(proxy)
.build()
.init();
System.out.println("AI: ");
//卡住
CountDownLatch countDownLatch = new CountDownLatch(1);
Message message = Message.of(prompt);
ConsoleStreamListener listener = new ConsoleStreamListener() {
@Override
public void onError(Throwable throwable, String response) {
throwable.printStackTrace();
countDownLatch.countDown();
}
};
listener.setOnComplate(msg -> {
countDownLatch.countDown();
});
chatGPT.streamChatCompletion(Arrays.asList(message), listener);
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
| 311 | 838 | 1,149 | <no_super_class> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/Embedding.java | Embedding | init | class Embedding {
/**
* keys
*/
private String apiKey;
private List<String> apiKeyList;
/**
* 自定义api host使用builder的方式构造client
*/
@Builder.Default
private String apiHost = Api.DEFAULT_API_HOST;
private Api apiClient;
private OkHttpClient okHttpClient;
/**
* 超时 默认300
*/
@Builder.Default
private long timeout = 300;
/**
* okhttp 代理
*/
@Builder.Default
private Proxy proxy = Proxy.NO_PROXY;
public Embedding init() {<FILL_FUNCTION_BODY>}
/**
* 生成向量
*/
public EmbeddingResult createEmbeddings(EmbeddingRequest request) {
Single<EmbeddingResult> embeddingResultSingle = this.apiClient.createEmbeddings(request);
return embeddingResultSingle.blockingGet();
}
/**
* 生成向量
*/
public EmbeddingResult createEmbeddings(String input, String user) {
EmbeddingRequest request = EmbeddingRequest.builder()
.input(Collections.singletonList(input))
.model(EmbeddingRequest.EmbeddingModelEnum.TEXT_EMBEDDING_ADA_002.getModelName())
.user(user)
.build();
Single<EmbeddingResult> embeddingResultSingle = this.apiClient.createEmbeddings(request);
return embeddingResultSingle.blockingGet();
}
} |
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(chain -> {
Request original = chain.request();
String key = apiKey;
if (apiKeyList != null && !apiKeyList.isEmpty()) {
key = RandomUtil.randomEle(apiKeyList);
}
Request request = original.newBuilder()
.header(Header.AUTHORIZATION.getValue(), "Bearer " + key)
.header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}).addInterceptor(chain -> {
Request original = chain.request();
Response response = chain.proceed(original);
if (!response.isSuccessful()) {
String errorMsg = response.body().string();
log.error("请求异常:{}", errorMsg);
BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class);
if (Objects.nonNull(baseResponse.getError())) {
log.error(baseResponse.getError().getMessage());
throw new ChatException(baseResponse.getError().getMessage());
}
throw new ChatException("error");
}
return response;
});
client.connectTimeout(timeout, TimeUnit.SECONDS);
client.writeTimeout(timeout, TimeUnit.SECONDS);
client.readTimeout(timeout, TimeUnit.SECONDS);
if (Objects.nonNull(proxy)) {
client.proxy(proxy);
}
this.okHttpClient = client.build();
this.apiClient = new Retrofit.Builder()
.baseUrl(this.apiHost)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(JacksonConverterFactory.create())
.build()
.create(Api.class);
return this;
| 413 | 496 | 909 | <no_super_class> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/Images.java | Images | init | class Images {
/**
* keys
*/
private String apiKey;
private List<String> apiKeyList;
/**
* 自定义api host使用builder的方式构造client
*/
@Builder.Default
private String apiHost = Api.DEFAULT_API_HOST;
private Api apiClient;
private OkHttpClient okHttpClient;
/**
* 超时 默认300
*/
@Builder.Default
private long timeout = 300;
/**
* okhttp 代理
*/
@Builder.Default
private Proxy proxy = Proxy.NO_PROXY;
/**
* 初始化
*/
public Images init() {<FILL_FUNCTION_BODY>}
public ImagesRensponse generations(Generations generations){
Single<ImagesRensponse> imagesRensponse =
this.apiClient.imageGenerations(generations);
return imagesRensponse.blockingGet();
}
public ImagesRensponse edits(File image,File mask,Edits edits){
RequestBody i = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), image);
MultipartBody.Part iPart = MultipartBody.Part.createFormData("image", image.getName(), i);
RequestBody m = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), mask);
MultipartBody.Part mPart = MultipartBody.Part.createFormData("mask", mask.getName(), m);
Single<ImagesRensponse> imagesRensponse =
this.apiClient.imageEdits(iPart,mPart,edits);
return imagesRensponse.blockingGet();
}
public ImagesRensponse variations(File image,Variations variations){
RequestBody i = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), image);
MultipartBody.Part iPart = MultipartBody.Part.createFormData("image", image.getName(), i);
Single<ImagesRensponse> imagesRensponse =
this.apiClient.imageVariations(iPart,variations);
return imagesRensponse.blockingGet();
}
} |
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.addInterceptor(chain -> {
Request original = chain.request();
String key = apiKey;
if (apiKeyList != null && !apiKeyList.isEmpty()) {
key = RandomUtil.randomEle(apiKeyList);
}
Request request = original.newBuilder()
.header(Header.AUTHORIZATION.getValue(), "Bearer " + key)
.header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}).addInterceptor(chain -> {
Request original = chain.request();
Response response = chain.proceed(original);
if (!response.isSuccessful()) {
String errorMsg = response.body().string();
log.error("请求异常:{}", errorMsg);
BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class);
if (Objects.nonNull(baseResponse.getError())) {
log.error(baseResponse.getError().getMessage());
throw new ChatException(baseResponse.getError().getMessage());
}
throw new ChatException("error");
}
return response;
});
client.connectTimeout(timeout, TimeUnit.SECONDS);
client.writeTimeout(timeout, TimeUnit.SECONDS);
client.readTimeout(timeout, TimeUnit.SECONDS);
if (Objects.nonNull(proxy)) {
client.proxy(proxy);
}
OkHttpClient httpClient = client.build();
this.okHttpClient = httpClient;
this.apiClient = new Retrofit.Builder()
.baseUrl(this.apiHost)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(JacksonConverterFactory.create())
.build()
.create(Api.class);
return this;
| 571 | 512 | 1,083 | <no_super_class> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/Test.java | Test | main | class Test {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
} |
Proxy proxys = Proxys.http("127.0.0.1",10809);
Images images = Images.builder()
.proxy(proxys)
.apiKey("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")
.apiHost("https://api.openai.com/")
.timeout(900)
.build()
.init();
File file = new File("C:\\Users\\马同徽\\Pictures\\微信图片_20230606140621.png");
Variations variations = Variations.ofURL(1,"256x256");
Generations generations = Generations.ofURL("一只鲨鱼和一直蜜蜂结合成一种动物",1,"256x256");
ImagesRensponse imagesRensponse = images.variations(file,variations);
System.out.println(imagesRensponse.getCreated());
System.out.println(imagesRensponse.getCode());
System.out.println(imagesRensponse.getMsg());
List<Object> data = imagesRensponse.getData();
for(Object o:data){
System.out.println(o.toString());
}
/*Audio audio = Audio.builder()
.proxy(proxys)
.apiKey("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")
.apiHost("https://api.openai.com/")
.timeout(900)
.build()
.init();
File file = new File("D:\\Jenny.mp3");
Transcriptions transcriptions = Transcriptions.of(file, AudioModel.WHISPER1.getValue());
AudioResponse response = audio.transcriptions(transcriptions);
System.out.println(response.getText());*/
| 30 | 520 | 550 | <no_super_class> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/listener/AbstractStreamListener.java | AbstractStreamListener | onEvent | class AbstractStreamListener extends EventSourceListener {
protected String lastMessage = "";
/**
* Called when all new message are received.
*
* @param message the new message
*/
@Setter
@Getter
protected Consumer<String> onComplate = s -> {
};
/**
* Called when a new message is received.
* 收到消息 单个字
*
* @param message the new message
*/
public abstract void onMsg(String message);
/**
* Called when an error occurs.
* 出错时调用
*
* @param throwable the throwable that caused the error
* @param response the response associated with the error, if any
*/
public abstract void onError(Throwable throwable, String response);
@Override
public void onOpen(EventSource eventSource, Response response) {
// do nothing
}
@Override
public void onClosed(EventSource eventSource) {
// do nothing
}
@Override
public void onEvent(EventSource eventSource, String id, String type, String data) {<FILL_FUNCTION_BODY>}
@SneakyThrows
@Override
public void onFailure(EventSource eventSource, Throwable throwable, Response response) {
try {
log.error("Stream connection error: {}", throwable);
String responseText = "";
if (Objects.nonNull(response)) {
responseText = response.body().string();
}
log.error("response:{}", responseText);
String forbiddenText = "Your access was terminated due to violation of our policies";
if (StrUtil.contains(responseText, forbiddenText)) {
log.error("Chat session has been terminated due to policy violation");
log.error("检测到号被封了");
}
String overloadedText = "That model is currently overloaded with other requests.";
if (StrUtil.contains(responseText, overloadedText)) {
log.error("检测到官方超载了,赶紧优化你的代码,做重试吧");
}
this.onError(throwable, responseText);
} catch (Exception e) {
log.warn("onFailure error:{}", e);
// do nothing
} finally {
eventSource.cancel();
}
}
} |
if (data.equals("[DONE]")) {
onComplate.accept(lastMessage);
return;
}
ChatCompletionResponse response = JSON.parseObject(data, ChatCompletionResponse.class);
// 读取Json
List<ChatChoice> choices = response.getChoices();
if (choices == null || choices.isEmpty()) {
return;
}
Message delta = choices.get(0).getDelta();
String text = delta.getContent();
if (text != null) {
lastMessage += text;
onMsg(text);
}
| 612 | 158 | 770 | <methods>public void <init>() ,public void onClosed(okhttp3.sse.EventSource) ,public void onEvent(okhttp3.sse.EventSource, java.lang.String, java.lang.String, java.lang.String) ,public void onFailure(okhttp3.sse.EventSource, java.lang.Throwable, okhttp3.Response) ,public void onOpen(okhttp3.sse.EventSource, okhttp3.Response) <variables> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/util/ChatContextHolder.java | ChatContextHolder | add | class ChatContextHolder {
private static Map<String, List<Message>> context = new HashMap<>();
/**
* 获取对话历史
*
* @param id
* @return
*/
public static List<Message> get(String id) {
List<Message> messages = context.get(id);
if (messages == null) {
messages = new ArrayList<>();
context.put(id, messages);
}
return messages;
}
/**
* 添加对话
*
* @param id
* @return
*/
public static void add(String id, String msg) {
Message message = Message.builder().content(msg).build();
add(id, message);
}
/**
* 添加对话
*
* @param id
* @return
*/
public static void add(String id, Message message) {<FILL_FUNCTION_BODY>}
/**
* 清除对话
* @param id
*/
public static void remove(String id) {
context.remove(id);
}
} |
List<Message> messages = context.get(id);
if (messages == null) {
messages = new ArrayList<>();
context.put(id, messages);
}
messages.add(message);
| 293 | 55 | 348 | <no_super_class> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/util/SseHelper.java | SseHelper | complete | class SseHelper {
public void complete(SseEmitter sseEmitter) {<FILL_FUNCTION_BODY>}
public void send(SseEmitter sseEmitter, Object data) {
try {
sseEmitter.send(data);
} catch (Exception e) {
}
}
} |
try {
sseEmitter.complete();
} catch (Exception e) {
}
| 95 | 31 | 126 | <no_super_class> |
PlexPt_chatgpt-java | chatgpt-java/src/main/java/com/plexpt/chatgpt/util/TokensUtil.java | TokensUtil | tokens | class TokensUtil {
private static final Map<String, Encoding> modelEncodingMap = new HashMap<>();
private static final EncodingRegistry encodingRegistry = Encodings.newDefaultEncodingRegistry();
static {
for (ChatCompletion.Model model : ChatCompletion.Model.values()) {
Optional<Encoding> encodingForModel = encodingRegistry.getEncodingForModel(model.getName());
encodingForModel.ifPresent(encoding -> modelEncodingMap.put(model.getName(), encoding));
}
}
/**
* 计算tokens
* @param modelName 模型名称
* @param messages 消息列表
* @return 计算出的tokens数量
*/
public static int tokens(String modelName, List<Message> messages) {<FILL_FUNCTION_BODY>}
} |
Encoding encoding = modelEncodingMap.get(modelName);
if (encoding == null) {
throw new IllegalArgumentException("Unsupported model: " + modelName);
}
int tokensPerMessage = 0;
int tokensPerName = 0;
if (modelName.startsWith("gpt-4")) {
tokensPerMessage = 3;
tokensPerName = 1;
} else if (modelName.startsWith("gpt-3.5-turbo")) {
tokensPerMessage = 4; // every message follows <|start|>{role/name}\n{content}<|end|>\n
tokensPerName = -1; // if there's a name, the role is omitted
}
int sum = 0;
for (Message message : messages) {
sum += tokensPerMessage;
sum += encoding.countTokens(message.getContent());
sum += encoding.countTokens(message.getRole());
if (StrUtil.isNotBlank(message.getName())) {
sum += encoding.countTokens(message.getName());
sum += tokensPerName;
}
}
sum += 3;
return sum;
| 205 | 291 | 496 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/config/AliPayConfig.java | AliPayConfig | check | class AliPayConfig extends PayConfig {
/**
* appId
*/
private String appId;
/**
* 商户私钥
*/
private String privateKey;
/**
* 支付宝公钥
*/
private String aliPayPublicKey;
public void check() {<FILL_FUNCTION_BODY>}
} |
Objects.requireNonNull(appId, "config param 'appId' is null.");
Objects.requireNonNull(privateKey, "config param 'privateKey' is null.");
Objects.requireNonNull(aliPayPublicKey, "config param 'aliPayPublicKey' is null.");
if (appId.length() > 32) {
throw new IllegalArgumentException("config param 'appId' is incorrect: size exceeds 32.");
}
| 95 | 113 | 208 | <methods>public void check() ,public java.lang.String getNotifyUrl() ,public java.lang.String getReturnUrl() ,public boolean isSandbox() ,public void setNotifyUrl(java.lang.String) ,public void setReturnUrl(java.lang.String) ,public void setSandbox(boolean) <variables>private java.lang.String notifyUrl,private java.lang.String returnUrl,private boolean sandbox |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/config/PayConfig.java | PayConfig | check | class PayConfig {
/**
* 支付完成后的异步通知地址.
*/
private String notifyUrl;
/**
* 支付完成后的同步返回地址.
*/
private String returnUrl;
/**
* 默认非沙箱测试
*/
private boolean sandbox = false;
public boolean isSandbox() {
return sandbox;
}
public void setSandbox(boolean sandbox) {
this.sandbox = sandbox;
}
public String getNotifyUrl() {
return notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public String getReturnUrl() {
return returnUrl;
}
public void setReturnUrl(String returnUrl) {
this.returnUrl = returnUrl;
}
public void check() {<FILL_FUNCTION_BODY>}
} |
Objects.requireNonNull(notifyUrl, "config param 'notifyUrl' is null.");
if (!notifyUrl.startsWith("http") && !notifyUrl.startsWith("https")) {
throw new IllegalArgumentException("config param 'notifyUrl' does not start with http/https.");
}
if (notifyUrl.length() > 256) {
throw new IllegalArgumentException("config param 'notifyUrl' is incorrect: size exceeds 256.");
}
if (returnUrl != null) {
if (!returnUrl.startsWith("http") && !returnUrl.startsWith("https")) {
throw new IllegalArgumentException("config param 'returnUrl' does not start with http/https.");
}
if (returnUrl.length() > 256) {
throw new IllegalArgumentException("config param 'returnUrl' is incorrect: size exceeds 256.");
}
}
| 251 | 219 | 470 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/config/WxPayConfig.java | WxPayConfig | initSSLContext | class WxPayConfig extends PayConfig {
/**
* 公众号appId
*/
private String appId;
/**
* 公众号appSecret
*/
private String appSecret;
/**
* 小程序appId
*/
private String miniAppId;
/**
* app应用appid
*/
private String appAppId;
/**
* 商户号
*/
private String mchId;
/**
* 商户密钥
*/
private String mchKey;
/**
* 商户证书路径
*/
private String keyPath;
/**
* 证书内容
*/
private SSLContext sslContext;
/**
* 初始化证书
* @return
*/
public SSLContext initSSLContext() {<FILL_FUNCTION_BODY>}
} |
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(this.keyPath));
} catch (IOException e) {
throw new RuntimeException("读取微信商户证书文件出错", e);
}
try {
KeyStore keystore = KeyStore.getInstance("PKCS12");
char[] partnerId2charArray = mchId.toCharArray();
keystore.load(inputStream, partnerId2charArray);
this.sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build();
return this.sslContext;
} catch (Exception e) {
throw new RuntimeException("证书文件有问题,请核实!", e);
} finally {
IOUtils.closeQuietly(inputStream);
}
| 234 | 208 | 442 | <methods>public void check() ,public java.lang.String getNotifyUrl() ,public java.lang.String getReturnUrl() ,public boolean isSandbox() ,public void setNotifyUrl(java.lang.String) ,public void setReturnUrl(java.lang.String) ,public void setSandbox(boolean) <variables>private java.lang.String notifyUrl,private java.lang.String returnUrl,private boolean sandbox |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/BestPayServiceImpl.java | BestPayServiceImpl | payBank | class BestPayServiceImpl implements BestPayService {
/**
* TODO 重构
* 暂时先再引入一个config
*/
private WxPayConfig wxPayConfig;
private AliPayConfig aliPayConfig;
public void setWxPayConfig(WxPayConfig wxPayConfig) {
this.wxPayConfig = wxPayConfig;
}
public void setAliPayConfig(AliPayConfig aliPayConfig) {
this.aliPayConfig = aliPayConfig;
}
@Override
public PayResponse pay(PayRequest request) {
Objects.requireNonNull(request, "request params must not be null");
//微信支付
if (BestPayPlatformEnum.WX == request.getPayTypeEnum().getPlatform()) {
WxPayServiceImpl wxPayService = new WxPayServiceImpl();
wxPayService.setWxPayConfig(this.wxPayConfig);
return wxPayService.pay(request);
}
// 支付宝支付
else if (BestPayPlatformEnum.ALIPAY == request.getPayTypeEnum().getPlatform()) {
AliPayServiceImpl aliPayService = new AliPayServiceImpl();
aliPayService.setAliPayConfig(aliPayConfig);
return aliPayService.pay(request);
}
throw new RuntimeException("错误的支付方式");
}
/**
* 同步返回
*
* @param request
* @return
*/
@Override
public PayResponse syncNotify(HttpServletRequest request) {
return null;
}
@Override
public boolean verify(Map<String, String> toBeVerifiedParamMap, SignType signType, String sign) {
return false;
}
/**
* 异步回调
*
* @return
*/
@Override
public PayResponse asyncNotify(String notifyData) {
//<xml>开头的是微信通知
if (notifyData.startsWith("<xml>")) {
WxPayServiceImpl wxPayService = new WxPayServiceImpl();
wxPayService.setWxPayConfig(this.wxPayConfig);
return wxPayService.asyncNotify(notifyData);
} else {
AliPayServiceImpl aliPayService = new AliPayServiceImpl();
aliPayService.setAliPayConfig(aliPayConfig);
return aliPayService.asyncNotify(notifyData);
}
}
@Override
public RefundResponse refund(RefundRequest request) {
if (request.getPayPlatformEnum() == BestPayPlatformEnum.WX) {
WxPayServiceImpl wxPayService = new WxPayServiceImpl();
wxPayService.setWxPayConfig(this.wxPayConfig);
return wxPayService.refund(request);
} else if (request.getPayPlatformEnum() == BestPayPlatformEnum.ALIPAY) {
AliPayServiceImpl aliPayService = new AliPayServiceImpl();
aliPayService.setAliPayConfig(this.aliPayConfig);
return aliPayService.refund(request);
}
throw new RuntimeException("错误的支付平台");
}
/**
* 查询订单
*
* @param request
* @return
*/
@Override
public OrderQueryResponse query(OrderQueryRequest request) {
if (request.getPlatformEnum() == BestPayPlatformEnum.WX) {
WxPayServiceImpl wxPayService = new WxPayServiceImpl();
wxPayService.setWxPayConfig(this.wxPayConfig);
return wxPayService.query(request);
} else if (request.getPlatformEnum() == BestPayPlatformEnum.ALIPAY) {
AliPayServiceImpl aliPayService = new AliPayServiceImpl();
aliPayService.setAliPayConfig(this.aliPayConfig);
return aliPayService.query(request);
}
throw new RuntimeException("错误的支付平台");
}
@Override
public String downloadBill(DownloadBillRequest request) {
WxPayServiceImpl wxPayService = new WxPayServiceImpl();
wxPayService.setWxPayConfig(this.wxPayConfig);
return wxPayService.downloadBill(request);
}
@Override
public String getQrCodeUrl(String productId) {
WxPayServiceImpl wxPayService = new WxPayServiceImpl();
wxPayService.setWxPayConfig(this.wxPayConfig);
return wxPayService.getQrCodeUrl(productId);
}
@Override
public CloseResponse close(CloseRequest request) {
if (request.getPayTypeEnum().getPlatform() == BestPayPlatformEnum.ALIPAY) {
AliPayServiceImpl aliPayService = new AliPayServiceImpl();
aliPayService.setAliPayConfig(this.aliPayConfig);
return aliPayService.close(request);
}
throw new RuntimeException("尚未支持该种支付方式");
}
@Override
public PayBankResponse payBank(PayBankRequest request) {<FILL_FUNCTION_BODY>}
} |
if (request.getPayTypeEnum().getPlatform() == BestPayPlatformEnum.WX) {
WxPayServiceImpl wxPayService = new WxPayServiceImpl();
wxPayService.setWxPayConfig(this.wxPayConfig);
return wxPayService.payBank(request);
} else if (request.getPayTypeEnum().getPlatform() == BestPayPlatformEnum.ALIPAY) {
AliPayServiceImpl aliPayService = new AliPayServiceImpl();
aliPayService.setAliPayConfig(this.aliPayConfig);
return aliPayService.payBank(request);
}
throw new RuntimeException("尚未支持该种支付方式");
| 1,273 | 167 | 1,440 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/WxEncryptAndDecryptServiceImpl.java | WxEncryptAndDecryptServiceImpl | decrypt | class WxEncryptAndDecryptServiceImpl extends AbstractEncryptAndDecryptServiceImpl {
/**
* 密钥算法
*/
private static final String ALGORITHM = "AES";
/**
* 加解密算法/工作模式/填充方式
*/
private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";
/**
* 加密
*
* @param key
* @param data
* @return
*/
@Override
public Object encrypt(String key, String data) {
return super.encrypt(key, data);
}
/**
* 解密
* https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_16#menu1
*
* @param key
* @param data
* @return
*/
@Override
public Object decrypt(String key, String data) {<FILL_FUNCTION_BODY>}
} |
Security.addProvider(new BouncyCastleProvider());
SecretKeySpec aesKey = new SecretKeySpec(DigestUtils.md5Hex(key).toLowerCase().getBytes(), ALGORITHM);
Cipher cipher = null;
try {
cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
try {
cipher.init(Cipher.DECRYPT_MODE, aesKey);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
try {
return new String(cipher.doFinal(Base64.getDecoder().decode(data)));
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
| 272 | 261 | 533 | <methods>public java.lang.Object decrypt(java.lang.String, java.lang.String) ,public java.lang.Object encrypt(java.lang.String, java.lang.String) <variables> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/WxPaySandboxKey.java | WxPaySandboxKey | get | class WxPaySandboxKey {
public void get(String mchId, String mchKey) {<FILL_FUNCTION_BODY>}
@Data
@Root(name = "xml")
static class SandboxParam {
@Element(name = "mch_id")
private String mchId;
@Element(name = "nonce_str")
private String nonceStr;
@Element(name = "sign")
private String sign;
public Map<String, String> buildMap() {
Map<String, String> map = new HashMap<>();
map.put("mch_id", this.mchId);
map.put("nonce_str", this.nonceStr);
return map;
}
}
} |
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(WxPayConstants.WXPAY_GATEWAY)
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
SandboxParam sandboxParam = new SandboxParam();
sandboxParam.setMchId(mchId);
sandboxParam.setNonceStr(RandomUtil.getRandomStr());
sandboxParam.setSign(WxPaySignature.sign(sandboxParam.buildMap(), mchKey));
String xml = XmlUtil.toString(sandboxParam);
RequestBody body = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
Call<WxPaySandboxKeyResponse> call = retrofit.create(WxPayApi.class).getsignkey(body);
Response<WxPaySandboxKeyResponse> retrofitResponse = null;
try {
retrofitResponse = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
if (!retrofitResponse.isSuccessful()) {
throw new RuntimeException("【微信统一支付】发起支付,网络异常," + retrofitResponse);
}
Object response = retrofitResponse.body();
log.info("【获取微信沙箱密钥】response={}", JsonUtil.toJson(response));
| 201 | 344 | 545 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/WxPaySignature.java | WxPaySignature | sign | class WxPaySignature {
/**
* 签名
* @param params
* @param signKey
* @return
*/
public static String sign(Map<String, String> params, String signKey) {<FILL_FUNCTION_BODY>}
/**
* 签名for App
* https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&index=2
* @param params
* @param signKey
* @return
*/
public static String signForApp(Map<String, String> params, String signKey) {
SortedMap<String, String> sortedMap = new TreeMap<>(params);
StringBuilder toSign = new StringBuilder();
for (String key : sortedMap.keySet()) {
String value = params.get(key);
if (StringUtils.isNotEmpty(value) && !"sign".equals(key) && !"key".equals(key)) {
toSign.append(key.toLowerCase()).append("=").append(value).append("&");
}
}
toSign.append("key=").append(signKey);
return DigestUtils.md5Hex(toSign.toString()).toUpperCase();
}
/**
* 校验签名
* @param params
* @param privateKey
* @return
*/
public static Boolean verify(Map<String, String> params, String privateKey) {
String sign = sign(params, privateKey);
return sign.equals(params.get("sign"));
}
} |
SortedMap<String, String> sortedMap = new TreeMap<>(params);
StringBuilder toSign = new StringBuilder();
for (String key : sortedMap.keySet()) {
String value = params.get(key);
if (StringUtils.isNotEmpty(value) && !"sign".equals(key) && !"key".equals(key)) {
toSign.append(key).append("=").append(value).append("&");
}
}
toSign.append("key=").append(signKey);
return DigestUtils.md5Hex(toSign.toString()).toUpperCase();
| 407 | 157 | 564 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/alipay/AlipayAppServiceImpl.java | AlipayAppServiceImpl | pay | class AlipayAppServiceImpl extends AliPayServiceImpl {
private final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN)
.addConverterFactory(GsonConverterFactory.create(
//下划线驼峰互转
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
))
.client(new OkHttpClient.Builder()
.addInterceptor((new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)))
.followRedirects(false) //禁制OkHttp的重定向操作,我们自己处理重定向
.followSslRedirects(false)
.build()
)
.build();
private final Retrofit devRetrofit = new Retrofit.Builder()
.baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV)
.addConverterFactory(GsonConverterFactory.create(
//下划线驼峰互转
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
))
.client(new OkHttpClient.Builder()
.addInterceptor((new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)))
.build()
)
.build();
@Override
public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>}
} |
AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest();
aliPayOrderQueryRequest.setMethod(AliPayConstants.ALIPAY_TRADE_APP_PAY);
aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId());
aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter));
aliPayOrderQueryRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());
AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent();
bizContent.setOutTradeNo(request.getOrderId());
bizContent.setTotalAmount(request.getOrderAmount());
bizContent.setSubject(request.getOrderName());
bizContent.setPassbackParams(request.getAttach());
aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*", ""));
String sign = AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey());
aliPayOrderQueryRequest.setSign(URLEncoder.encode(sign));
Map<String, String> stringStringMap = MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest);
String body = MapUtil.toUrl(stringStringMap);
PayResponse payResponse = new PayResponse();
payResponse.setBody(body);
return payResponse;
| 414 | 375 | 789 | <methods>public non-sealed void <init>() ,public com.lly835.bestpay.model.PayResponse asyncNotify(java.lang.String) ,public com.lly835.bestpay.model.CloseResponse close(com.lly835.bestpay.model.CloseRequest) ,public java.lang.String downloadBill(com.lly835.bestpay.model.DownloadBillRequest) ,public com.lly835.bestpay.model.PayResponse pay(com.lly835.bestpay.model.PayRequest) ,public com.lly835.bestpay.model.PayBankResponse payBank(com.lly835.bestpay.model.PayBankRequest) ,public com.lly835.bestpay.model.OrderQueryResponse query(com.lly835.bestpay.model.OrderQueryRequest) ,public com.lly835.bestpay.model.RefundResponse refund(com.lly835.bestpay.model.RefundRequest) ,public void setAliPayConfig(com.lly835.bestpay.config.AliPayConfig) ,public boolean verify(Map<java.lang.String,java.lang.String>, com.lly835.bestpay.config.SignType, java.lang.String) <variables>protected com.lly835.bestpay.config.AliPayConfig aliPayConfig,private retrofit2.Retrofit devRetrofit,protected static final java.time.format.DateTimeFormatter formatter,private retrofit2.Retrofit retrofit |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/alipay/AlipayBarCodeServiceImpl.java | AlipayBarCodeServiceImpl | pay | class AlipayBarCodeServiceImpl extends AliPayServiceImpl {
private final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN)
.addConverterFactory(GsonConverterFactory.create(
//下划线驼峰互转
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
))
.client(new OkHttpClient.Builder()
.addInterceptor((new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)))
.build()
)
.build();
private final Retrofit devRetrofit = new Retrofit.Builder()
.baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV)
.addConverterFactory(GsonConverterFactory.create(
//下划线驼峰互转
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
))
.client(new OkHttpClient.Builder()
.addInterceptor((new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)))
.build()
)
.build();
@Override
public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>}
} |
AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest();
aliPayOrderQueryRequest.setMethod(AliPayConstants.ALIPAY_TRADE_BARCODE_PAY);
aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId());
aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter));
aliPayOrderQueryRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());
AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent();
bizContent.setOutTradeNo(request.getOrderId());
bizContent.setTotalAmount(request.getOrderAmount());
bizContent.setSubject(request.getOrderName());
bizContent.setAuthCode(request.getAuthCode());
bizContent.setIsAsyncPay(true);
aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*", ""));
aliPayOrderQueryRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey()));
Call<AliPayOrderCreateResponse> call;
if (aliPayConfig.isSandbox()) {
call = devRetrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest)));
} else {
call = retrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest)));
}
Response<AliPayOrderCreateResponse> retrofitResponse = null;
try {
retrofitResponse = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
assert retrofitResponse != null;
if (!retrofitResponse.isSuccessful()) {
throw new RuntimeException("【支付宝创建订单】网络异常. alipay.trade.pay");
}
assert retrofitResponse.body() != null;
AliPayOrderCreateResponse.AlipayTradeCreateResponse response = retrofitResponse.body().getAlipayTradePayResponse();
if (!response.getCode().equals(AliPayConstants.RESPONSE_CODE_SUCCESS)) {
throw new RuntimeException("【支付宝创建订单】alipay.trade.pay. code=" + response.getCode() + ", returnMsg=" + response.getMsg() + String.format("|%s|%s", response.getSubCode(), response.getSubMsg()));
}
PayResponse payResponse = new PayResponse();
payResponse.setOutTradeNo(response.getTradeNo());
payResponse.setOrderId(response.getOutTradeNo());
return payResponse;
| 375 | 709 | 1,084 | <methods>public non-sealed void <init>() ,public com.lly835.bestpay.model.PayResponse asyncNotify(java.lang.String) ,public com.lly835.bestpay.model.CloseResponse close(com.lly835.bestpay.model.CloseRequest) ,public java.lang.String downloadBill(com.lly835.bestpay.model.DownloadBillRequest) ,public com.lly835.bestpay.model.PayResponse pay(com.lly835.bestpay.model.PayRequest) ,public com.lly835.bestpay.model.PayBankResponse payBank(com.lly835.bestpay.model.PayBankRequest) ,public com.lly835.bestpay.model.OrderQueryResponse query(com.lly835.bestpay.model.OrderQueryRequest) ,public com.lly835.bestpay.model.RefundResponse refund(com.lly835.bestpay.model.RefundRequest) ,public void setAliPayConfig(com.lly835.bestpay.config.AliPayConfig) ,public boolean verify(Map<java.lang.String,java.lang.String>, com.lly835.bestpay.config.SignType, java.lang.String) <variables>protected com.lly835.bestpay.config.AliPayConfig aliPayConfig,private retrofit2.Retrofit devRetrofit,protected static final java.time.format.DateTimeFormatter formatter,private retrofit2.Retrofit retrofit |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/alipay/AlipayH5ServiceImpl.java | AlipayH5ServiceImpl | pay | class AlipayH5ServiceImpl extends AliPayServiceImpl {
private Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN)
.addConverterFactory(GsonConverterFactory.create(
//下划线驼峰互转
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
))
.client(new OkHttpClient.Builder()
.addInterceptor((new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)))
.build()
)
.build();
@Override
public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>}
} |
AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest();
aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId());
aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter));
AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent();
bizContent.setOutTradeNo(request.getOrderId());
bizContent.setTotalAmount(request.getOrderAmount());
bizContent.setSubject(request.getOrderName());
bizContent.setBuyerLogonId(request.getBuyerLogonId());
bizContent.setBuyerId(request.getBuyerId());
bizContent.setPassbackParams(request.getAttach());
//必须传一个
if (StringUtil.isEmpty(bizContent.getBuyerId())
&& StringUtil.isEmpty(bizContent.getBuyerLogonId())) {
throw new RuntimeException("alipay.trade.create: buyer_logon_id 和 buyer_id不能同时为空");
}
aliPayOrderQueryRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());
aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*",""));
aliPayOrderQueryRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey()));
Call<AliPayOrderCreateResponse> call = retrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest)));
Response<AliPayOrderCreateResponse> retrofitResponse = null;
try{
retrofitResponse = call.execute();
}catch (IOException e) {
e.printStackTrace();
}
assert retrofitResponse != null;
if (!retrofitResponse.isSuccessful()) {
throw new RuntimeException("【支付宝创建订单】网络异常. alipay.trade.create");
}
assert retrofitResponse.body() != null;
AliPayOrderCreateResponse.AlipayTradeCreateResponse response = retrofitResponse.body().getAlipayTradeCreateResponse();
if(!response.getCode().equals(AliPayConstants.RESPONSE_CODE_SUCCESS)) {
throw new RuntimeException("【支付宝创建订单】alipay.trade.create. code=" + response.getCode() + ", returnMsg=" + response.getMsg() + String.format("|%s|%s", response.getSubCode(), response.getSubMsg()));
}
PayResponse payResponse = new PayResponse();
payResponse.setOutTradeNo(response.getTradeNo());
payResponse.setOrderId(response.getOutTradeNo());
return payResponse;
| 206 | 750 | 956 | <methods>public non-sealed void <init>() ,public com.lly835.bestpay.model.PayResponse asyncNotify(java.lang.String) ,public com.lly835.bestpay.model.CloseResponse close(com.lly835.bestpay.model.CloseRequest) ,public java.lang.String downloadBill(com.lly835.bestpay.model.DownloadBillRequest) ,public com.lly835.bestpay.model.PayResponse pay(com.lly835.bestpay.model.PayRequest) ,public com.lly835.bestpay.model.PayBankResponse payBank(com.lly835.bestpay.model.PayBankRequest) ,public com.lly835.bestpay.model.OrderQueryResponse query(com.lly835.bestpay.model.OrderQueryRequest) ,public com.lly835.bestpay.model.RefundResponse refund(com.lly835.bestpay.model.RefundRequest) ,public void setAliPayConfig(com.lly835.bestpay.config.AliPayConfig) ,public boolean verify(Map<java.lang.String,java.lang.String>, com.lly835.bestpay.config.SignType, java.lang.String) <variables>protected com.lly835.bestpay.config.AliPayConfig aliPayConfig,private retrofit2.Retrofit devRetrofit,protected static final java.time.format.DateTimeFormatter formatter,private retrofit2.Retrofit retrofit |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/alipay/AlipayQRCodeServiceImpl.java | AlipayQRCodeServiceImpl | pay | class AlipayQRCodeServiceImpl extends AliPayServiceImpl {
private final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN)
.addConverterFactory(GsonConverterFactory.create(
//下划线驼峰互转
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
))
.client(new OkHttpClient.Builder()
.addInterceptor((new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)))
.build()
)
.build();
private final Retrofit devRetrofit = new Retrofit.Builder()
.baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV)
.addConverterFactory(GsonConverterFactory.create(
//下划线驼峰互转
new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
))
.client(new OkHttpClient.Builder()
.addInterceptor((new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)))
.build()
)
.build();
@Override
public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>}
} |
AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest();
aliPayOrderQueryRequest.setMethod(AliPayConstants.ALIPAY_TRADE_QRCODE_PAY);
aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId());
aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter));
aliPayOrderQueryRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());
AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent();
bizContent.setOutTradeNo(request.getOrderId());
bizContent.setTotalAmount(request.getOrderAmount());
bizContent.setSubject(request.getOrderName());
aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*", ""));
aliPayOrderQueryRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey()));
Call<AliPayOrderCreateResponse> call;
if (aliPayConfig.isSandbox()) {
call = devRetrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest)));
} else {
call = retrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest)));
}
Response<AliPayOrderCreateResponse> retrofitResponse = null;
try {
retrofitResponse = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
assert retrofitResponse != null;
if (!retrofitResponse.isSuccessful()) {
throw new RuntimeException("【支付宝创建订单】网络异常. alipay.trade.precreate");
}
assert retrofitResponse.body() != null;
AliPayOrderCreateResponse.AlipayTradeCreateResponse response = retrofitResponse.body().getAlipayTradePrecreateResponse();
if (!response.getCode().equals(AliPayConstants.RESPONSE_CODE_SUCCESS)) {
throw new RuntimeException("【支付宝创建订单】alipay.trade.precreate. code=" + response.getCode() + ", returnMsg=" + response.getMsg() + String.format("|%s|%s", response.getSubCode(), response.getSubMsg()));
}
PayResponse payResponse = new PayResponse();
payResponse.setOutTradeNo(response.getTradeNo());
payResponse.setOrderId(response.getOutTradeNo());
payResponse.setCodeUrl(response.getQrCode());
return payResponse;
| 376 | 700 | 1,076 | <methods>public non-sealed void <init>() ,public com.lly835.bestpay.model.PayResponse asyncNotify(java.lang.String) ,public com.lly835.bestpay.model.CloseResponse close(com.lly835.bestpay.model.CloseRequest) ,public java.lang.String downloadBill(com.lly835.bestpay.model.DownloadBillRequest) ,public com.lly835.bestpay.model.PayResponse pay(com.lly835.bestpay.model.PayRequest) ,public com.lly835.bestpay.model.PayBankResponse payBank(com.lly835.bestpay.model.PayBankRequest) ,public com.lly835.bestpay.model.OrderQueryResponse query(com.lly835.bestpay.model.OrderQueryRequest) ,public com.lly835.bestpay.model.RefundResponse refund(com.lly835.bestpay.model.RefundRequest) ,public void setAliPayConfig(com.lly835.bestpay.config.AliPayConfig) ,public boolean verify(Map<java.lang.String,java.lang.String>, com.lly835.bestpay.config.SignType, java.lang.String) <variables>protected com.lly835.bestpay.config.AliPayConfig aliPayConfig,private retrofit2.Retrofit devRetrofit,protected static final java.time.format.DateTimeFormatter formatter,private retrofit2.Retrofit retrofit |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/wx/WxPayMicroServiceImpl.java | WxPayMicroServiceImpl | pay | class WxPayMicroServiceImpl extends WxPayServiceImpl {
/**
* 微信付款码支付
* 提交支付请求后微信会同步返回支付结果。
* 当返回结果为“系统错误 {@link WxPayConstants#SYSTEMERROR}”时,商户系统等待5秒后调用【查询订单API {@link WxPayServiceImpl#query(OrderQueryRequest)}】,查询支付实际交易结果;
* 当返回结果为“正在支付 {@link WxPayConstants#USERPAYING}”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议30秒);
*
* @param request
* @return
*/
@Override
public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>}
} |
WxPayUnifiedorderRequest wxRequest = new WxPayUnifiedorderRequest();
wxRequest.setOutTradeNo(request.getOrderId());
wxRequest.setTotalFee(MoneyUtil.Yuan2Fen(request.getOrderAmount()));
wxRequest.setBody(request.getOrderName());
wxRequest.setOpenid(request.getOpenid());
wxRequest.setAuthCode(request.getAuthCode());
wxRequest.setAppid(wxPayConfig.getAppId());
wxRequest.setMchId(wxPayConfig.getMchId());
wxRequest.setNonceStr(RandomUtil.getRandomStr());
wxRequest.setSpbillCreateIp(StringUtils.isEmpty(request.getSpbillCreateIp()) ? "8.8.8.8" : request.getSpbillCreateIp());
wxRequest.setAttach(request.getAttach());
wxRequest.setSign(WxPaySignature.sign(MapUtil.buildMap(wxRequest), wxPayConfig.getMchKey()));
//对付款码支付无用的字段
wxRequest.setNotifyUrl("");
wxRequest.setTradeType("");
RequestBody body = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), XmlUtil.toString(wxRequest));
WxPayApi api = null;
if (wxPayConfig.isSandbox()) {
api = devRetrofit.create(WxPayApi.class);
} else {
api = retrofit.create(WxPayApi.class);
}
Call<WxPaySyncResponse> call = api.micropay(body);
Response<WxPaySyncResponse> retrofitResponse = null;
try {
retrofitResponse = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
assert retrofitResponse != null;
if (!retrofitResponse.isSuccessful()) {
throw new RuntimeException("【微信付款码支付】发起支付, 网络异常");
}
return buildPayResponse(retrofitResponse.body());
| 218 | 535 | 753 | <methods>public non-sealed void <init>() ,public com.lly835.bestpay.model.PayResponse asyncNotify(java.lang.String) ,public java.lang.String downloadBill(com.lly835.bestpay.model.DownloadBillRequest) ,public java.lang.String getQrCodeUrl(java.lang.String) ,public com.lly835.bestpay.model.PayResponse pay(com.lly835.bestpay.model.PayRequest) ,public com.lly835.bestpay.model.PayBankResponse payBank(com.lly835.bestpay.model.PayBankRequest) ,public com.lly835.bestpay.model.OrderQueryResponse query(com.lly835.bestpay.model.OrderQueryRequest) ,public com.lly835.bestpay.model.RefundResponse refund(com.lly835.bestpay.model.RefundRequest) ,public void setWxPayConfig(com.lly835.bestpay.config.WxPayConfig) ,public com.lly835.bestpay.model.PayResponse syncNotify(javax.servlet.http.HttpServletRequest) ,public boolean verify(Map#RAW, com.lly835.bestpay.config.SignType, java.lang.String) <variables>protected final retrofit2.Retrofit devRetrofit,protected final retrofit2.Retrofit retrofit,protected com.lly835.bestpay.config.WxPayConfig wxPayConfig |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/CamelCaseUtil.java | CamelCaseUtil | toUnderlineName | class CamelCaseUtil {
private static final char SEPARATOR = '_';
public static String toUnderlineName(String s) {<FILL_FUNCTION_BODY>}
/**
* 小驼峰
*/
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* 大驼峰
*/
public static String toCapitalizeCamelCase(String s) {
if (null == s) {
return null;
}
s = toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
} |
if (null == s) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean nextUpperCase = true;
if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}
if ((i >= 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
if (i > 0) sb.append(SEPARATOR);
}
upperCase = true;
} else {
upperCase = false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
| 327 | 219 | 546 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/HttpRequestUtil.java | HttpRequestUtil | post | class HttpRequestUtil {
private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class); //日志记录
/**
* post请求
* @param url url地址
* @param jsonParam 参数
* @return
*/
public static String post(String url,String jsonParam){<FILL_FUNCTION_BODY>}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static String get(String url){
String responseString = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
return EntityUtils.toString(response.getEntity());
/**把json字符串转换成json对象**/
} else {
logger.error("get请求提交失败:" + url);
}
} catch (IOException e) {
logger.error("get请求提交失败:" + url, e);
}
return responseString;
}
} |
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
String jsonResult = null;
HttpPost method = new HttpPost(url);
try {
if (null != jsonParam) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
String str = "";
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity());
return str;
/**把json字符串转换成json对象**/
// jsonResult = JSONObject.fromObject(str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
}
return jsonResult;
| 339 | 332 | 671 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/JsonUtil.java | JsonUtil | toObject | class JsonUtil {
private static final ObjectMapper mapper = new ObjectMapper();
private static GsonBuilder gsonBuilder = new GsonBuilder();
/**
* Convert target object to json string.
*
* @param obj target object.
* @return converted json string.
*/
public static String toJson(Object obj) {
gsonBuilder.setPrettyPrinting();
return gsonBuilder.create().toJson(obj);
}
public static String toJsonWithUnderscores(Object obj) {
gsonBuilder.setPrettyPrinting();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create().toJson(obj);
}
/**
* Convert json string to target object.
*
* @param json json string.
* @param valueType target object class type.
* @param <T> target class type.
* @return converted target object.
*/
public static <T> T toObject(String json, Class<T> valueType) {<FILL_FUNCTION_BODY>}
} |
Objects.requireNonNull(json, "json is null.");
Objects.requireNonNull(valueType, "value type is null.");
try {
return mapper.readValue(json, valueType);
} catch (IOException e) {
throw new IllegalStateException("fail to convert [" + json + "] to [" + valueType + "].", e);
}
| 295 | 96 | 391 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/NameValuePairUtil.java | NameValuePairUtil | convert | class NameValuePairUtil {
/**
* 将Map转换为List<{@link NameValuePair}>.
*
* @param map
* @return
*/
public static List<NameValuePair> convert(Map<String, String> map) {<FILL_FUNCTION_BODY>}
} |
List<NameValuePair> nameValuePairs = new ArrayList<>();
map.forEach((key, value) -> {
nameValuePairs.add(new BasicNameValuePair(key, value));
});
return nameValuePairs;
| 85 | 64 | 149 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/RandomUtil.java | RandomUtil | getRandomStr | class RandomUtil {
private static final String RANDOM_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final java.util.Random RANDOM = new java.util.Random();
public static String getRandomStr() {<FILL_FUNCTION_BODY>}
} |
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 16; i++) {
sb.append(RANDOM_STR.charAt(RANDOM.nextInt(RANDOM_STR.length())));
}
return sb.toString();
| 109 | 72 | 181 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/ServletRequestUtils.java | ServletRequestUtils | getParameterMap | class ServletRequestUtils {
public static TreeMap<String, String> getParameterMap(ServletRequest request) {<FILL_FUNCTION_BODY>}
} |
Objects.requireNonNull(request, "request is null.");
TreeMap<String, String> map = new TreeMap<>();
Enumeration enu = request.getParameterNames();
while (enu.hasMoreElements()) {
String paraName = (String) enu.nextElement();
map.put(paraName, request.getParameter(paraName));
}
return map;
| 43 | 101 | 144 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/StreamUtil.java | StreamUtil | io | class StreamUtil {
private static final int DEFAULT_BUFFER_SIZE = 8192;
public static void io(InputStream in, OutputStream out) throws IOException {
io(in, out, -1);
}
public static void io(InputStream in, OutputStream out, int bufferSize) throws IOException {
if (bufferSize == -1) {
bufferSize = DEFAULT_BUFFER_SIZE;
}
byte[] buffer = new byte[bufferSize];
int amount;
while ((amount = in.read(buffer)) >= 0) {
out.write(buffer, 0, amount);
}
}
public static void io(Reader in, Writer out) throws IOException {
io(in, out, -1);
}
public static void io(Reader in, Writer out, int bufferSize) throws IOException {<FILL_FUNCTION_BODY>}
public static OutputStream synchronizedOutputStream(OutputStream out) {
return new SynchronizedOutputStream(out);
}
public static OutputStream synchronizedOutputStream(OutputStream out, Object lock) {
return new SynchronizedOutputStream(out, lock);
}
public static String readText(InputStream in) throws IOException {
return readText(in, null, -1);
}
public static String readText(InputStream in, String encoding) throws IOException {
return readText(in, encoding, -1);
}
public static String readText(InputStream in, String encoding, int bufferSize)
throws IOException {
Reader reader = (encoding == null) ? new InputStreamReader(in) : new InputStreamReader(in,
encoding);
return readText(reader, bufferSize);
}
public static String readText(Reader reader) throws IOException {
return readText(reader, -1);
}
public static String readText(Reader reader, int bufferSize) throws IOException {
StringWriter writer = new StringWriter();
io(reader, writer, bufferSize);
return writer.toString();
}
private static class SynchronizedOutputStream extends OutputStream {
private OutputStream out;
private Object lock;
SynchronizedOutputStream(OutputStream out) {
this(out, out);
}
SynchronizedOutputStream(OutputStream out, Object lock) {
this.out = out;
this.lock = lock;
}
public void write(int datum) throws IOException {
synchronized (lock) {
out.write(datum);
}
}
public void write(byte[] data) throws IOException {
synchronized (lock) {
out.write(data);
}
}
public void write(byte[] data, int offset, int length) throws IOException {
synchronized (lock) {
out.write(data, offset, length);
}
}
public void flush() throws IOException {
synchronized (lock) {
out.flush();
}
}
public void close() throws IOException {
synchronized (lock) {
out.close();
}
}
}
} |
if (bufferSize == -1) {
bufferSize = DEFAULT_BUFFER_SIZE >> 1;
}
char[] buffer = new char[bufferSize];
int amount;
while ((amount = in.read(buffer)) >= 0) {
out.write(buffer, 0, amount);
}
| 769 | 83 | 852 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/StringUtil.java | StringUtil | isEmpty | class StringUtil {
public static boolean areNotEmpty(String... values) {
boolean result = true;
if (values != null && values.length != 0) {
String[] var2 = values;
int var3 = values.length;
for(int var4 = 0; var4 < var3; ++var4) {
String value = var2[var4];
result &= !isEmpty(value);
}
} else {
result = false;
}
return result;
}
public static boolean isEmpty(String value) {<FILL_FUNCTION_BODY>}
} |
int strLen;
if (value != null && (strLen = value.length()) != 0) {
for(int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(value.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
| 160 | 98 | 258 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/WebUtil.java | WebUtil | buildForm | class WebUtil {
public static String buildForm(String baseUrl,Map<String, String> parameters) {<FILL_FUNCTION_BODY>}
private static String buildHiddenFields(Map<String, String> parameters) {
if (parameters != null && !parameters.isEmpty()) {
StringBuffer sb = new StringBuffer();
Set<String> keys = parameters.keySet();
Iterator var3 = keys.iterator();
while(var3.hasNext()) {
String key = (String)var3.next();
String value = (String)parameters.get(key);
if (key != null && value != null) {
sb.append(buildHiddenField(key, value));
}
}
String result = sb.toString();
return result;
} else {
return "";
}
}
private static String buildHiddenField(String key, String value) {
StringBuffer sb = new StringBuffer();
sb.append("<input type=\"hidden\" name=\"");
sb.append(key);
sb.append("\" value=\"");
String a = value.replace("\"", """);
sb.append(a).append("\">\n");
return sb.toString();
}
public static String buildQuery(Map<String, String> params, String charset) throws IOException {
if (params != null && !params.isEmpty()) {
StringBuilder query = new StringBuilder();
Set<Map.Entry<String, String>> entries = params.entrySet();
boolean hasParam = false;
Iterator var5 = entries.iterator();
while(var5.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry)var5.next();
String name = entry.getKey();
String value = entry.getValue();
if (StringUtil.areNotEmpty(new String[]{name, value})) {
if (hasParam) {
query.append("&");
} else {
hasParam = true;
}
query.append(name).append("=").append(URLEncoder.encode(value, charset));
}
}
return query.toString();
} else {
return null;
}
}
public static String getRequestUrl(Map<String,String> parameters,Boolean isSandbox) {
StringBuffer urlSb;
if(isSandbox)
urlSb = new StringBuffer(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV);
else
urlSb = new StringBuffer(AliPayConstants.ALIPAY_GATEWAY_OPEN);
urlSb.append("/gateway.do");
try {
String charset = null != parameters.get("charset") ? parameters.get("charset") : "utf-8";
String sysMustQuery = WebUtil.buildQuery(parameters, charset);
urlSb.append("?");
urlSb.append(sysMustQuery);
} catch (IOException e) {
e.printStackTrace();
}
return urlSb.toString();
}
} |
StringBuffer sb = new StringBuffer();
sb.append("<form id='bestPayForm' name=\"punchout_form\" method=\"post\" action=\"");
sb.append(baseUrl);
sb.append("\">\n");
sb.append(buildHiddenFields(parameters));
sb.append("<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >\n");
sb.append("</form>\n");
sb.append("<script>document.getElementById('bestPayForm').submit();</script>");
String form = sb.toString();
return form;
| 782 | 160 | 942 | <no_super_class> |
Pay-Group_best-pay-sdk | best-pay-sdk/src/main/java/com/lly835/bestpay/utils/XmlUtil.java | XmlUtil | toMap | class XmlUtil {
/**
* xml转对象
* @param xml
* @param objClass
* @return
*/
public static Object toObject(String xml, Class objClass) {
Serializer serializer = new Persister();
try {
return serializer.read(objClass, xml);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* xml 转 字符
* @param obj
* @return
*/
public static String toString(Object obj) {
Serializer serializer = new Persister();
StringWriter output = new StringWriter();
try {
serializer.write(obj, output);
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
/**
* xml 转 map
*
* @param strXML XML字符串
* @return XML数据转换后的Map
* @throws Exception
*/
public static Map<String, String> toMap(String strXML) {<FILL_FUNCTION_BODY>}
} |
try {
Map<String, String> data = new HashMap<>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
try {
stream.close();
} catch (Exception ex) {
// do nothing
}
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
| 294 | 280 | 574 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/AbstractFrontendMojo.java | AbstractFrontendMojo | execute | class AbstractFrontendMojo extends AbstractMojo {
@Component
protected MojoExecution execution;
/**
* Whether you should skip while running in the test phase (default is false)
*/
@Parameter(property = "skipTests", required = false, defaultValue = "false")
protected Boolean skipTests;
/**
* Set this to true to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on
* occasion.
*
* @since 1.4
*/
@Parameter(property = "maven.test.failure.ignore", defaultValue = "false")
protected boolean testFailureIgnore;
/**
* The base directory for running all Node commands. (Usually the directory that contains package.json)
*/
@Parameter(defaultValue = "${basedir}", property = "workingDirectory", required = false)
protected File workingDirectory;
/**
* The base directory for installing node and npm.
*/
@Parameter(property = "installDirectory", required = false)
protected File installDirectory;
/**
* Additional environment variables to pass to the build.
*/
@Parameter
protected Map<String, String> environmentVariables;
@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject project;
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repositorySystemSession;
/**
* Determines if this execution should be skipped.
*/
private boolean skipTestPhase() {
return skipTests && isTestingPhase();
}
/**
* Determines if the current execution is during a testing phase (e.g., "test" or "integration-test").
*/
private boolean isTestingPhase() {
String phase = execution.getLifecyclePhase();
return "test".equals(phase) || "integration-test".equals(phase);
}
protected abstract void execute(FrontendPluginFactory factory) throws FrontendException;
/**
* Implemented by children to determine if this execution should be skipped.
*/
protected abstract boolean skipExecution();
@Override
public void execute() throws MojoFailureException {<FILL_FUNCTION_BODY>}
} |
if (testFailureIgnore && !isTestingPhase()) {
getLog().info("testFailureIgnore property is ignored in non test phases");
}
if (!(skipTestPhase() || skipExecution())) {
if (installDirectory == null) {
installDirectory = workingDirectory;
}
try {
execute(new FrontendPluginFactory(workingDirectory, installDirectory,
new RepositoryCacheResolver(repositorySystemSession)));
} catch (TaskRunnerException e) {
if (testFailureIgnore && isTestingPhase()) {
getLog().error("There are test failures.\nFailed to run task: " + e.getMessage(), e);
} else {
throw new MojoFailureException("Failed to run task", e);
}
} catch (FrontendException e) {
throw MojoUtils.toMojoFailureException(e);
}
} else {
getLog().info("Skipping execution.");
}
| 576 | 233 | 809 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/BowerMojo.java | BowerMojo | getProxyConfig | class BowerMojo extends AbstractFrontendMojo {
/**
* Bower arguments. Default is "install".
*/
@Parameter(defaultValue = "install", property = "frontend.bower.arguments", required = false)
private String arguments;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.bower", defaultValue = "${skip.bower}")
private boolean skip;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
@Parameter(property = "frontend.bower.bowerInheritsProxyConfigFromMaven", required = false, defaultValue = "true")
private boolean bowerInheritsProxyConfigFromMaven;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
protected synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
ProxyConfig proxyConfig = getProxyConfig();
factory.getBowerRunner(proxyConfig).execute(arguments, environmentVariables);
}
private ProxyConfig getProxyConfig() {<FILL_FUNCTION_BODY>}
} |
if (bowerInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(session, decrypter);
} else {
getLog().info("bower not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
| 336 | 83 | 419 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/BunMojo.java | BunMojo | getProxyConfig | class BunMojo extends AbstractFrontendMojo {
private static final String NPM_REGISTRY_URL = "npmRegistryURL";
/**
* bun arguments. Default is "install".
*/
@Parameter(defaultValue = "", property = "frontend.bun.arguments", required = false)
private String arguments;
@Parameter(property = "frontend.bun.bunInheritsProxyConfigFromMaven", required = false,
defaultValue = "true")
private boolean bunInheritsProxyConfigFromMaven;
/**
* Registry override, passed as the registry option during npm install if set.
*/
@Parameter(property = NPM_REGISTRY_URL, required = false, defaultValue = "")
private String npmRegistryURL;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
@Component
private BuildContext buildContext;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.bun", defaultValue = "${skip.bun}")
private boolean skip;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
File packageJson = new File(this.workingDirectory, "package.json");
if (this.buildContext == null || this.buildContext.hasDelta(packageJson)
|| !this.buildContext.isIncremental()) {
ProxyConfig proxyConfig = getProxyConfig();
factory.getBunRunner(proxyConfig, getRegistryUrl()).execute(this.arguments,
this.environmentVariables);
} else {
getLog().info("Skipping bun install as package.json unchanged");
}
}
private ProxyConfig getProxyConfig() {<FILL_FUNCTION_BODY>}
private String getRegistryUrl() {
// check to see if overridden via `-D`, otherwise fallback to pom value
return System.getProperty(NPM_REGISTRY_URL, this.npmRegistryURL);
}
} |
if (this.bunInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(this.session, this.decrypter);
} else {
getLog().info("bun not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
| 584 | 89 | 673 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/EmberMojo.java | EmberMojo | shouldExecute | class EmberMojo extends AbstractFrontendMojo {
/**
* Grunt arguments. Default is empty (runs just the "grunt" command).
*/
@Parameter(property = "frontend.ember.arguments")
private String arguments;
/**
* Files that should be checked for changes, in addition to the srcdir files.
* {@link #workingDirectory}.
*/
@Parameter(property = "triggerfiles")
private List<File> triggerfiles;
/**
* The directory containing front end files that will be processed by grunt.
* If this is set then files in the directory will be checked for
* modifications before running grunt.
*/
@Parameter(property = "srcdir")
private File srcdir;
/**
* The directory where front end files will be output by grunt. If this is
* set then they will be refreshed so they correctly show as modified in
* Eclipse.
*/
@Parameter(property = "outputdir")
private File outputdir;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.ember", defaultValue = "${skip.ember}")
private boolean skip;
@Component
private BuildContext buildContext;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
if (shouldExecute()) {
factory.getEmberRunner().execute(arguments, environmentVariables);
if (outputdir != null) {
getLog().info("Refreshing files after ember: " + outputdir);
buildContext.refresh(outputdir);
}
} else {
getLog().info("Skipping ember as no modified files in " + srcdir);
}
}
private boolean shouldExecute() {<FILL_FUNCTION_BODY>}
} |
if (triggerfiles == null || triggerfiles.isEmpty()) {
triggerfiles = Arrays.asList(new File(workingDirectory, "Gruntfile.js"));
}
return MojoUtils.shouldExecute(buildContext, triggerfiles, srcdir);
| 495 | 68 | 563 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/GruntMojo.java | GruntMojo | shouldExecute | class GruntMojo extends AbstractFrontendMojo {
/**
* Grunt arguments. Default is empty (runs just the "grunt" command).
*/
@Parameter(property = "frontend.grunt.arguments")
private String arguments;
/**
* Files that should be checked for changes, in addition to the srcdir files.
* Defaults to Gruntfile.js in the {@link #workingDirectory}.
*/
@Parameter(property = "triggerfiles")
private List<File> triggerfiles;
/**
* The directory containing front end files that will be processed by grunt.
* If this is set then files in the directory will be checked for
* modifications before running grunt.
*/
@Parameter(property = "srcdir")
private File srcdir;
/**
* The directory where front end files will be output by grunt. If this is
* set then they will be refreshed so they correctly show as modified in
* Eclipse.
*/
@Parameter(property = "outputdir")
private File outputdir;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.grunt", defaultValue = "${skip.grunt}")
private boolean skip;
@Component
private BuildContext buildContext;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
if (shouldExecute()) {
factory.getGruntRunner().execute(arguments, environmentVariables);
if (outputdir != null) {
getLog().info("Refreshing files after grunt: " + outputdir);
buildContext.refresh(outputdir);
}
} else {
getLog().info("Skipping grunt as no modified files in " + srcdir);
}
}
private boolean shouldExecute() {<FILL_FUNCTION_BODY>}
} |
if (triggerfiles == null || triggerfiles.isEmpty()) {
triggerfiles = Arrays.asList(new File(workingDirectory, "Gruntfile.js"));
}
return MojoUtils.shouldExecute(buildContext, triggerfiles, srcdir);
| 508 | 67 | 575 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/GulpMojo.java | GulpMojo | shouldExecute | class GulpMojo extends AbstractFrontendMojo {
/**
* Gulp arguments. Default is empty (runs just the "gulp" command).
*/
@Parameter(property = "frontend.gulp.arguments")
private String arguments;
/**
* Files that should be checked for changes, in addition to the srcdir files.
* Defaults to gulpfile.js in the {@link #workingDirectory}.
*/
@Parameter(property = "triggerfiles")
private List<File> triggerfiles;
/**
* The directory containing front end files that will be processed by gulp.
* If this is set then files in the directory will be checked for
* modifications before running gulp.
*/
@Parameter(property = "srcdir")
private File srcdir;
/**
* The directory where front end files will be output by gulp. If this is
* set then they will be refreshed so they correctly show as modified in
* Eclipse.
*/
@Parameter(property = "outputdir")
private File outputdir;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.gulp", defaultValue = "${skip.gulp}")
private boolean skip;
@Component
private BuildContext buildContext;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
if (shouldExecute()) {
factory.getGulpRunner().execute(arguments, environmentVariables);
if (outputdir != null) {
getLog().info("Refreshing files after gulp: " + outputdir);
buildContext.refresh(outputdir);
}
} else {
getLog().info("Skipping gulp as no modified files in " + srcdir);
}
}
private boolean shouldExecute() {<FILL_FUNCTION_BODY>}
} |
if (triggerfiles == null || triggerfiles.isEmpty()) {
triggerfiles = Arrays.asList(new File(workingDirectory, "gulpfile.js"));
}
return MojoUtils.shouldExecute(buildContext, triggerfiles, srcdir);
| 508 | 67 | 575 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/InstallBunMojo.java | InstallBunMojo | execute | class InstallBunMojo extends AbstractFrontendMojo {
/**
* The version of Bun to install. IMPORTANT! Most Bun version names start with 'v', for example
* 'v1.0.0'
*/
@Parameter(property = "bunVersion", required = true)
private String bunVersion;
/**
* Server Id for download username and password
*/
@Parameter(property = "serverId", defaultValue = "")
private String serverId;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.installbun", alias = "skip.installbun", defaultValue = "${skip.installbun}")
private boolean skip;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public void execute(FrontendPluginFactory factory) throws InstallationException {<FILL_FUNCTION_BODY>}
} |
ProxyConfig proxyConfig = MojoUtils.getProxyConfig(this.session, this.decrypter);
Server server = MojoUtils.decryptServer(this.serverId, this.session, this.decrypter);
if (null != server) {
factory.getBunInstaller(proxyConfig).setBunVersion(this.bunVersion).setUserName(server.getUsername())
.setPassword(server.getPassword()).install();
} else {
factory.getBunInstaller(proxyConfig).setBunVersion(this.bunVersion).install();
}
| 307 | 150 | 457 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/InstallNodeAndNpmMojo.java | InstallNodeAndNpmMojo | getNodeDownloadRoot | class InstallNodeAndNpmMojo extends AbstractFrontendMojo {
/**
* Where to download Node.js binary from. Defaults to https://nodejs.org/dist/
*/
@Parameter(property = "nodeDownloadRoot", required = false)
private String nodeDownloadRoot;
/**
* Where to download NPM binary from. Defaults to https://registry.npmjs.org/npm/-/
*/
@Parameter(property = "npmDownloadRoot", required = false, defaultValue = NPMInstaller.DEFAULT_NPM_DOWNLOAD_ROOT)
private String npmDownloadRoot;
/**
* Where to download Node.js and NPM binaries from.
*
* @deprecated use {@link #nodeDownloadRoot} and {@link #npmDownloadRoot} instead, this configuration will be used only when no {@link #nodeDownloadRoot} or {@link #npmDownloadRoot} is specified.
*/
@Parameter(property = "downloadRoot", required = false, defaultValue = "")
@Deprecated
private String downloadRoot;
/**
* The version of Node.js to install. IMPORTANT! Most Node.js version names start with 'v', for example 'v0.10.18'
*/
@Parameter(property="nodeVersion", required = true)
private String nodeVersion;
/**
* The version of NPM to install.
*/
@Parameter(property = "npmVersion", required = false, defaultValue = "provided")
private String npmVersion;
/**
* Server Id for download username and password
*/
@Parameter(property = "serverId", defaultValue = "")
private String serverId;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.installnodenpm", defaultValue = "${skip.installnodenpm}")
private boolean skip;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public void execute(FrontendPluginFactory factory) throws InstallationException {
ProxyConfig proxyConfig = MojoUtils.getProxyConfig(session, decrypter);
String nodeDownloadRoot = getNodeDownloadRoot();
String npmDownloadRoot = getNpmDownloadRoot();
Server server = MojoUtils.decryptServer(serverId, session, decrypter);
if (null != server) {
factory.getNodeInstaller(proxyConfig)
.setNodeVersion(nodeVersion)
.setNodeDownloadRoot(nodeDownloadRoot)
.setNpmVersion(npmVersion)
.setUserName(server.getUsername())
.setPassword(server.getPassword())
.install();
factory.getNPMInstaller(proxyConfig)
.setNodeVersion(nodeVersion)
.setNpmVersion(npmVersion)
.setNpmDownloadRoot(npmDownloadRoot)
.setUserName(server.getUsername())
.setPassword(server.getPassword())
.install();
} else {
factory.getNodeInstaller(proxyConfig)
.setNodeVersion(nodeVersion)
.setNodeDownloadRoot(nodeDownloadRoot)
.setNpmVersion(npmVersion)
.install();
factory.getNPMInstaller(proxyConfig)
.setNodeVersion(this.nodeVersion)
.setNpmVersion(this.npmVersion)
.setNpmDownloadRoot(npmDownloadRoot)
.install();
}
}
private String getNodeDownloadRoot() {<FILL_FUNCTION_BODY>}
private String getNpmDownloadRoot() {
if (downloadRoot != null && !"".equals(downloadRoot) && NPMInstaller.DEFAULT_NPM_DOWNLOAD_ROOT.equals(npmDownloadRoot)) {
return downloadRoot;
}
return npmDownloadRoot;
}
} |
if (downloadRoot != null && !"".equals(downloadRoot) && nodeDownloadRoot == null) {
return downloadRoot;
}
return nodeDownloadRoot;
| 1,024 | 45 | 1,069 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/InstallNodeAndPnpmMojo.java | InstallNodeAndPnpmMojo | execute | class InstallNodeAndPnpmMojo extends AbstractFrontendMojo {
/**
* Where to download Node.js binary from. Defaults to https://nodejs.org/dist/
*/
@Parameter(property = "nodeDownloadRoot", required = false)
private String nodeDownloadRoot;
/**
* Where to download pnpm binary from. Defaults to https://registry.npmjs.org/pnpm/-/
*/
@Parameter(property = "pnpmDownloadRoot", required = false, defaultValue = PnpmInstaller.DEFAULT_PNPM_DOWNLOAD_ROOT)
private String pnpmDownloadRoot;
/**
* Where to download Node.js and pnpm binaries from.
*
* @deprecated use {@link #nodeDownloadRoot} and {@link #pnpmDownloadRoot} instead, this configuration will be used only when no {@link #nodeDownloadRoot} or {@link #pnpmDownloadRoot} is specified.
*/
@Parameter(property = "downloadRoot", required = false, defaultValue = "")
@Deprecated
private String downloadRoot;
/**
* The version of Node.js to install. IMPORTANT! Most Node.js version names start with 'v', for example 'v0.10.18'
*/
@Parameter(property="nodeVersion", required = true)
private String nodeVersion;
/**
* The version of pnpm to install. Note that the version string can optionally be prefixed with
* 'v' (i.e., both 'v1.2.3' and '1.2.3' are valid).
*/
@Parameter(property = "pnpmVersion", required = true)
private String pnpmVersion;
/**
* Server Id for download username and password
*/
@Parameter(property = "serverId", defaultValue = "")
private String serverId;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.installnodepnpm", defaultValue = "${skip.installnodepnpm}")
private boolean skip;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public void execute(FrontendPluginFactory factory) throws InstallationException {<FILL_FUNCTION_BODY>}
private String getNodeDownloadRoot() {
if (downloadRoot != null && !"".equals(downloadRoot) && nodeDownloadRoot == null) {
return downloadRoot;
}
return nodeDownloadRoot;
}
private String getPnpmDownloadRoot() {
if (downloadRoot != null && !"".equals(downloadRoot) && PnpmInstaller.DEFAULT_PNPM_DOWNLOAD_ROOT.equals(pnpmDownloadRoot)) {
return downloadRoot;
}
return pnpmDownloadRoot;
}
} |
ProxyConfig proxyConfig = MojoUtils.getProxyConfig(session, decrypter);
// Use different names to avoid confusion with fields `nodeDownloadRoot` and
// `pnpmDownloadRoot`.
//
// TODO: Remove the `downloadRoot` config (with breaking change) to simplify download root
// resolution.
String resolvedNodeDownloadRoot = getNodeDownloadRoot();
String resolvedPnpmDownloadRoot = getPnpmDownloadRoot();
Server server = MojoUtils.decryptServer(serverId, session, decrypter);
if (null != server) {
factory.getNodeInstaller(proxyConfig)
.setNodeVersion(nodeVersion)
.setNodeDownloadRoot(resolvedNodeDownloadRoot)
.setUserName(server.getUsername())
.setPassword(server.getPassword())
.install();
factory.getPnpmInstaller(proxyConfig)
.setPnpmVersion(pnpmVersion)
.setPnpmDownloadRoot(resolvedPnpmDownloadRoot)
.setUserName(server.getUsername())
.setPassword(server.getPassword())
.install();
} else {
factory.getNodeInstaller(proxyConfig)
.setNodeVersion(nodeVersion)
.setNodeDownloadRoot(resolvedNodeDownloadRoot)
.install();
factory.getPnpmInstaller(proxyConfig)
.setPnpmVersion(this.pnpmVersion)
.setPnpmDownloadRoot(resolvedPnpmDownloadRoot)
.install();
}
| 762 | 371 | 1,133 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/InstallNodeAndYarnMojo.java | InstallNodeAndYarnMojo | execute | class InstallNodeAndYarnMojo extends AbstractFrontendMojo {
private static final String YARNRC_YAML_FILE_NAME = ".yarnrc.yml";
/**
* Where to download Node.js binary from. Defaults to https://nodejs.org/dist/
*/
@Parameter(property = "nodeDownloadRoot", required = false)
private String nodeDownloadRoot;
/**
* Where to download Yarn binary from. Defaults to https://github.com/yarnpkg/yarn/releases/download/...
*/
@Parameter(property = "yarnDownloadRoot", required = false,
defaultValue = YarnInstaller.DEFAULT_YARN_DOWNLOAD_ROOT)
private String yarnDownloadRoot;
/**
* The version of Node.js to install. IMPORTANT! Most Node.js version names start with 'v', for example
* 'v0.10.18'
*/
@Parameter(property = "nodeVersion", required = true)
private String nodeVersion;
/**
* The version of Yarn to install. IMPORTANT! Most Yarn names start with 'v', for example 'v0.15.0'.
*/
@Parameter(property = "yarnVersion", required = true)
private String yarnVersion;
/**
* Server Id for download username and password
*/
@Parameter(property = "serverId", defaultValue = "")
private String serverId;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.installyarn", alias = "skip.installyarn", defaultValue = "${skip.installyarn}")
private boolean skip;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
@Override
protected boolean skipExecution() {
return this.skip;
}
/**
* Checks whether a .yarnrc.yml file exists at the project root (in multi-module builds, it will be the Reactor project)
*
* @return true if the .yarnrc.yml file exists, false otherwise
*/
private boolean isYarnrcYamlFilePresent() {
Stream<File> filesToCheck = Stream.of(
new File(session.getCurrentProject().getBasedir(), YARNRC_YAML_FILE_NAME),
new File(session.getRequest().getMultiModuleProjectDirectory(), YARNRC_YAML_FILE_NAME),
new File(session.getExecutionRootDirectory(), YARNRC_YAML_FILE_NAME)
);
return filesToCheck
.anyMatch(File::exists);
}
@Override
public void execute(FrontendPluginFactory factory) throws InstallationException {<FILL_FUNCTION_BODY>}
} |
ProxyConfig proxyConfig = MojoUtils.getProxyConfig(this.session, this.decrypter);
Server server = MojoUtils.decryptServer(this.serverId, this.session, this.decrypter);
if (null != server) {
factory.getNodeInstaller(proxyConfig).setNodeDownloadRoot(this.nodeDownloadRoot)
.setNodeVersion(this.nodeVersion).setPassword(server.getPassword())
.setUserName(server.getUsername()).install();
factory.getYarnInstaller(proxyConfig).setYarnDownloadRoot(this.yarnDownloadRoot)
.setYarnVersion(this.yarnVersion).setUserName(server.getUsername())
.setPassword(server.getPassword()).setIsYarnBerry(isYarnrcYamlFilePresent()).install();
} else {
factory.getNodeInstaller(proxyConfig).setNodeDownloadRoot(this.nodeDownloadRoot)
.setNodeVersion(this.nodeVersion).install();
factory.getYarnInstaller(proxyConfig).setYarnDownloadRoot(this.yarnDownloadRoot)
.setYarnVersion(this.yarnVersion).setIsYarnBerry(isYarnrcYamlFilePresent()).install();
}
| 741 | 309 | 1,050 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/MojoUtils.java | MojoUtils | shouldExecute | class MojoUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(MojoUtils.class);
static <E extends Throwable> MojoFailureException toMojoFailureException(E e) {
String causeMessage = e.getCause() != null ? ": " + e.getCause().getMessage() : "";
return new MojoFailureException(e.getMessage() + causeMessage, e);
}
static ProxyConfig getProxyConfig(MavenSession mavenSession, SettingsDecrypter decrypter) {
if (mavenSession == null ||
mavenSession.getSettings() == null ||
mavenSession.getSettings().getProxies() == null ||
mavenSession.getSettings().getProxies().isEmpty()) {
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
} else {
final List<Proxy> mavenProxies = mavenSession.getSettings().getProxies();
final List<ProxyConfig.Proxy> proxies = new ArrayList<ProxyConfig.Proxy>(mavenProxies.size());
for (Proxy mavenProxy : mavenProxies) {
if (mavenProxy.isActive()) {
mavenProxy = decryptProxy(mavenProxy, decrypter);
proxies.add(new ProxyConfig.Proxy(mavenProxy.getId(), mavenProxy.getProtocol(), mavenProxy.getHost(),
mavenProxy.getPort(), mavenProxy.getUsername(), mavenProxy.getPassword(), mavenProxy.getNonProxyHosts()));
}
}
LOGGER.info("Found proxies: {}", proxies);
return new ProxyConfig(proxies);
}
}
private static Proxy decryptProxy(Proxy proxy, SettingsDecrypter decrypter) {
synchronized (proxy) {
final DefaultSettingsDecryptionRequest decryptionRequest = new DefaultSettingsDecryptionRequest(proxy);
SettingsDecryptionResult decryptedResult = decrypter.decrypt(decryptionRequest);
return decryptedResult.getProxy();
}
}
static Server decryptServer(String serverId, MavenSession mavenSession, SettingsDecrypter decrypter) {
if (StringUtils.isEmpty(serverId)) {
return null;
}
Server server = mavenSession.getSettings().getServer(serverId);
if (server != null) {
synchronized (server) {
final DefaultSettingsDecryptionRequest decryptionRequest = new DefaultSettingsDecryptionRequest(server);
SettingsDecryptionResult decryptedResult = decrypter.decrypt(decryptionRequest);
return decryptedResult.getServer();
}
} else {
LOGGER.warn("Could not find server '" + serverId + "' in settings.xml");
return null;
}
}
static boolean shouldExecute(BuildContext buildContext, List<File> triggerfiles, File srcdir) {<FILL_FUNCTION_BODY>}
} |
// If there is no buildContext, or this is not an incremental build, always execute.
if (buildContext == null || !buildContext.isIncremental()) {
return true;
}
if (triggerfiles != null) {
for (File triggerfile : triggerfiles) {
if (buildContext.hasDelta(triggerfile)) {
return true;
}
}
}
if (srcdir == null) {
return true;
}
// Check for changes in the srcdir
Scanner scanner = buildContext.newScanner(srcdir);
scanner.scan();
String[] includedFiles = scanner.getIncludedFiles();
return (includedFiles != null && includedFiles.length > 0);
| 743 | 197 | 940 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/NpmMojo.java | NpmMojo | getProxyConfig | class NpmMojo extends AbstractFrontendMojo {
private static final String NPM_REGISTRY_URL = "npmRegistryURL";
/**
* npm arguments. Default is "install".
*/
@Parameter(defaultValue = "install", property = "frontend.npm.arguments", required = false)
private String arguments;
@Parameter(property = "frontend.npm.npmInheritsProxyConfigFromMaven", required = false, defaultValue = "true")
private boolean npmInheritsProxyConfigFromMaven;
/**
* Registry override, passed as the registry option during npm install if set.
*/
@Parameter(property = NPM_REGISTRY_URL, required = false, defaultValue = "")
private String npmRegistryURL;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
@Component
private BuildContext buildContext;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.npm", defaultValue = "${skip.npm}")
private boolean skip;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
File packageJson = new File(workingDirectory, "package.json");
if (buildContext == null || buildContext.hasDelta(packageJson) || !buildContext.isIncremental()) {
ProxyConfig proxyConfig = getProxyConfig();
factory.getNpmRunner(proxyConfig, getRegistryUrl()).execute(arguments, environmentVariables);
} else {
getLog().info("Skipping npm install as package.json unchanged");
}
}
private ProxyConfig getProxyConfig() {<FILL_FUNCTION_BODY>}
private String getRegistryUrl() {
// check to see if overridden via `-D`, otherwise fallback to pom value
return System.getProperty(NPM_REGISTRY_URL, npmRegistryURL);
}
} |
if (npmInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(session, decrypter);
} else {
getLog().info("npm not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
| 564 | 81 | 645 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/NpxMojo.java | NpxMojo | getProxyConfig | class NpxMojo extends AbstractFrontendMojo {
private static final String NPM_REGISTRY_URL = "npmRegistryURL";
/**
* npm arguments. Default is "install".
*/
@Parameter(defaultValue = "install", property = "frontend.npx.arguments", required = false)
private String arguments;
@Parameter(property = "frontend.npx.npmInheritsProxyConfigFromMaven", required = false, defaultValue = "true")
private boolean npmInheritsProxyConfigFromMaven;
/**
* Registry override, passed as the registry option during npm install if set.
*/
@Parameter(property = NPM_REGISTRY_URL, required = false, defaultValue = "")
private String npmRegistryURL;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
@Component
private BuildContext buildContext;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.npx", defaultValue = "${skip.npx}")
private boolean skip;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
File packageJson = new File(workingDirectory, "package.json");
if (buildContext == null || buildContext.hasDelta(packageJson) || !buildContext.isIncremental()) {
ProxyConfig proxyConfig = getProxyConfig();
factory.getNpxRunner(proxyConfig, getRegistryUrl()).execute(arguments, environmentVariables);
} else {
getLog().info("Skipping npm install as package.json unchanged");
}
}
private ProxyConfig getProxyConfig() {<FILL_FUNCTION_BODY>}
private String getRegistryUrl() {
// check to see if overridden via `-D`, otherwise fallback to pom value
return System.getProperty(NPM_REGISTRY_URL, npmRegistryURL);
}
} |
if (npmInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(session, decrypter);
} else {
getLog().info("npm not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
| 568 | 81 | 649 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/PnpmMojo.java | PnpmMojo | execute | class PnpmMojo extends AbstractFrontendMojo {
private static final String PNPM_REGISTRY_URL = "npmRegistryURL";
/**
* pnpm arguments. Default is "install".
*/
@Parameter(defaultValue = "install", property = "frontend.pnpm.arguments", required = false)
private String arguments;
@Parameter(property = "frontend.pnpm.pnpmInheritsProxyConfigFromMaven", required = false, defaultValue = "true")
private boolean pnpmInheritsProxyConfigFromMaven;
/**
* Registry override, passed as the registry option during pnpm install if set.
*/
@Parameter(property = PNPM_REGISTRY_URL, required = false, defaultValue = "")
private String pnpmRegistryURL;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
@Component
private BuildContext buildContext;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.pnpm", defaultValue = "${skip.pnpm}")
private boolean skip;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {<FILL_FUNCTION_BODY>}
private ProxyConfig getProxyConfig() {
if (pnpmInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(session, decrypter);
} else {
getLog().info("pnpm not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
}
private String getRegistryUrl() {
// check to see if overridden via `-D`, otherwise fallback to pom value
return System.getProperty(PNPM_REGISTRY_URL, pnpmRegistryURL);
}
} |
File packageJson = new File(workingDirectory, "package.json");
if (buildContext == null || buildContext.hasDelta(packageJson) || !buildContext.isIncremental()) {
ProxyConfig proxyConfig = getProxyConfig();
factory.getPnpmRunner(proxyConfig, getRegistryUrl()).execute(arguments, environmentVariables);
} else {
getLog().info("Skipping pnpm install as package.json unchanged");
}
| 540 | 112 | 652 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/RepositoryCacheResolver.java | RepositoryCacheResolver | createArtifact | class RepositoryCacheResolver implements CacheResolver {
private static final String GROUP_ID = "com.github.eirslett";
private final RepositorySystemSession repositorySystemSession;
public RepositoryCacheResolver(RepositorySystemSession repositorySystemSession) {
this.repositorySystemSession = repositorySystemSession;
}
@Override
public File resolve(CacheDescriptor cacheDescriptor) {
LocalRepositoryManager manager = repositorySystemSession.getLocalRepositoryManager();
File localArtifact = new File(
manager.getRepository().getBasedir(),
manager.getPathForLocalArtifact(createArtifact(cacheDescriptor))
);
return localArtifact;
}
private DefaultArtifact createArtifact(CacheDescriptor cacheDescriptor) {<FILL_FUNCTION_BODY>}
} |
String version = cacheDescriptor.getVersion().replaceAll("^v", "");
DefaultArtifact artifact;
if (cacheDescriptor.getClassifier() == null) {
artifact = new DefaultArtifact(
GROUP_ID,
cacheDescriptor.getName(),
cacheDescriptor.getExtension(),
version
);
} else {
artifact = new DefaultArtifact(
GROUP_ID,
cacheDescriptor.getName(),
cacheDescriptor.getClassifier(),
cacheDescriptor.getExtension(),
version
);
}
return artifact;
| 190 | 140 | 330 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/WebpackMojo.java | WebpackMojo | execute | class WebpackMojo extends AbstractFrontendMojo {
/**
* Webpack arguments. Default is empty (runs just the "webpack" command).
*/
@Parameter(property = "frontend.webpack.arguments")
private String arguments;
/**
* Files that should be checked for changes, in addition to the srcdir files.
* Defaults to webpack.config.js in the {@link #workingDirectory}.
*/
@Parameter(property = "triggerfiles")
private List<File> triggerfiles;
/**
* The directory containing front end files that will be processed by webpack.
* If this is set then files in the directory will be checked for
* modifications before running webpack.
*/
@Parameter(property = "srcdir")
private File srcdir;
/**
* The directory where front end files will be output by webpack. If this is
* set then they will be refreshed so they correctly show as modified in
* Eclipse.
*/
@Parameter(property = "outputdir")
private File outputdir;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.webpack", defaultValue = "${skip.webpack}")
private boolean skip;
@Component
private BuildContext buildContext;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {<FILL_FUNCTION_BODY>}
private boolean shouldExecute() {
if (triggerfiles == null || triggerfiles.isEmpty()) {
triggerfiles = Arrays.asList(new File(workingDirectory, "webpack.config.js"));
}
return MojoUtils.shouldExecute(buildContext, triggerfiles, srcdir);
}
} |
if (shouldExecute()) {
factory.getWebpackRunner().execute(arguments, environmentVariables);
if (outputdir != null) {
getLog().info("Refreshing files after webpack: " + outputdir);
buildContext.refresh(outputdir);
}
} else {
getLog().info("Skipping webpack as no modified files in " + srcdir);
}
| 467 | 105 | 572 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-maven-plugin/src/main/java/com/github/eirslett/maven/plugins/frontend/mojo/YarnMojo.java | YarnMojo | getProxyConfig | class YarnMojo extends AbstractFrontendMojo {
private static final String NPM_REGISTRY_URL = "npmRegistryURL";
/**
* npm arguments. Default is "install".
*/
@Parameter(defaultValue = "", property = "frontend.yarn.arguments", required = false)
private String arguments;
@Parameter(property = "frontend.yarn.yarnInheritsProxyConfigFromMaven", required = false,
defaultValue = "true")
private boolean yarnInheritsProxyConfigFromMaven;
/**
* Registry override, passed as the registry option during npm install if set.
*/
@Parameter(property = NPM_REGISTRY_URL, required = false, defaultValue = "")
private String npmRegistryURL;
@Parameter(property = "session", defaultValue = "${session}", readonly = true)
private MavenSession session;
@Component
private BuildContext buildContext;
@Component(role = SettingsDecrypter.class)
private SettingsDecrypter decrypter;
/**
* Skips execution of this mojo.
*/
@Parameter(property = "skip.yarn", defaultValue = "${skip.yarn}")
private boolean skip;
@Override
protected boolean skipExecution() {
return this.skip;
}
@Override
public synchronized void execute(FrontendPluginFactory factory) throws TaskRunnerException {
File packageJson = new File(this.workingDirectory, "package.json");
if (this.buildContext == null || this.buildContext.hasDelta(packageJson)
|| !this.buildContext.isIncremental()) {
ProxyConfig proxyConfig = getProxyConfig();
factory.getYarnRunner(proxyConfig, getRegistryUrl()).execute(this.arguments,
this.environmentVariables);
} else {
getLog().info("Skipping yarn install as package.json unchanged");
}
}
private ProxyConfig getProxyConfig() {<FILL_FUNCTION_BODY>}
private String getRegistryUrl() {
// check to see if overridden via `-D`, otherwise fallback to pom value
return System.getProperty(NPM_REGISTRY_URL, this.npmRegistryURL);
}
} |
if (this.yarnInheritsProxyConfigFromMaven) {
return MojoUtils.getProxyConfig(this.session, this.decrypter);
} else {
getLog().info("yarn not inheriting proxy config from Maven");
return new ProxyConfig(Collections.<ProxyConfig.Proxy>emptyList());
}
| 582 | 89 | 671 | <methods>public non-sealed void <init>() ,public void execute() throws MojoFailureException<variables>protected Map<java.lang.String,java.lang.String> environmentVariables,protected MojoExecution execution,protected java.io.File installDirectory,private MavenProject project,private RepositorySystemSession repositorySystemSession,protected java.lang.Boolean skipTests,protected boolean testFailureIgnore,protected java.io.File workingDirectory |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ArchiveExtractor.java | DefaultArchiveExtractor | extract | class DefaultArchiveExtractor implements ArchiveExtractor {
private static final Logger LOG = LoggerFactory.getLogger(DefaultArchiveExtractor.class);
private void prepDestination(File path, boolean directory) throws IOException {
if (directory) {
path.mkdirs();
} else {
if (!path.getParentFile().exists()) {
path.getParentFile().mkdirs();
}
if (!path.getParentFile().canWrite()) {
throw new AccessDeniedException(
String.format("Could not get write permissions for '%s'", path.getParentFile().getAbsolutePath()));
}
}
}
@Override
public void extract(String archive, String destinationDirectory) throws ArchiveExtractionException {<FILL_FUNCTION_BODY>}
/**
* Do multiple file system checks that should enable the plugin to work on any file system
* whether or not it's case sensitive or not.
*
* @param destPath
* @param destDir
* @return
*/
private boolean startsWithPath(String destPath, String destDir) {
if (destPath.startsWith(destDir)) {
return true;
} else if (destDir.length() > destPath.length()) {
return false;
} else {
if (new File(destPath).exists() && !(new File(destPath.toLowerCase()).exists())) {
return false;
}
return destPath.toLowerCase().startsWith(destDir.toLowerCase());
}
}
} |
final File archiveFile = new File(archive);
try (FileInputStream fis = new FileInputStream(archiveFile)) {
if ("msi".equals(FileUtils.getExtension(archiveFile.getAbsolutePath()))) {
String command = "msiexec /a " + archiveFile.getAbsolutePath() + " /qn TARGETDIR=\""
+ destinationDirectory + "\"";
Process child = Runtime.getRuntime().exec(command);
try {
int result = child.waitFor();
if (result != 0) {
throw new ArchiveExtractionException(
"Could not extract " + archiveFile.getAbsolutePath() + "; return code " + result);
}
} catch (InterruptedException e) {
throw new ArchiveExtractionException(
"Unexpected interruption of while waiting for extraction process", e);
}
} else if ("zip".equals(FileUtils.getExtension(archiveFile.getAbsolutePath()))) {
Path destinationPath = Paths.get(destinationDirectory).normalize();
try (ZipFile zipFile = new ZipFile(archiveFile)) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
final Path destPath = destinationPath.resolve(entry.getName()).normalize();
if (!destPath.startsWith(destinationPath)) {
throw new RuntimeException("Bad zip entry");
}
prepDestination(destPath.toFile(), entry.isDirectory());
if (!entry.isDirectory()) {
InputStream in = null;
OutputStream out = null;
try {
in = zipFile.getInputStream(entry);
out = new BufferedOutputStream(Files.newOutputStream(destPath));
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
}
}
} else {
// TarArchiveInputStream can be constructed with a normal FileInputStream if
// we ever need to extract regular '.tar' files.
TarArchiveInputStream tarIn = null;
try {
tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(fis));
TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
String canonicalDestinationDirectory = new File(destinationDirectory).getCanonicalPath();
while (tarEntry != null) {
// Create a file for this tarEntry
final File destPath = new File(destinationDirectory, tarEntry.getName());
prepDestination(destPath, tarEntry.isDirectory());
if (!startsWithPath(destPath.getCanonicalPath(), canonicalDestinationDirectory)) {
throw new IOException(
"Expanding " + tarEntry.getName() + " would create file outside of " + canonicalDestinationDirectory
);
}
if (!tarEntry.isDirectory()) {
destPath.createNewFile();
boolean isExecutable = (tarEntry.getMode() & 0100) > 0;
destPath.setExecutable(isExecutable);
OutputStream out = null;
try {
out = new FileOutputStream(destPath);
IOUtils.copy(tarIn, out);
} finally {
IOUtils.closeQuietly(out);
}
}
tarEntry = tarIn.getNextTarEntry();
}
} finally {
IOUtils.closeQuietly(tarIn);
}
}
} catch (IOException e) {
throw new ArchiveExtractionException("Could not extract archive: '"
+ archive
+ "'", e);
}
| 393 | 925 | 1,318 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ArgumentsParser.java | ArgumentsParser | parse | class ArgumentsParser {
private final List<String> additionalArguments;
ArgumentsParser() {
this(Collections.<String>emptyList());
}
ArgumentsParser(List<String> additionalArguments) {
this.additionalArguments = additionalArguments;
}
/**
* Parses a given string of arguments, splitting it by characters that are whitespaces according to {@link Character#isWhitespace(char)}.
* <p>
* This method respects quoted arguments. Meaning that whitespaces appearing phrases that are enclosed by an opening
* single or double quote and a closing single or double quote or the end of the string will not be considered.
* <p>
* All characters excluding whitespaces considered for splitting stay in place.
* <p>
* Examples:
* "foo bar" will be split to ["foo", "bar"]
* "foo \"bar foobar\"" will be split to ["foo", "\"bar foobar\""]
* "foo 'bar" will be split to ["foo", "'bar"]
*
* @param args a string of arguments
* @return an mutable copy of the list of all arguments
*/
List<String> parse(String args) {<FILL_FUNCTION_BODY>}
private static void addArgument(StringBuilder argumentBuilder, List<String> arguments) {
if (argumentBuilder.length() > 0) {
String argument = argumentBuilder.toString();
arguments.add(argument);
argumentBuilder.setLength(0);
}
}
} |
if (args == null || "null".equals(args) || args.isEmpty()) {
return Collections.emptyList();
}
final List<String> arguments = new LinkedList<>();
final StringBuilder argumentBuilder = new StringBuilder();
Character quote = null;
for (int i = 0, l = args.length(); i < l; i++) {
char c = args.charAt(i);
if (Character.isWhitespace(c) && quote == null) {
addArgument(argumentBuilder, arguments);
continue;
} else if (c == '"' || c == '\'') {
// explicit boxing allows us to use object caching of the Character class
Character currentQuote = Character.valueOf(c);
if (quote == null) {
quote = currentQuote;
} else if (quote.equals(currentQuote)){
quote = null;
} // else
// we ignore the case when a quoted argument contains the other kind of quote
}
argumentBuilder.append(c);
}
addArgument(argumentBuilder, arguments);
for (String argument : this.additionalArguments) {
if (!arguments.contains(argument)) {
arguments.add(argument);
}
}
return new ArrayList<>(arguments);
| 382 | 324 | 706 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/BunInstaller.java | BunInstaller | bunIsAlreadyInstalled | class BunInstaller {
public static final String INSTALL_PATH = "/bun";
public static final String DEFAULT_BUN_DOWNLOAD_ROOT =
"https://github.com/oven-sh/bun/releases/download/";
private static final Object LOCK = new Object();
private String bunVersion, userName, password;
private final Logger logger;
private final InstallConfig config;
private final ArchiveExtractor archiveExtractor;
private final FileDownloader fileDownloader;
BunInstaller(InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader) {
this.logger = LoggerFactory.getLogger(getClass());
this.config = config;
this.archiveExtractor = archiveExtractor;
this.fileDownloader = fileDownloader;
}
public BunInstaller setBunVersion(String bunVersion) {
this.bunVersion = bunVersion;
return this;
}
public BunInstaller setUserName(String userName) {
this.userName = userName;
return this;
}
public BunInstaller setPassword(String password) {
this.password = password;
return this;
}
public void install() throws InstallationException {
// use static lock object for a synchronized block
synchronized (LOCK) {
if (!bunIsAlreadyInstalled()) {
if (!this.bunVersion.startsWith("v")) {
this.logger.warn("Bun version does not start with naming convention 'v'.");
}
if (this.config.getPlatform().isWindows()) {
throw new InstallationException("Unable to install bun on windows!");
} else {
installBunDefault();
}
}
}
}
private boolean bunIsAlreadyInstalled() {<FILL_FUNCTION_BODY>}
private void installBunDefault() throws InstallationException {
try {
logger.info("Installing Bun version {}", bunVersion);
String downloadUrl = createDownloadUrl();
CacheDescriptor cacheDescriptor = new CacheDescriptor("bun", this.bunVersion,
"zip");
File archive = this.config.getCacheResolver().resolve(cacheDescriptor);
downloadFileIfMissing(downloadUrl, archive, this.userName, this.password);
File installDirectory = getInstallDirectory();
// We need to delete the existing bun directory first so we clean out any old files, and
// so we can rename the package directory below.
try {
if (installDirectory.isDirectory()) {
FileUtils.deleteDirectory(installDirectory);
}
} catch (IOException e) {
logger.warn("Failed to delete existing Bun installation.");
}
try {
extractFile(archive, installDirectory);
} catch (ArchiveExtractionException e) {
if (e.getCause() instanceof EOFException) {
this.logger.error("The archive file {} is corrupted and will be deleted. "
+ "Please try the build again.", archive.getPath());
archive.delete();
}
throw e;
}
// Search for the bun binary
File bunBinary =
new File(getInstallDirectory(), File.separator + createBunTargetArchitecturePath() + File.separator + "bun");
if (!bunBinary.exists()) {
throw new FileNotFoundException(
"Could not find the downloaded bun binary in " + bunBinary);
} else {
File destinationDirectory = getInstallDirectory();
File destination = new File(destinationDirectory, "bun");
this.logger.info("Copying bun binary from {} to {}", bunBinary, destination);
if (destination.exists() && !destination.delete()) {
throw new InstallationException("Could not install Bun: Was not allowed to delete " + destination);
}
try {
Files.move(bunBinary.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new InstallationException("Could not install Bun: Was not allowed to rename "
+ bunBinary + " to " + destination);
}
if (!destination.setExecutable(true, false)) {
throw new InstallationException(
"Could not install Bun: Was not allowed to make " + destination + " executable.");
}
this.logger.info("Installed bun locally.");
}
} catch (IOException e) {
throw new InstallationException("Could not install bun", e);
} catch (DownloadException e) {
throw new InstallationException("Could not download bun", e);
} catch (ArchiveExtractionException e) {
throw new InstallationException("Could not extract the bun archive", e);
}
}
private String createDownloadUrl() {
String downloadUrl = String.format("%sbun-%s", DEFAULT_BUN_DOWNLOAD_ROOT, bunVersion);
String extension = "zip";
String fileending = String.format("%s.%s", createBunTargetArchitecturePath(), extension);
downloadUrl += fileending;
return downloadUrl;
}
private String createBunTargetArchitecturePath() {
OS os = OS.guess();
Architecture architecture = Architecture.guess();
String destOs = os.equals(OS.Linux) ? "linux" : os.equals(OS.Mac) ? "darwin" : null;
String destArc = architecture.equals(Architecture.x64) ? "x64" : architecture.equals(
Architecture.arm64) ? "aarch64" : null;
return String.format("%s-%s-%s", INSTALL_PATH, destOs, destArc);
}
private File getInstallDirectory() {
File installDirectory = new File(this.config.getInstallDirectory(), "/");
if (!installDirectory.exists()) {
this.logger.info("Creating install directory {}", installDirectory);
installDirectory.mkdirs();
}
return installDirectory;
}
private void extractFile(File archive, File destinationDirectory) throws ArchiveExtractionException {
this.logger.info("Unpacking {} into {}", archive, destinationDirectory);
this.archiveExtractor.extract(archive.getPath(), destinationDirectory.getPath());
}
private void downloadFileIfMissing(String downloadUrl, File destination, String userName, String password)
throws DownloadException {
if (!destination.exists()) {
downloadFile(downloadUrl, destination, userName, password);
}
}
private void downloadFile(String downloadUrl, File destination, String userName, String password)
throws DownloadException {
this.logger.info("Downloading {} to {}", downloadUrl, destination);
this.fileDownloader.download(downloadUrl, destination.getPath(), userName, password);
}
} |
try {
BunExecutorConfig executorConfig = new InstallBunExecutorConfig(config);
File bunFile = executorConfig.getBunPath();
if (bunFile.exists()) {
final String version =
new BunExecutor(executorConfig, Arrays.asList("--version"), null).executeAndGetResult(logger);
if (version.equals(this.bunVersion.replaceFirst("^v", ""))) {
this.logger.info("Bun {} is already installed.", version);
return true;
} else {
this.logger.info("Bun {} was installed, but we need version {}", version,
this.bunVersion);
return false;
}
} else {
return false;
}
} catch (ProcessExecutionException e) {
this.logger.warn("Unable to determine current bun version: {}", e.getMessage());
return false;
}
| 1,741 | 233 | 1,974 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/BunTaskExecutor.java | BunTaskExecutor | execute | class BunTaskExecutor {
private static final String DS = "//";
private static final String AT = "@";
private final Logger logger;
private final String taskName;
private final ArgumentsParser argumentsParser;
private final BunExecutorConfig config;
public BunTaskExecutor(BunExecutorConfig config, String taskLocation) {
this(config, taskLocation, Collections.emptyList());
}
public BunTaskExecutor(BunExecutorConfig config, String taskName, String taskLocation) {
this(config, taskName, taskLocation, Collections.emptyList());
}
public BunTaskExecutor(BunExecutorConfig config, String taskLocation,
List<String> additionalArguments) {
this(config, getTaskNameFromLocation(taskLocation), taskLocation, additionalArguments);
}
public BunTaskExecutor(BunExecutorConfig config, String taskName, String taskLocation,
List<String> additionalArguments) {
logger = LoggerFactory.getLogger(getClass());
this.config = config;
this.taskName = taskName;
this.argumentsParser = new ArgumentsParser(additionalArguments);
}
private static String getTaskNameFromLocation(String taskLocation) {
return taskLocation.replaceAll("^.*/([^/]+)(?:\\.js)?$", "$1");
}
public final void execute(String args, Map<String, String> environment) throws TaskRunnerException {<FILL_FUNCTION_BODY>}
private List<String> getArguments(String args) {
return argumentsParser.parse(args);
}
private static String taskToString(String taskName, List<String> arguments) {
List<String> clonedArguments = new ArrayList<>(arguments);
for (int i = 0; i < clonedArguments.size(); i++) {
final String s = clonedArguments.get(i);
final boolean maskMavenProxyPassword = s.contains("proxy=");
if (maskMavenProxyPassword) {
final String bestEffortMaskedPassword = maskPassword(s);
clonedArguments.set(i, bestEffortMaskedPassword);
}
}
return "'" + taskName + " " + implode(" ", clonedArguments) + "'";
}
private static String maskPassword(String proxyString) {
String retVal = proxyString;
if (proxyString != null && !"".equals(proxyString.trim())) {
boolean hasSchemeDefined = proxyString.contains("http:") || proxyString.contains("https:");
boolean hasProtocolDefined = proxyString.contains(DS);
boolean hasAtCharacterDefined = proxyString.contains(AT);
if (hasSchemeDefined && hasProtocolDefined && hasAtCharacterDefined) {
final int firstDoubleSlashIndex = proxyString.indexOf(DS);
final int lastAtCharIndex = proxyString.lastIndexOf(AT);
boolean hasPossibleURIUserInfo = firstDoubleSlashIndex < lastAtCharIndex;
if (hasPossibleURIUserInfo) {
final String userInfo =
proxyString.substring(firstDoubleSlashIndex + DS.length(), lastAtCharIndex);
final String[] userParts = userInfo.split(":");
if (userParts.length > 0) {
final int startOfUserNameIndex = firstDoubleSlashIndex + DS.length();
final int firstColonInUsernameOrEndOfUserNameIndex =
startOfUserNameIndex + userParts[0].length();
final String leftPart =
proxyString.substring(0, firstColonInUsernameOrEndOfUserNameIndex);
final String rightPart = proxyString.substring(lastAtCharIndex);
retVal = leftPart + ":***" + rightPart;
}
}
}
}
return retVal;
}
} |
final List<String> arguments = getArguments(args);
logger.info("Running " + taskToString(taskName, arguments) + " in " + config.getWorkingDirectory());
try {
final int result =
new BunExecutor(config, arguments, environment).executeAndRedirectOutput(logger);
if (result != 0) {
throw new TaskRunnerException(
taskToString(taskName, arguments) + " failed. (error code " + result + ")");
}
} catch (ProcessExecutionException e) {
throw new TaskRunnerException(taskToString(taskName, arguments) + " failed.", e);
}
| 959 | 158 | 1,117 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/DirectoryCacheResolver.java | DirectoryCacheResolver | resolve | class DirectoryCacheResolver implements CacheResolver {
private final File cacheDirectory;
public DirectoryCacheResolver(File cacheDirectory) {
this.cacheDirectory = cacheDirectory;
}
@Override
public File resolve(CacheDescriptor cacheDescriptor) {<FILL_FUNCTION_BODY>}
} |
if (!cacheDirectory.exists()) {
cacheDirectory.mkdirs();
}
StringBuilder filename = new StringBuilder()
.append(cacheDescriptor.getName())
.append("-")
.append(cacheDescriptor.getVersion());
if (cacheDescriptor.getClassifier() != null) {
filename.append("-").append(cacheDescriptor.getClassifier());
}
filename.append(".").append(cacheDescriptor.getExtension());
return new File(cacheDirectory, filename.toString());
| 76 | 129 | 205 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/FileDownloader.java | DefaultFileDownloader | download | class DefaultFileDownloader implements FileDownloader {
private static final Logger LOGGER = LoggerFactory.getLogger(FileDownloader.class);
private final ProxyConfig proxyConfig;
public DefaultFileDownloader(ProxyConfig proxyConfig){
this.proxyConfig = proxyConfig;
}
@Override
public void download(String downloadUrl, String destination, String userName, String password) throws DownloadException {<FILL_FUNCTION_BODY>}
private CloseableHttpResponse execute(String requestUrl, String userName, String password) throws IOException {
final HttpGet request = new HttpGet(requestUrl);
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
final Proxy proxy = proxyConfig.getProxyForUrl(requestUrl);
if (proxy != null) {
LOGGER.info("Downloading via proxy " + proxy.toString());
final RequestConfig requestConfig = RequestConfig.custom()
.setProxy(new HttpHost(proxy.host, proxy.port))
.build();
request.setConfig(requestConfig);
if (proxy.useAuthentication()) {
credentialsProvider.setCredentials(
new AuthScope(proxy.host, proxy.port),
new UsernamePasswordCredentials(proxy.username, proxy.password));
}
} else {
LOGGER.info("No proxy was configured, downloading directly");
}
if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)) {
LOGGER.info("Using credentials (" + userName + ") from settings.xml");
// Auth target host
URL targetUrl = new URL(requestUrl);
credentialsProvider.setCredentials(
new AuthScope(targetUrl.getHost(), targetUrl.getPort()),
new UsernamePasswordCredentials(userName, password));
final HttpClientContext localContext = makeLocalContext(targetUrl);
return buildHttpClient(credentialsProvider)
.execute(request, localContext);
}
return buildHttpClient(credentialsProvider).execute(request);
}
private HttpClientContext makeLocalContext(URL requestUrl) {
// Auth target host
HttpHost target = new HttpHost (requestUrl.getHost(), requestUrl.getPort(), requestUrl.getProtocol());
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(target, basicAuth);
// Add AuthCache to the execution context
HttpClientContext localContext = HttpClientContext.create();
localContext.setAuthCache(authCache);
return localContext;
}
private CloseableHttpClient buildHttpClient(CredentialsProvider credentialsProvider) {
return HttpClients.custom()
.disableContentCompression()
.useSystemProperties()
.setDefaultCredentialsProvider(credentialsProvider)
.build();
}
} |
// force tls to 1.2 since github removed weak cryptographic standards
// https://blog.github.com/2018-02-02-weak-cryptographic-standards-removal-notice/
System.setProperty("https.protocols", "TLSv1.2");
String fixedDownloadUrl = downloadUrl;
try {
fixedDownloadUrl = FilenameUtils.separatorsToUnix(fixedDownloadUrl);
URI downloadURI = new URI(fixedDownloadUrl);
if ("file".equalsIgnoreCase(downloadURI.getScheme())) {
FileUtils.copyFile(new File(downloadURI), new File(destination));
}
else {
CloseableHttpResponse response = execute(fixedDownloadUrl, userName, password);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != 200){
throw new DownloadException("Got error code "+ statusCode +" from the server.");
}
byte[] data = IOUtils.toByteArray(response.getEntity().getContent());
new File(FilenameUtils.getFullPathNoEndSeparator(destination)).mkdirs();
FileUtils.writeByteArrayToFile(new File(destination), data);
}
} catch (IOException | URISyntaxException e) {
throw new DownloadException("Could not download " + fixedDownloadUrl, e);
}
| 726 | 347 | 1,073 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/NodeTaskExecutor.java | NodeTaskExecutor | maskPassword | class NodeTaskExecutor {
private static final String DS = "//";
private static final String AT = "@";
private final Logger logger;
private final String taskName;
private String taskLocation;
private final ArgumentsParser argumentsParser;
private final NodeExecutorConfig config;
private final Map<String, String> proxy;
public NodeTaskExecutor(NodeExecutorConfig config, String taskLocation) {
this(config, taskLocation, Collections.<String>emptyList());
}
public NodeTaskExecutor(NodeExecutorConfig config, String taskName, String taskLocation) {
this(config, taskName, taskLocation, Collections.<String>emptyList());
}
public NodeTaskExecutor(NodeExecutorConfig config, String taskLocation, List<String> additionalArguments) {
this(config, getTaskNameFromLocation(taskLocation), taskLocation, additionalArguments);
}
public NodeTaskExecutor(NodeExecutorConfig config, String taskName, String taskLocation, List<String> additionalArguments) {
this(config, taskName, taskLocation, additionalArguments, Collections.<String, String>emptyMap());
}
public NodeTaskExecutor(NodeExecutorConfig config, String taskName, String taskLocation, List<String> additionalArguments, Map<String, String> proxy) {
this.logger = LoggerFactory.getLogger(getClass());
this.config = config;
this.taskName = taskName;
this.taskLocation = taskLocation;
this.argumentsParser = new ArgumentsParser(additionalArguments);
this.proxy = proxy;
}
private static String getTaskNameFromLocation(String taskLocation) {
return taskLocation.replaceAll("^.*/([^/]+)(?:\\.js)?$","$1");
}
public final void execute(String args, Map<String, String> environment) throws TaskRunnerException {
final String absoluteTaskLocation = getAbsoluteTaskLocation();
final List<String> arguments = getArguments(args);
logger.info("Running " + taskToString(taskName, arguments) + " in " + config.getWorkingDirectory());
try {
Map<String, String> internalEnvironment = new HashMap<>();
if (environment != null && !environment.isEmpty()) {
internalEnvironment.putAll(environment);
}
if (!proxy.isEmpty()) {
internalEnvironment.putAll(proxy);
}
final int result = new NodeExecutor(config, prepend(absoluteTaskLocation, arguments), internalEnvironment ).executeAndRedirectOutput(logger);
if (result != 0) {
throw new TaskRunnerException(taskToString(taskName, arguments) + " failed. (error code " + result + ")");
}
} catch (ProcessExecutionException e) {
throw new TaskRunnerException(taskToString(taskName, arguments) + " failed.", e);
}
}
private String getAbsoluteTaskLocation() {
String location = normalize(taskLocation);
if (Utils.isRelative(taskLocation)) {
File taskFile = new File(config.getWorkingDirectory(), location);
if (!taskFile.exists()) {
taskFile = new File(config.getInstallDirectory(), location);
}
location = taskFile.getAbsolutePath();
}
return location;
}
private List<String> getArguments(String args) {
return argumentsParser.parse(args);
}
private static String taskToString(String taskName, List<String> arguments) {
List<String> clonedArguments = new ArrayList<String>(arguments);
for (int i = 0; i < clonedArguments.size(); i++) {
final String s = clonedArguments.get(i);
final boolean maskMavenProxyPassword = s.contains("proxy=");
if (maskMavenProxyPassword) {
final String bestEffortMaskedPassword = maskPassword(s);
clonedArguments.set(i, bestEffortMaskedPassword);
}
}
return "'" + taskName + " " + implode(" ", clonedArguments) + "'";
}
private static String maskPassword(String proxyString) {<FILL_FUNCTION_BODY>}
public void setTaskLocation(String taskLocation) {
this.taskLocation = taskLocation;
}
} |
String retVal = proxyString;
if (proxyString != null && !"".equals(proxyString.trim())) {
boolean hasSchemeDefined = proxyString.contains("http:") || proxyString.contains("https:");
boolean hasProtocolDefined = proxyString.contains(DS);
boolean hasAtCharacterDefined = proxyString.contains(AT);
if (hasSchemeDefined && hasProtocolDefined && hasAtCharacterDefined) {
final int firstDoubleSlashIndex = proxyString.indexOf(DS);
final int lastAtCharIndex = proxyString.lastIndexOf(AT);
boolean hasPossibleURIUserInfo = firstDoubleSlashIndex < lastAtCharIndex;
if (hasPossibleURIUserInfo) {
final String userInfo = proxyString.substring(firstDoubleSlashIndex + DS.length(), lastAtCharIndex);
final String[] userParts = userInfo.split(":");
if (userParts.length > 0) {
final int startOfUserNameIndex = firstDoubleSlashIndex + DS.length();
final int firstColonInUsernameOrEndOfUserNameIndex = startOfUserNameIndex + userParts[0].length();
final String leftPart = proxyString.substring(0, firstColonInUsernameOrEndOfUserNameIndex);
final String rightPart = proxyString.substring(lastAtCharIndex);
retVal = leftPart + ":***" + rightPart;
}
}
}
}
return retVal;
| 1,058 | 368 | 1,426 | <no_super_class> |
eirslett_frontend-maven-plugin | frontend-maven-plugin/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ProcessExecutor.java | ProcessExecutor | executeAndRedirectOutput | class ProcessExecutor {
private final static String PATH_ENV_VAR = "PATH";
private final Map<String, String> environment;
private CommandLine commandLine;
private final Executor executor;
public ProcessExecutor(File workingDirectory, List<String> paths, List<String> command, Platform platform, Map<String, String> additionalEnvironment){
this(workingDirectory, paths, command, platform, additionalEnvironment, 0);
}
public ProcessExecutor(File workingDirectory, List<String> paths, List<String> command, Platform platform, Map<String, String> additionalEnvironment, long timeoutInSeconds) {
this.environment = createEnvironment(paths, platform, additionalEnvironment);
this.commandLine = createCommandLine(command);
this.executor = createExecutor(workingDirectory, timeoutInSeconds);
}
public String executeAndGetResult(final Logger logger) throws ProcessExecutionException {
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
int exitValue = execute(logger, stdout, stderr);
if (exitValue == 0) {
return stdout.toString().trim();
} else {
throw new ProcessExecutionException(stdout + " " + stderr);
}
}
public int executeAndRedirectOutput(final Logger logger) throws ProcessExecutionException {<FILL_FUNCTION_BODY>}
private int execute(final Logger logger, final OutputStream stdout, final OutputStream stderr)
throws ProcessExecutionException {
logger.debug("Executing command line {}", commandLine);
try {
ExecuteStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr);
executor.setStreamHandler(streamHandler);
int exitValue = executor.execute(commandLine, environment);
logger.debug("Exit value {}", exitValue);
return exitValue;
} catch (ExecuteException e) {
if (executor.getWatchdog() != null && executor.getWatchdog().killedProcess()) {
throw new ProcessExecutionException("Process killed after timeout");
}
throw new ProcessExecutionException(e);
} catch (IOException e) {
throw new ProcessExecutionException(e);
}
}
private CommandLine createCommandLine(List<String> command) {
CommandLine commmandLine = new CommandLine(command.get(0));
for (int i = 1;i < command.size();i++) {
String argument = command.get(i);
commmandLine.addArgument(argument, false);
}
return commmandLine;
}
private Map<String, String> createEnvironment(final List<String> paths, final Platform platform, final Map<String, String> additionalEnvironment) {
final Map<String, String> environment = new HashMap<>(System.getenv());
if (additionalEnvironment != null) {
environment.putAll(additionalEnvironment);
}
if (platform.isWindows()) {
for (final Map.Entry<String, String> entry : environment.entrySet()) {
final String pathName = entry.getKey();
if (PATH_ENV_VAR.equalsIgnoreCase(pathName)) {
final String pathValue = entry.getValue();
environment.put(pathName, extendPathVariable(pathValue, paths));
}
}
} else {
final String pathValue = environment.get(PATH_ENV_VAR);
environment.put(PATH_ENV_VAR, extendPathVariable(pathValue, paths));
}
return environment;
}
private String extendPathVariable(final String existingValue, final List<String> paths) {
final StringBuilder pathBuilder = new StringBuilder();
for (final String path : paths) {
pathBuilder.append(path).append(File.pathSeparator);
}
if (existingValue != null) {
pathBuilder.append(existingValue).append(File.pathSeparator);
}
return pathBuilder.toString();
}
private Executor createExecutor(File workingDirectory, long timeoutInSeconds) {
DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(workingDirectory);
executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); // Fixes #41
if (timeoutInSeconds > 0) {
executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000));
}
return executor;
}
private static class LoggerOutputStream extends LogOutputStream {
private final Logger logger;
LoggerOutputStream(Logger logger, int logLevel) {
super(logLevel);
this.logger = logger;
}
@Override
public final void flush() {
// buffer processing on close() only
}
@Override
protected void processLine(final String line, final int logLevel) {
logger.info(line);
}
}
} |
OutputStream stdout = new LoggerOutputStream(logger, 0);
return execute(logger, stdout, stdout);
| 1,229 | 33 | 1,262 | <no_super_class> |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 2