prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
package com.educandoweb.course.config;
import java.time.Instant;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.educandoweb.course.entities.Category;
import com.educandoweb.course.entities.Order;
import com.educandoweb.course.entities.OrderItem;
import com.educandoweb.course.entities.Payment;
import com.educandoweb.course.entities.Product;
import com.educandoweb.course.entities.User;
import com.educandoweb.course.entities.enums.OrderStatus;
import com.educandoweb.course.repositories.CategoryRepository;
import com.educandoweb.course.repositories.OrderItemRepository;
import com.educandoweb.course.repositories.OrderRepository;
import com.educandoweb.course.repositories.ProductRepository;
import com.educandoweb.course.repositories.UserRepository;
@Configuration
@Profile("test")
public class TestConfig implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
private OrderRepository orderRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private OrderItemRepository orderItemRepository;
@Override
public void run(String... args) throws Exception {
Category cat1 = new Category(null, "Electronics");
Category cat2 = new Category(null, "Books");
Category cat3 = new Category(null, "Computers");
Product p1 = new Product(null, "The Lord of the Rings", "Lorem ipsum dolor sit amet, consectetur.", 90.5, "");
Product p2 = new Product(null, "Smart TV", "Nulla eu imperdiet purus. Maecenas ante.", 2190.0, "");
Product p3 = new Product(null, "Macbook Pro", "Nam eleifend maximus tortor, at mollis.", 1250.0, "");
Product p4 = new Product(null, "PC Gamer", "Donec aliquet odio ac rhoncus cursus.", 1200.0, "");
Product p5 = new Product(null, "Rails for Dummies", "Cras fringilla convallis sem vel faucibus.", 100.99, "");
categoryRepository.saveAll(Arrays.asList(cat1, cat2, cat3));
productRepository.saveAll(Arrays.asList(p1, p2, p3, p4, p5));
p1.getCategories().add(cat2);
p2.getCategories().add(cat1);
p2.getCategories().add(cat3);
p3.getCategories().add(cat3);
p4.getCategories().add(cat3);
p5.getCategories().add(cat2);
productRepository.saveAll(Arrays.asList(p1, p2, p3, p4, p5));
User u1 = new User(null, "Maria Brown", "[email protected]", "988888888", "123456");
User u2 = new User(null, "Alex Green", "[email protected]", "977777777", "123456");
Order o1 = new Order(null, Instant.parse("2019-06-20T19:53:07Z"), OrderStatus.PAID, u1);
Order o2 = new Order(null, Instant.parse("2019-07-21T03:42:10Z"), OrderStatus.WAITING_PAYMENT, u2);
Order o3 = new Order(null, Instant.parse("2019-07-22T15:21:22Z"), OrderStatus.WAITING_PAYMENT, u1);
userRepository.saveAll(Arrays.asList(u1, u2));
orderRepository.saveAll(Arrays.asList(o1, o2, o3));
OrderItem oi1 = new OrderItem(o1, p1, 2, p1.getPrice());
OrderItem oi2 = new OrderItem(o1, p3, 1, p3.getPrice());
OrderItem oi3 = new OrderItem(o2, p3, 2, p3.getPrice());
OrderItem oi4 = new OrderItem(o3, p5, | 2, p5.getPrice()); |
orderItemRepository.saveAll(Arrays.asList(oi1, oi2, oi3, oi4));
Payment pay1 = new Payment(null, Instant.parse("2019-06-20T21:53:07Z"), o1);
o1.setPayment(pay1);
orderRepository.save(o1);
}
} | src/main/java/com/educandoweb/course/config/TestConfig.java | matheusgmello-workshop-springboot3-jpa-16e84f3 | [
{
"filename": "src/main/java/com/educandoweb/course/entities/Product.java",
"retrieved_chunk": "\tpublic Set<Category> getCategories() {\n\t\treturn categories;\n\t}\n\t@JsonIgnore\n\tpublic Set<Order> getOrders() {\n\t\tSet<Order> set = new HashSet<>();\n\t\tfor (OrderItem x : items) {\n\t\t\tset.add(x.getOrder());\n\t\t}\n\t\treturn set;",
"score": 49.812082842318716
},
{
"filename": "src/main/java/com/educandoweb/course/entities/OrderItem.java",
"retrieved_chunk": "\tprivate static final long serialVersionUID = 1L;\n\t@EmbeddedId\n\tprivate OrderItemPK id = new OrderItemPK();\n\tprivate Integer quantity;\n\tprivate Double price;\n\tpublic OrderItem() {\n\t}\n\tpublic OrderItem(Order order, Product product, Integer quantity, Double price) {\n\t\tsuper();\n\t\tid.setOrder(order);",
"score": 48.940914334172646
},
{
"filename": "src/main/java/com/educandoweb/course/entities/enums/OrderStatus.java",
"retrieved_chunk": "package com.educandoweb.course.entities.enums;\npublic enum OrderStatus {\n\tWAITING_PAYMENT(1),\n\tPAID(2),\n\tSHIPPED(3),\n\tDELIVERED(4),\n\tCANCELED(5);\n\tprivate int code;\n\tprivate OrderStatus(int code) {\n\t\tthis.code = code;",
"score": 39.49368991376773
},
{
"filename": "src/main/java/com/educandoweb/course/entities/Order.java",
"retrieved_chunk": "\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\tprivate Instant moment;\n\tprivate Integer orderStatus;\n\t@ManyToOne\n\t@JoinColumn(name = \"client_id\")\n\tprivate User client;\n\t@OneToMany(mappedBy = \"id.order\")\n\tprivate Set<OrderItem> items = new HashSet<>();",
"score": 38.18090833011709
},
{
"filename": "src/main/java/com/educandoweb/course/entities/OrderItem.java",
"retrieved_chunk": "\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tOrderItem other = (OrderItem) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)",
"score": 35.03947003474339
}
] | java | 2, p5.getPrice()); |
package org.example.hmwk1.service.concretes;
import org.example.hmwk1.adapter.CheckService;
import org.example.hmwk1.entity.Customer;
import org.example.hmwk1.service.abstracts.UserService;
import java.util.ArrayList;
import java.util.List;
public class UserManager implements UserService {
private final CheckService checkService;
List<Customer> customers = new ArrayList<>();
public UserManager(CheckService checkService) {
this.checkService = checkService;
}
@Override
public void addUser(Customer customer) {
if (!checkService.checkUser(customer)) {
System.err.println("Invalid Process by Mernis");
System.exit(1);
}
if (customers.contains(customer)) {
System.err.println("User already exist");
} else {
customers.add(customer);
System.out.println("User is added.");
}
}
public Customer getCustomer(int id ){
for (Customer customer : customers) {
if(customer.getId() == id){
return customer;
}
}
throw new RuntimeException("Invalid id");
}
@Override
public List<Customer> getUsers() {
return customers;
}
@Override
public void deleteUser(Customer user) {
if (customers.contains(user)) {
customers.remove(user);
System.out.println("User: " + user.getId() + " is deleted.");
}
System.out.println("User is not in database.");
}
@Override
public void updateUser(int id, Customer customer) {
Customer userToUpdate = null;
for (Customer user2 : customers) {
if (user2.getId() == id) {
System.out.println(user2.getName() +" is updated to " + customer.getName());
userToUpdate = user2;
userToUpdate.setId(customer.getId());
userToUpdate.setPassword(customer.getPassword());
userToUpdate.setEmail(customer.getEmail());
userToUpdate.setName(customer.getName());
userToUpdate.setSurName(customer.getSurName());
| userToUpdate.setBirthYear(customer.getBirthYear()); |
userToUpdate.setTc(customer.getTc());
}
return;
}
System.out.println("Customer can not found.");
}
}
| src/main/java/org/example/hmwk1/service/concretes/UserManager.java | MERVECETIN1929-Turkcell-Homework1-bdf94f0 | [
{
"filename": "src/main/java/org/example/hmwk1/adapter/MernisService.java",
"retrieved_chunk": " userList.add(weasley);\n userList.add(snape);\n userList.add(john);\n }\n @Override\n public boolean checkUser(Customer customer) {\n for (Customer customer2 : userList) {\n if (customer2.getTc().equals(customer.getTc()) &&\n customer2.getName().equals(customer.getName()) &&\n customer2.getSurName().equals(customer.getSurName()) &&",
"score": 33.860620528487
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " for(Campaign campaign:campaignService.getCampaigns()){\n if(campaign.getGames().contains(game) && !(customer.getGames().contains(game))){\n game.setCost(game.getCost()-(game.getCost()*campaign.getDiscountAmount()/100));\n game.setCountOwner(game.getCountOwner()+1);\n System.out.println(\"New Cost \"+ game.getName()+\" is \"+game.getCost());\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName());\n customer.addGame(game);\n }\n }\n if (customer.getGames().contains(game)) {",
"score": 33.130695815515715
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " return;\n } else {\n game.setCountOwner(game.getCountOwner() + 1);\n customer.addGame(game);\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName());\n }\n }*/\n}",
"score": 31.122433697699115
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " customer.addGame(game);\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName()+\" cost: \"+game.getCost());\n }\n }\n// @Override\n// public void campaignSell(Customer customer, Game game) {\n// for(Campaign campaign:campaignService.getCampaigns()){\n//\n// if(campaign.getGames().contains(game) && !(customer.getGames().contains(game))){\n// game.setCost(game.getCost()-(game.getCost()*campaign.getDiscountAmount()/100));",
"score": 31.11973143299297
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " if(campaign.getGames().contains(game) ){\n game.setCost(game.getCost()-(game.getCost()*campaign.getDiscountAmount()/100));\n game.setCountOwner(game.getCountOwner()+1);\n System.out.println(\"New Cost \"+ game.getName()+\" is \"+game.getCost());\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName());\n customer.addGame(game);\n }\n }\n if(!(customer.getGames().contains(game))){\n game.setCountOwner(game.getCountOwner() + 1);",
"score": 30.99760230110188
}
] | java | userToUpdate.setBirthYear(customer.getBirthYear()); |
package org.example.hmwk1.service.concretes;
import org.example.hmwk1.adapter.CheckService;
import org.example.hmwk1.entity.Customer;
import org.example.hmwk1.service.abstracts.UserService;
import java.util.ArrayList;
import java.util.List;
public class UserManager implements UserService {
private final CheckService checkService;
List<Customer> customers = new ArrayList<>();
public UserManager(CheckService checkService) {
this.checkService = checkService;
}
@Override
public void addUser(Customer customer) {
if (!checkService.checkUser(customer)) {
System.err.println("Invalid Process by Mernis");
System.exit(1);
}
if (customers.contains(customer)) {
System.err.println("User already exist");
} else {
customers.add(customer);
System.out.println("User is added.");
}
}
public Customer getCustomer(int id ){
for (Customer customer : customers) {
if(customer.getId() == id){
return customer;
}
}
throw new RuntimeException("Invalid id");
}
@Override
public List<Customer> getUsers() {
return customers;
}
@Override
public void deleteUser(Customer user) {
if (customers.contains(user)) {
customers.remove(user);
System.out.println("User: " + user.getId() + " is deleted.");
}
System.out.println("User is not in database.");
}
@Override
public void updateUser(int id, Customer customer) {
Customer userToUpdate = null;
for (Customer user2 : customers) {
if (user2.getId() == id) {
System.out.println(user2.getName() +" is updated to " + customer.getName());
userToUpdate = user2;
userToUpdate.setId(customer.getId());
userToUpdate.setPassword(customer.getPassword());
userToUpdate.setEmail(customer.getEmail());
userToUpdate.setName(customer.getName());
userToUpdate.setSurName(customer.getSurName());
userToUpdate.setBirthYear(customer.getBirthYear());
userToUpdate. | setTc(customer.getTc()); |
}
return;
}
System.out.println("Customer can not found.");
}
}
| src/main/java/org/example/hmwk1/service/concretes/UserManager.java | MERVECETIN1929-Turkcell-Homework1-bdf94f0 | [
{
"filename": "src/main/java/org/example/hmwk1/adapter/MernisService.java",
"retrieved_chunk": " userList.add(weasley);\n userList.add(snape);\n userList.add(john);\n }\n @Override\n public boolean checkUser(Customer customer) {\n for (Customer customer2 : userList) {\n if (customer2.getTc().equals(customer.getTc()) &&\n customer2.getName().equals(customer.getName()) &&\n customer2.getSurName().equals(customer.getSurName()) &&",
"score": 36.83375468050895
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " return;\n } else {\n game.setCountOwner(game.getCountOwner() + 1);\n customer.addGame(game);\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName());\n }\n }*/\n}",
"score": 33.548897320809495
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " for(Campaign campaign:campaignService.getCampaigns()){\n if(campaign.getGames().contains(game) && !(customer.getGames().contains(game))){\n game.setCost(game.getCost()-(game.getCost()*campaign.getDiscountAmount()/100));\n game.setCountOwner(game.getCountOwner()+1);\n System.out.println(\"New Cost \"+ game.getName()+\" is \"+game.getCost());\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName());\n customer.addGame(game);\n }\n }\n if (customer.getGames().contains(game)) {",
"score": 32.638376271865965
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " if(campaign.getGames().contains(game) ){\n game.setCost(game.getCost()-(game.getCost()*campaign.getDiscountAmount()/100));\n game.setCountOwner(game.getCountOwner()+1);\n System.out.println(\"New Cost \"+ game.getName()+\" is \"+game.getCost());\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName());\n customer.addGame(game);\n }\n }\n if(!(customer.getGames().contains(game))){\n game.setCountOwner(game.getCountOwner() + 1);",
"score": 31.504670990957294
},
{
"filename": "src/main/java/org/example/hmwk1/service/concretes/SellingManager.java",
"retrieved_chunk": " customer.addGame(game);\n System.out.println(\"Game \" + game.getName() + \" sold to \" + customer.getName()+\" cost: \"+game.getCost());\n }\n }\n// @Override\n// public void campaignSell(Customer customer, Game game) {\n// for(Campaign campaign:campaignService.getCampaigns()){\n//\n// if(campaign.getGames().contains(game) && !(customer.getGames().contains(game))){\n// game.setCost(game.getCost()-(game.getCost()*campaign.getDiscountAmount()/100));",
"score": 30.38587604514155
}
] | java | setTc(customer.getTc()); |
package com.educandoweb.course.config;
import java.time.Instant;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.educandoweb.course.entities.Category;
import com.educandoweb.course.entities.Order;
import com.educandoweb.course.entities.OrderItem;
import com.educandoweb.course.entities.Payment;
import com.educandoweb.course.entities.Product;
import com.educandoweb.course.entities.User;
import com.educandoweb.course.entities.enums.OrderStatus;
import com.educandoweb.course.repositories.CategoryRepository;
import com.educandoweb.course.repositories.OrderItemRepository;
import com.educandoweb.course.repositories.OrderRepository;
import com.educandoweb.course.repositories.ProductRepository;
import com.educandoweb.course.repositories.UserRepository;
@Configuration
@Profile("test")
public class TestConfig implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
private OrderRepository orderRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private OrderItemRepository orderItemRepository;
@Override
public void run(String... args) throws Exception {
Category cat1 = new Category(null, "Electronics");
Category cat2 = new Category(null, "Books");
Category cat3 = new Category(null, "Computers");
Product p1 = new Product(null, "The Lord of the Rings", "Lorem ipsum dolor sit amet, consectetur.", 90.5, "");
Product p2 = new Product(null, "Smart TV", "Nulla eu imperdiet purus. Maecenas ante.", 2190.0, "");
Product p3 = new Product(null, "Macbook Pro", "Nam eleifend maximus tortor, at mollis.", 1250.0, "");
Product p4 = new Product(null, "PC Gamer", "Donec aliquet odio ac rhoncus cursus.", 1200.0, "");
Product p5 = new Product(null, "Rails for Dummies", "Cras fringilla convallis sem vel faucibus.", 100.99, "");
categoryRepository.saveAll(Arrays.asList(cat1, cat2, cat3));
productRepository.saveAll(Arrays.asList(p1, p2, p3, p4, p5));
p1.getCategories().add(cat2);
p2.getCategories().add(cat1);
p2.getCategories().add(cat3);
p3.getCategories().add(cat3);
p4.getCategories().add(cat3);
p5.getCategories().add(cat2);
productRepository.saveAll(Arrays.asList(p1, p2, p3, p4, p5));
User u1 = new User(null, "Maria Brown", "[email protected]", "988888888", "123456");
User u2 = new User(null, "Alex Green", "[email protected]", "977777777", "123456");
Order o1 = new Order(null, Instant.parse("2019-06-20T19:53:07Z"), OrderStatus.PAID, u1);
Order o2 = new Order(null, Instant.parse("2019-07-21T03:42:10Z"), OrderStatus.WAITING_PAYMENT, u2);
Order o3 = new Order(null, Instant.parse("2019-07-22T15:21:22Z"), OrderStatus.WAITING_PAYMENT, u1);
userRepository.saveAll(Arrays.asList(u1, u2));
orderRepository.saveAll(Arrays.asList(o1, o2, o3));
OrderItem oi1 = new OrderItem(o1, p1, 2, p1.getPrice());
OrderItem oi2 = new OrderItem(o1, p3, 1, p3.getPrice());
OrderItem oi3 = new OrderItem(o2 | , p3, 2, p3.getPrice()); |
OrderItem oi4 = new OrderItem(o3, p5, 2, p5.getPrice());
orderItemRepository.saveAll(Arrays.asList(oi1, oi2, oi3, oi4));
Payment pay1 = new Payment(null, Instant.parse("2019-06-20T21:53:07Z"), o1);
o1.setPayment(pay1);
orderRepository.save(o1);
}
} | src/main/java/com/educandoweb/course/config/TestConfig.java | matheusgmello-workshop-springboot3-jpa-16e84f3 | [
{
"filename": "src/main/java/com/educandoweb/course/entities/Product.java",
"retrieved_chunk": "\tpublic Set<Category> getCategories() {\n\t\treturn categories;\n\t}\n\t@JsonIgnore\n\tpublic Set<Order> getOrders() {\n\t\tSet<Order> set = new HashSet<>();\n\t\tfor (OrderItem x : items) {\n\t\t\tset.add(x.getOrder());\n\t\t}\n\t\treturn set;",
"score": 44.61298968833685
},
{
"filename": "src/main/java/com/educandoweb/course/entities/OrderItem.java",
"retrieved_chunk": "\tprivate static final long serialVersionUID = 1L;\n\t@EmbeddedId\n\tprivate OrderItemPK id = new OrderItemPK();\n\tprivate Integer quantity;\n\tprivate Double price;\n\tpublic OrderItem() {\n\t}\n\tpublic OrderItem(Order order, Product product, Integer quantity, Double price) {\n\t\tsuper();\n\t\tid.setOrder(order);",
"score": 42.24341910030059
},
{
"filename": "src/main/java/com/educandoweb/course/entities/Order.java",
"retrieved_chunk": "\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\tprivate Instant moment;\n\tprivate Integer orderStatus;\n\t@ManyToOne\n\t@JoinColumn(name = \"client_id\")\n\tprivate User client;\n\t@OneToMany(mappedBy = \"id.order\")\n\tprivate Set<OrderItem> items = new HashSet<>();",
"score": 36.71127616608037
},
{
"filename": "src/main/java/com/educandoweb/course/entities/enums/OrderStatus.java",
"retrieved_chunk": "package com.educandoweb.course.entities.enums;\npublic enum OrderStatus {\n\tWAITING_PAYMENT(1),\n\tPAID(2),\n\tSHIPPED(3),\n\tDELIVERED(4),\n\tCANCELED(5);\n\tprivate int code;\n\tprivate OrderStatus(int code) {\n\t\tthis.code = code;",
"score": 36.16557283983367
},
{
"filename": "src/main/java/com/educandoweb/course/entities/enums/OrderStatus.java",
"retrieved_chunk": "\t\tthrow new IllegalArgumentException(\"Invalid OrderStatus code\");\n\t}\n}",
"score": 34.21308396352827
}
] | java | , p3, 2, p3.getPrice()); |
package com.educandoweb.course.config;
import java.time.Instant;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.educandoweb.course.entities.Category;
import com.educandoweb.course.entities.Order;
import com.educandoweb.course.entities.OrderItem;
import com.educandoweb.course.entities.Payment;
import com.educandoweb.course.entities.Product;
import com.educandoweb.course.entities.User;
import com.educandoweb.course.entities.enums.OrderStatus;
import com.educandoweb.course.repositories.CategoryRepository;
import com.educandoweb.course.repositories.OrderItemRepository;
import com.educandoweb.course.repositories.OrderRepository;
import com.educandoweb.course.repositories.ProductRepository;
import com.educandoweb.course.repositories.UserRepository;
@Configuration
@Profile("test")
public class TestConfig implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
@Autowired
private OrderRepository orderRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private OrderItemRepository orderItemRepository;
@Override
public void run(String... args) throws Exception {
Category cat1 = new Category(null, "Electronics");
Category cat2 = new Category(null, "Books");
Category cat3 = new Category(null, "Computers");
Product p1 = new Product(null, "The Lord of the Rings", "Lorem ipsum dolor sit amet, consectetur.", 90.5, "");
Product p2 = new Product(null, "Smart TV", "Nulla eu imperdiet purus. Maecenas ante.", 2190.0, "");
Product p3 = new Product(null, "Macbook Pro", "Nam eleifend maximus tortor, at mollis.", 1250.0, "");
Product p4 = new Product(null, "PC Gamer", "Donec aliquet odio ac rhoncus cursus.", 1200.0, "");
Product p5 = new Product(null, "Rails for Dummies", "Cras fringilla convallis sem vel faucibus.", 100.99, "");
categoryRepository.saveAll(Arrays.asList(cat1, cat2, cat3));
productRepository.saveAll(Arrays.asList(p1, p2, p3, p4, p5));
p1.getCategories().add(cat2);
p2.getCategories().add(cat1);
p2.getCategories().add(cat3);
p3.getCategories().add(cat3);
p4.getCategories().add(cat3);
| p5.getCategories().add(cat2); |
productRepository.saveAll(Arrays.asList(p1, p2, p3, p4, p5));
User u1 = new User(null, "Maria Brown", "[email protected]", "988888888", "123456");
User u2 = new User(null, "Alex Green", "[email protected]", "977777777", "123456");
Order o1 = new Order(null, Instant.parse("2019-06-20T19:53:07Z"), OrderStatus.PAID, u1);
Order o2 = new Order(null, Instant.parse("2019-07-21T03:42:10Z"), OrderStatus.WAITING_PAYMENT, u2);
Order o3 = new Order(null, Instant.parse("2019-07-22T15:21:22Z"), OrderStatus.WAITING_PAYMENT, u1);
userRepository.saveAll(Arrays.asList(u1, u2));
orderRepository.saveAll(Arrays.asList(o1, o2, o3));
OrderItem oi1 = new OrderItem(o1, p1, 2, p1.getPrice());
OrderItem oi2 = new OrderItem(o1, p3, 1, p3.getPrice());
OrderItem oi3 = new OrderItem(o2, p3, 2, p3.getPrice());
OrderItem oi4 = new OrderItem(o3, p5, 2, p5.getPrice());
orderItemRepository.saveAll(Arrays.asList(oi1, oi2, oi3, oi4));
Payment pay1 = new Payment(null, Instant.parse("2019-06-20T21:53:07Z"), o1);
o1.setPayment(pay1);
orderRepository.save(o1);
}
} | src/main/java/com/educandoweb/course/config/TestConfig.java | matheusgmello-workshop-springboot3-jpa-16e84f3 | [
{
"filename": "src/main/java/com/educandoweb/course/entities/Product.java",
"retrieved_chunk": "\tpublic Set<Category> getCategories() {\n\t\treturn categories;\n\t}\n\t@JsonIgnore\n\tpublic Set<Order> getOrders() {\n\t\tSet<Order> set = new HashSet<>();\n\t\tfor (OrderItem x : items) {\n\t\t\tset.add(x.getOrder());\n\t\t}\n\t\treturn set;",
"score": 62.040811118404214
},
{
"filename": "src/main/java/com/educandoweb/course/entities/Product.java",
"retrieved_chunk": "\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tProduct other = (Product) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;",
"score": 15.064663385553587
},
{
"filename": "src/main/java/com/educandoweb/course/entities/Category.java",
"retrieved_chunk": "\t}\n\tpublic Set<Product> getProducts() {\n\t\treturn products;\n\t}\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;",
"score": 12.937434024856481
},
{
"filename": "src/main/java/com/educandoweb/course/services/ProductService.java",
"retrieved_chunk": "\tprivate ProductRepository repository;\n\tpublic List<Product> findAll() {\n\t\treturn repository.findAll();\n\t}\n\tpublic Product findById(Long id) {\n\t\tOptional<Product> obj = repository.findById(id);\n\t\treturn obj.get();\n\t}\n}",
"score": 11.927892491829525
},
{
"filename": "src/main/java/com/educandoweb/course/entities/Category.java",
"retrieved_chunk": "\t@ManyToMany(mappedBy = \"categories\")\n\tprivate Set<Product> products = new HashSet<>();\n\tpublic Category() {\n\t}\n\tpublic Category(Long id, String name) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t}\n\tpublic Long getId() {",
"score": 11.334707961358156
}
] | java | p5.getCategories().add(cat2); |
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package team.teampotato.minegpt.forge.forged.mixin;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.text.Text;
import team.teampotato.minegpt.forge.forged.impl.ClientCommandInternals;
@Mixin(ClientPlayerEntity.class)
abstract class ClientPlayerEntityMixin {
@Inject(method = "sendCommand(Ljava/lang/String;)Z", at = @At("HEAD"), cancellable = true)
private void onSendCommand(String command, CallbackInfoReturnable<Boolean> cir) {
if | (ClientCommandInternals.executeCommand(command)) { |
cir.setReturnValue(true);
}
}
@Inject(method = "sendCommand(Ljava/lang/String;Lnet/minecraft/text/Text;)V", at = @At("HEAD"), cancellable = true)
private void onSendCommand(String command, Text preview, CallbackInfo info) {
if (ClientCommandInternals.executeCommand(command)) {
info.cancel();
}
}
}
| forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/ClientPlayerEntityMixin.java | MCTeamPotato-MineGPT-00b1415 | [
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/ClientPlayNetworkHandlerMixin.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.At;\nimport org.spongepowered.asm.mixin.injection.Inject;\nimport org.spongepowered.asm.mixin.injection.callback.CallbackInfo;\nimport net.minecraft.client.network.ClientCommandSource;\nimport net.minecraft.client.network.ClientPlayNetworkHandler;\nimport net.minecraft.command.CommandRegistryAccess;\nimport net.minecraft.command.CommandSource;\nimport net.minecraft.network.packet.s2c.play.CommandTreeS2CPacket;\nimport net.minecraft.network.packet.s2c.play.GameJoinS2CPacket;\nimport team.teampotato.minegpt.forge.forged.api.ClientCommandRegistrationEvent;",
"score": 58.67094148868959
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/ClientPlayNetworkHandlerMixin.java",
"retrieved_chunk": "import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\nimport team.teampotato.minegpt.forge.forged.impl.ClientCommandInternals;\n@Mixin(ClientPlayNetworkHandler.class)\nabstract class ClientPlayNetworkHandlerMixin {\n @Shadow\n private CommandDispatcher<CommandSource> commandDispatcher;\n @Shadow\n @Final\n private ClientCommandSource commandSource;\n @Inject(method = \"onGameJoin\", at = @At(\"RETURN\"))",
"score": 49.60834350075324
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/ClientCommandSourceMixin.java",
"retrieved_chunk": "import net.minecraft.client.network.ClientCommandSource;\nimport net.minecraft.client.network.ClientPlayerEntity;\nimport net.minecraft.client.world.ClientWorld;\nimport net.minecraft.text.Text;\nimport net.minecraft.util.Formatting;\nimport team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\n@Mixin(ClientCommandSource.class)\nabstract class ClientCommandSourceMixin implements FabricClientCommandSource {\n @Shadow\n @Final",
"score": 46.44942048295479
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/impl/ClientCommandInternals.java",
"retrieved_chunk": "import net.minecraft.text.Texts;\nimport team.teampotato.minegpt.forge.forged.api.ClientCommandManager;\nimport team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\nimport team.teampotato.minegpt.forge.forged.mixin.HelpCommandAccessor;\n@OnlyIn(Dist.CLIENT)\npublic final class ClientCommandInternals {\n private static final Logger LOGGER = LoggerFactory.getLogger(ClientCommandInternals.class);\n private static final String API_COMMAND_NAME = \"fabric-command-api-v2:client\";\n private static final String SHORT_API_COMMAND_NAME = \"fcc\";\n private static @Nullable CommandDispatcher<FabricClientCommandSource> activeDispatcher;",
"score": 39.24092446284039
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/ClientCommandSourceMixin.java",
"retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage team.teampotato.minegpt.forge.forged.mixin;\nimport org.spongepowered.asm.mixin.Final;\nimport org.spongepowered.asm.mixin.Mixin;\nimport org.spongepowered.asm.mixin.Shadow;\nimport net.minecraft.client.MinecraftClient;",
"score": 33.224051239615925
}
] | java | (ClientCommandInternals.executeCommand(command)) { |
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package team.teampotato.minegpt.forge.forged.mixin;
import com.mojang.brigadier.CommandDispatcher;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.client.network.ClientCommandSource;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.command.CommandRegistryAccess;
import net.minecraft.command.CommandSource;
import net.minecraft.network.packet.s2c.play.CommandTreeS2CPacket;
import net.minecraft.network.packet.s2c.play.GameJoinS2CPacket;
import team.teampotato.minegpt.forge.forged.api.ClientCommandRegistrationEvent;
import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;
import team.teampotato.minegpt.forge.forged.impl.ClientCommandInternals;
@Mixin(ClientPlayNetworkHandler.class)
abstract class ClientPlayNetworkHandlerMixin {
@Shadow
private CommandDispatcher<CommandSource> commandDispatcher;
@Shadow
@Final
private ClientCommandSource commandSource;
@Inject(method = "onGameJoin", at = @At("RETURN"))
private void onGameJoin(GameJoinS2CPacket packet, CallbackInfo info) {
final CommandDispatcher<FabricClientCommandSource> dispatcher = new CommandDispatcher<>();
ClientCommandInternals.setActiveDispatcher(dispatcher);
ClientCommandRegistrationEvent.EVENT.invoker().register(dispatcher, new CommandRegistryAccess(packet.registryManager()));
| ClientCommandInternals.finalizeInit(); |
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Inject(method = "onCommandTree", at = @At("RETURN"))
private void onOnCommandTree(CommandTreeS2CPacket packet, CallbackInfo info) {
// Add the commands to the vanilla dispatcher for completion.
// It's done here because both the server and the client commands have
// to be in the same dispatcher and completion results.
ClientCommandInternals.addCommands((CommandDispatcher) commandDispatcher, (FabricClientCommandSource) commandSource);
}
}
| forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/ClientPlayNetworkHandlerMixin.java | MCTeamPotato-MineGPT-00b1415 | [
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/ClientPlayerEntityMixin.java",
"retrieved_chunk": " }\n }\n @Inject(method = \"sendCommand(Ljava/lang/String;Lnet/minecraft/text/Text;)V\", at = @At(\"HEAD\"), cancellable = true)\n private void onSendCommand(String command, Text preview, CallbackInfo info) {\n if (ClientCommandInternals.executeCommand(command)) {\n info.cancel();\n }\n }\n}",
"score": 37.77985966064113
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/impl/ClientCommandInternals.java",
"retrieved_chunk": "import net.minecraft.text.Texts;\nimport team.teampotato.minegpt.forge.forged.api.ClientCommandManager;\nimport team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\nimport team.teampotato.minegpt.forge.forged.mixin.HelpCommandAccessor;\n@OnlyIn(Dist.CLIENT)\npublic final class ClientCommandInternals {\n private static final Logger LOGGER = LoggerFactory.getLogger(ClientCommandInternals.class);\n private static final String API_COMMAND_NAME = \"fabric-command-api-v2:client\";\n private static final String SHORT_API_COMMAND_NAME = \"fcc\";\n private static @Nullable CommandDispatcher<FabricClientCommandSource> activeDispatcher;",
"score": 26.4351416415215
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/impl/ClientCommandInternals.java",
"retrieved_chunk": " public static void setActiveDispatcher(@Nullable CommandDispatcher<FabricClientCommandSource> dispatcher) {\n ClientCommandInternals.activeDispatcher = dispatcher;\n }\n public static @Nullable CommandDispatcher<FabricClientCommandSource> getActiveDispatcher() {\n return activeDispatcher;\n }\n /**\n * Executes a client-sided command. Callers should ensure that this is only called\n * on slash-prefixed messages and the slash needs to be removed before calling.\n * (This is the same requirement as {@code ClientPlayerEntity#sendCommand}.)",
"score": 24.923565119828336
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/ClientPlayerEntityMixin.java",
"retrieved_chunk": "import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;\nimport net.minecraft.client.network.ClientPlayerEntity;\nimport net.minecraft.text.Text;\nimport team.teampotato.minegpt.forge.forged.impl.ClientCommandInternals;\n@Mixin(ClientPlayerEntity.class)\nabstract class ClientPlayerEntityMixin {\n @Inject(method = \"sendCommand(Ljava/lang/String;)Z\", at = @At(\"HEAD\"), cancellable = true)\n private void onSendCommand(String command, CallbackInfoReturnable<Boolean> cir) {\n if (ClientCommandInternals.executeCommand(command)) {\n cir.setReturnValue(true);",
"score": 24.153283287934272
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/api/ClientCommandRegistrationEvent.java",
"retrieved_chunk": " * Called when registering client commands.\n *\n * @param dispatcher the command dispatcher to register commands to\n * @param registryAccess object exposing access to the game's registries\n */\n void register(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registryAccess);\n}",
"score": 23.126814789655587
}
] | java | ClientCommandInternals.finalizeInit(); |
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package team.teampotato.minegpt.forge.forged.api;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.jetbrains.annotations.Nullable;
import team.teampotato.minegpt.forge.forged.impl.ClientCommandInternals;
/**
* Manages client-sided commands and provides some related helper methods.
*
* <p>Client-sided commands are fully executed on the client,
* so players can use them in both singleplayer and multiplayer.
*
* <p>Registrations can be done in handlers for {@link ClientCommandRegistrationEvent#EVENT}
* (See example below.)
*
* <p>The commands are run on the client game thread by default.
* Avoid doing any heavy calculations here as that can freeze the game's rendering.
* For example, you can move heavy code to another thread.
*
* <p>This class also has alternatives to the server-side helper methods in
* {@link net.minecraft.server.command.CommandManager}:
* {@link #literal(String)} and {@link #argument(String, ArgumentType)}.
*
* <p>The precedence rules of client-sided and server-sided commands with the same name
* are an implementation detail that is not guaranteed to remain the same in future versions.
* The aim is to make commands from the server take precedence over client-sided commands
* in a future version of this API.
*
* <h2>Example command</h2>
* <pre>
* {@code
* ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {
* dispatcher.register(
* ClientCommandManager.literal("hello").executes(context -> {
* context.getSource().sendFeedback(Text.literal("Hello, world!"));
* return 0;
* })
* );
* });
* }
* </pre>
*/
@OnlyIn(Dist.CLIENT)
public final class ClientCommandManager {
private ClientCommandManager() {
}
/**
* Gets the active command dispatcher that handles client command registration and execution.
*
* <p>May be null when not connected to a server (dedicated or integrated).</p>
*
* @return active dispatcher if present
*/
public static @Nullable CommandDispatcher<FabricClientCommandSource> getActiveDispatcher() {
return | ClientCommandInternals.getActiveDispatcher(); |
}
/**
* Creates a literal argument builder.
*
* @param name the literal name
* @return the created argument builder
*/
public static LiteralArgumentBuilder<FabricClientCommandSource> literal(String name) {
return LiteralArgumentBuilder.literal(name);
}
/**
* Creates a required argument builder.
*
* @param name the name of the argument
* @param type the type of the argument
* @param <T> the type of the parsed argument value
* @return the created argument builder
*/
public static <T> RequiredArgumentBuilder<FabricClientCommandSource, T> argument(String name, ArgumentType<T> type) {
return RequiredArgumentBuilder.argument(name, type);
}
} | forge/src/main/java/team/teampotato/minegpt/forge/forged/api/ClientCommandManager.java | MCTeamPotato-MineGPT-00b1415 | [
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/impl/ClientCommandInternals.java",
"retrieved_chunk": " public static void setActiveDispatcher(@Nullable CommandDispatcher<FabricClientCommandSource> dispatcher) {\n ClientCommandInternals.activeDispatcher = dispatcher;\n }\n public static @Nullable CommandDispatcher<FabricClientCommandSource> getActiveDispatcher() {\n return activeDispatcher;\n }\n /**\n * Executes a client-sided command. Callers should ensure that this is only called\n * on slash-prefixed messages and the slash needs to be removed before calling.\n * (This is the same requirement as {@code ClientPlayerEntity#sendCommand}.)",
"score": 38.75013510039131
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/api/ClientCommandRegistrationEvent.java",
"retrieved_chunk": "/**\n * Callback for when client commands are registered to the dispatcher.\n *\n * <p>To register some commands, you would register an event listener and implement the callback.\n *\n * <p>See {@link ClientCommandManager} for more details and an example.\n */\npublic interface ClientCommandRegistrationEvent {\n Event<ClientCommandRegistrationEvent> EVENT = EventFactory.createEventResult();\n /**",
"score": 24.872633079786542
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/ClientPlayNetworkHandlerMixin.java",
"retrieved_chunk": " // It's done here because both the server and the client commands have\n // to be in the same dispatcher and completion results.\n ClientCommandInternals.addCommands((CommandDispatcher) commandDispatcher, (FabricClientCommandSource) commandSource);\n }\n}",
"score": 23.41528098580181
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/api/FabricClientCommandSource.java",
"retrieved_chunk": " * Gets the world where the player used the command.\n *\n * @return the world\n */\n ClientWorld getWorld();\n /**\n * Gets the meta property under {@code key} that was assigned to this source.\n *\n * <p>This method should return the same result for every call with the same {@code key}.\n *",
"score": 20.420019962432328
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/impl/ClientCommandInternals.java",
"retrieved_chunk": " }\n // See ChatInputSuggestor.formatException. That cannot be used directly as it returns an OrderedText instead of a Text.\n private static Text getErrorMessage(CommandSyntaxException e) {\n Text message = Texts.toText(e.getRawMessage());\n String context = e.getContext();\n return context != null ? Text.translatable(\"command.context.parse_error\", message, context) : message;\n }\n /**\n * Runs final initialization tasks such as {@link CommandDispatcher#findAmbiguities(AmbiguityConsumer)}\n * on the command dispatcher. Also registers a {@code /fcc help} command if there are other commands present.",
"score": 20.11004375583892
}
] | java | ClientCommandInternals.getActiveDispatcher(); |
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package team.teampotato.minegpt.forge.forged.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Iterables;
import com.mojang.brigadier.AmbiguityConsumer;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.ParsedCommandNode;
import com.mojang.brigadier.exceptions.BuiltInExceptionProvider;
import com.mojang.brigadier.exceptions.CommandExceptionType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.tree.CommandNode;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraft.client.MinecraftClient;
import net.minecraft.command.CommandException;
import net.minecraft.text.Text;
import net.minecraft.text.Texts;
import team.teampotato.minegpt.forge.forged.api.ClientCommandManager;
import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;
import team.teampotato.minegpt.forge.forged.mixin.HelpCommandAccessor;
@OnlyIn(Dist.CLIENT)
public final class ClientCommandInternals {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientCommandInternals.class);
private static final String API_COMMAND_NAME = "fabric-command-api-v2:client";
private static final String SHORT_API_COMMAND_NAME = "fcc";
private static @Nullable CommandDispatcher<FabricClientCommandSource> activeDispatcher;
public static void setActiveDispatcher(@Nullable CommandDispatcher<FabricClientCommandSource> dispatcher) {
ClientCommandInternals.activeDispatcher = dispatcher;
}
public static @Nullable CommandDispatcher<FabricClientCommandSource> getActiveDispatcher() {
return activeDispatcher;
}
/**
* Executes a client-sided command. Callers should ensure that this is only called
* on slash-prefixed messages and the slash needs to be removed before calling.
* (This is the same requirement as {@code ClientPlayerEntity#sendCommand}.)
*
* @param command the command with slash removed
* @return true if the command should not be sent to the server, false otherwise
*/
public static boolean executeCommand(String command) {
MinecraftClient client = MinecraftClient.getInstance();
// The interface is implemented on ClientCommandSource with a mixin.
// noinspection ConstantConditions
FabricClientCommandSource commandSource = (FabricClientCommandSource) client.getNetworkHandler().getCommandSource();
client.getProfiler().push(command);
try {
// TODO: Check for server commands before executing.
// This requires parsing the command, checking if they match a server command
// and then executing the command with the parse results.
activeDispatcher.execute(command, commandSource);
return true;
} catch (CommandSyntaxException e) {
boolean ignored = isIgnoredException(e.getType());
if (ignored) {
LOGGER.debug("Syntax exception for client-sided command '{}'", command, e);
return false;
}
LOGGER.warn("Syntax exception for client-sided command '{}'", command, e);
commandSource.sendError(getErrorMessage(e));
return true;
} catch (CommandException e) {
LOGGER.warn("Error while executing client-sided command '{}'", command, e);
commandSource.sendError(e.getTextMessage());
return true;
} catch (RuntimeException e) {
LOGGER.warn("Error while executing client-sided command '{}'", command, e);
commandSource.sendError(Text.of(e.getMessage()));
return true;
} finally {
client.getProfiler().pop();
}
}
/**
* Tests whether a command syntax exception with the type
* should be ignored and the command sent to the server.
*
* @param type the exception type
* @return true if ignored, false otherwise
*/
private static boolean isIgnoredException(CommandExceptionType type) {
BuiltInExceptionProvider builtins = CommandSyntaxException.BUILT_IN_EXCEPTIONS;
// Only ignore unknown commands and node parse exceptions.
// The argument-related dispatcher exceptions are not ignored because
// they will only happen if the user enters a correct command.
return type == builtins.dispatcherUnknownCommand() || type == builtins.dispatcherParseException();
}
// See ChatInputSuggestor.formatException. That cannot be used directly as it returns an OrderedText instead of a Text.
private static Text getErrorMessage(CommandSyntaxException e) {
Text message = Texts.toText(e.getRawMessage());
String context = e.getContext();
return context != null ? Text.translatable("command.context.parse_error", message, context) : message;
}
/**
* Runs final initialization tasks such as {@link CommandDispatcher#findAmbiguities(AmbiguityConsumer)}
* on the command dispatcher. Also registers a {@code /fcc help} command if there are other commands present.
*/
public static void finalizeInit() {
if (!activeDispatcher.getRoot().getChildren().isEmpty()) {
// Register an API command if there are other commands;
// these helpers are not needed if there are no client commands
LiteralArgumentBuilder<FabricClientCommandSource> help = ClientCommandManager.literal("help");
help.executes(ClientCommandInternals::executeRootHelp);
help.then(ClientCommandManager.argument("command", StringArgumentType.greedyString()).executes(ClientCommandInternals::executeArgumentHelp));
CommandNode<FabricClientCommandSource> mainNode = | activeDispatcher.register(ClientCommandManager.literal(API_COMMAND_NAME).then(help)); |
activeDispatcher.register(ClientCommandManager.literal(SHORT_API_COMMAND_NAME).redirect(mainNode));
}
// noinspection CodeBlock2Expr
activeDispatcher.findAmbiguities((parent, child, sibling, inputs) -> {
LOGGER.warn("Ambiguity between arguments {} and {} with inputs: {}", activeDispatcher.getPath(child), activeDispatcher.getPath(sibling), inputs);
});
}
private static int executeRootHelp(CommandContext<FabricClientCommandSource> context) {
return executeHelp(activeDispatcher.getRoot(), context);
}
private static int executeArgumentHelp(CommandContext<FabricClientCommandSource> context) throws CommandSyntaxException {
ParseResults<FabricClientCommandSource> parseResults = activeDispatcher.parse(StringArgumentType.getString(context, "command"), context.getSource());
List<ParsedCommandNode<FabricClientCommandSource>> nodes = parseResults.getContext().getNodes();
if (nodes.isEmpty()) {
throw HelpCommandAccessor.getFailedException().create();
}
return executeHelp(Iterables.getLast(nodes).getNode(), context);
}
private static int executeHelp(CommandNode<FabricClientCommandSource> startNode, CommandContext<FabricClientCommandSource> context) {
Map<CommandNode<FabricClientCommandSource>, String> commands = activeDispatcher.getSmartUsage(startNode, context.getSource());
for (String command : commands.values()) {
context.getSource().sendFeedback(Text.literal("/" + command));
}
return commands.size();
}
public static void addCommands(CommandDispatcher<FabricClientCommandSource> target, FabricClientCommandSource source) {
Map<CommandNode<FabricClientCommandSource>, CommandNode<FabricClientCommandSource>> originalToCopy = new HashMap<>();
originalToCopy.put(activeDispatcher.getRoot(), target.getRoot());
copyChildren(activeDispatcher.getRoot(), target.getRoot(), source, originalToCopy);
}
/**
* Copies the child commands from origin to target, filtered by {@code child.canUse(source)}.
* Mimics vanilla's CommandManager.makeTreeForSource.
*
* @param origin the source command node
* @param target the target command node
* @param source the command source
* @param originalToCopy a mutable map from original command nodes to their copies, used for redirects;
* should contain a mapping from origin to target
*/
private static void copyChildren(
CommandNode<FabricClientCommandSource> origin,
CommandNode<FabricClientCommandSource> target,
FabricClientCommandSource source,
Map<CommandNode<FabricClientCommandSource>, CommandNode<FabricClientCommandSource>> originalToCopy
) {
for (CommandNode<FabricClientCommandSource> child : origin.getChildren()) {
if (!child.canUse(source)) continue;
ArgumentBuilder<FabricClientCommandSource, ?> builder = child.createBuilder();
// Reset the unnecessary non-completion stuff from the builder
builder.requires(s -> true); // This is checked with the if check above.
if (builder.getCommand() != null) {
builder.executes(context -> 0);
}
// Set up redirects
if (builder.getRedirect() != null) {
builder.redirect(originalToCopy.get(builder.getRedirect()));
}
CommandNode<FabricClientCommandSource> result = builder.build();
originalToCopy.put(child, result);
target.addChild(result);
if (!child.getChildren().isEmpty()) {
copyChildren(child, result, source, originalToCopy);
}
}
}
}
| forge/src/main/java/team/teampotato/minegpt/forge/forged/impl/ClientCommandInternals.java | MCTeamPotato-MineGPT-00b1415 | [
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/command/ClientConfigCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\nimport team.teampotato.minegpt.screen.PingScreen;\n@OnlyIn(Dist.CLIENT)\npublic class ClientConfigCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 39.06067640559035
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/command/ClientCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\nimport team.teampotato.minegpt.screen.PingScreen;\n@OnlyIn(Dist.CLIENT)\npublic class ClientCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 39.06067640559035
},
{
"filename": "fabric/src/main/java/team/teampotato/minegpt/fabric/command/ClientConfigCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.config.Config;\nimport team.teampotato.minegpt.screen.PingScreen;\n@Environment(EnvType.CLIENT)\npublic class ClientConfigCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 38.18672144431212
},
{
"filename": "fabric/src/main/java/team/teampotato/minegpt/fabric/command/ClientCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.config.Config;\nimport team.teampotato.minegpt.screen.PingScreen;\n@Environment(EnvType.CLIENT)\npublic class ClientCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 38.18672144431212
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/command/ClientConfigCommand.java",
"retrieved_chunk": " context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.3\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.4\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.5\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.6\").formatted(Formatting.GREEN));\n return 1;\n }))\n .then(ClientCommandManager.literal(\"pingtest\")\n .executes(context -> {\n MinecraftClient.getInstance().execute(() -> {\n MinecraftClient.getInstance().setScreen(new PingScreen());",
"score": 30.22900213079901
}
] | java | activeDispatcher.register(ClientCommandManager.literal(API_COMMAND_NAME).then(help)); |
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package team.teampotato.minegpt.forge.forged.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Iterables;
import com.mojang.brigadier.AmbiguityConsumer;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.ParsedCommandNode;
import com.mojang.brigadier.exceptions.BuiltInExceptionProvider;
import com.mojang.brigadier.exceptions.CommandExceptionType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.tree.CommandNode;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraft.client.MinecraftClient;
import net.minecraft.command.CommandException;
import net.minecraft.text.Text;
import net.minecraft.text.Texts;
import team.teampotato.minegpt.forge.forged.api.ClientCommandManager;
import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;
import team.teampotato.minegpt.forge.forged.mixin.HelpCommandAccessor;
@OnlyIn(Dist.CLIENT)
public final class ClientCommandInternals {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientCommandInternals.class);
private static final String API_COMMAND_NAME = "fabric-command-api-v2:client";
private static final String SHORT_API_COMMAND_NAME = "fcc";
private static @Nullable CommandDispatcher<FabricClientCommandSource> activeDispatcher;
public static void setActiveDispatcher(@Nullable CommandDispatcher<FabricClientCommandSource> dispatcher) {
ClientCommandInternals.activeDispatcher = dispatcher;
}
public static @Nullable CommandDispatcher<FabricClientCommandSource> getActiveDispatcher() {
return activeDispatcher;
}
/**
* Executes a client-sided command. Callers should ensure that this is only called
* on slash-prefixed messages and the slash needs to be removed before calling.
* (This is the same requirement as {@code ClientPlayerEntity#sendCommand}.)
*
* @param command the command with slash removed
* @return true if the command should not be sent to the server, false otherwise
*/
public static boolean executeCommand(String command) {
MinecraftClient client = MinecraftClient.getInstance();
// The interface is implemented on ClientCommandSource with a mixin.
// noinspection ConstantConditions
FabricClientCommandSource commandSource = (FabricClientCommandSource) client.getNetworkHandler().getCommandSource();
client.getProfiler().push(command);
try {
// TODO: Check for server commands before executing.
// This requires parsing the command, checking if they match a server command
// and then executing the command with the parse results.
activeDispatcher.execute(command, commandSource);
return true;
} catch (CommandSyntaxException e) {
boolean ignored = isIgnoredException(e.getType());
if (ignored) {
LOGGER.debug("Syntax exception for client-sided command '{}'", command, e);
return false;
}
LOGGER.warn("Syntax exception for client-sided command '{}'", command, e);
commandSource.sendError(getErrorMessage(e));
return true;
} catch (CommandException e) {
LOGGER.warn("Error while executing client-sided command '{}'", command, e);
commandSource.sendError(e.getTextMessage());
return true;
} catch (RuntimeException e) {
LOGGER.warn("Error while executing client-sided command '{}'", command, e);
commandSource.sendError(Text.of(e.getMessage()));
return true;
} finally {
client.getProfiler().pop();
}
}
/**
* Tests whether a command syntax exception with the type
* should be ignored and the command sent to the server.
*
* @param type the exception type
* @return true if ignored, false otherwise
*/
private static boolean isIgnoredException(CommandExceptionType type) {
BuiltInExceptionProvider builtins = CommandSyntaxException.BUILT_IN_EXCEPTIONS;
// Only ignore unknown commands and node parse exceptions.
// The argument-related dispatcher exceptions are not ignored because
// they will only happen if the user enters a correct command.
return type == builtins.dispatcherUnknownCommand() || type == builtins.dispatcherParseException();
}
// See ChatInputSuggestor.formatException. That cannot be used directly as it returns an OrderedText instead of a Text.
private static Text getErrorMessage(CommandSyntaxException e) {
Text message = Texts.toText(e.getRawMessage());
String context = e.getContext();
return context != null ? Text.translatable("command.context.parse_error", message, context) : message;
}
/**
* Runs final initialization tasks such as {@link CommandDispatcher#findAmbiguities(AmbiguityConsumer)}
* on the command dispatcher. Also registers a {@code /fcc help} command if there are other commands present.
*/
public static void finalizeInit() {
if (!activeDispatcher.getRoot().getChildren().isEmpty()) {
// Register an API command if there are other commands;
// these helpers are not needed if there are no client commands
LiteralArgumentBuilder<FabricClientCommandSource> help = ClientCommandManager.literal("help");
help.executes(ClientCommandInternals::executeRootHelp);
help.then(ClientCommandManager.argument("command", StringArgumentType.greedyString()).executes(ClientCommandInternals::executeArgumentHelp));
CommandNode<FabricClientCommandSource> mainNode = activeDispatcher.register(ClientCommandManager.literal(API_COMMAND_NAME).then(help));
activeDispatcher. | register(ClientCommandManager.literal(SHORT_API_COMMAND_NAME).redirect(mainNode)); |
}
// noinspection CodeBlock2Expr
activeDispatcher.findAmbiguities((parent, child, sibling, inputs) -> {
LOGGER.warn("Ambiguity between arguments {} and {} with inputs: {}", activeDispatcher.getPath(child), activeDispatcher.getPath(sibling), inputs);
});
}
private static int executeRootHelp(CommandContext<FabricClientCommandSource> context) {
return executeHelp(activeDispatcher.getRoot(), context);
}
private static int executeArgumentHelp(CommandContext<FabricClientCommandSource> context) throws CommandSyntaxException {
ParseResults<FabricClientCommandSource> parseResults = activeDispatcher.parse(StringArgumentType.getString(context, "command"), context.getSource());
List<ParsedCommandNode<FabricClientCommandSource>> nodes = parseResults.getContext().getNodes();
if (nodes.isEmpty()) {
throw HelpCommandAccessor.getFailedException().create();
}
return executeHelp(Iterables.getLast(nodes).getNode(), context);
}
private static int executeHelp(CommandNode<FabricClientCommandSource> startNode, CommandContext<FabricClientCommandSource> context) {
Map<CommandNode<FabricClientCommandSource>, String> commands = activeDispatcher.getSmartUsage(startNode, context.getSource());
for (String command : commands.values()) {
context.getSource().sendFeedback(Text.literal("/" + command));
}
return commands.size();
}
public static void addCommands(CommandDispatcher<FabricClientCommandSource> target, FabricClientCommandSource source) {
Map<CommandNode<FabricClientCommandSource>, CommandNode<FabricClientCommandSource>> originalToCopy = new HashMap<>();
originalToCopy.put(activeDispatcher.getRoot(), target.getRoot());
copyChildren(activeDispatcher.getRoot(), target.getRoot(), source, originalToCopy);
}
/**
* Copies the child commands from origin to target, filtered by {@code child.canUse(source)}.
* Mimics vanilla's CommandManager.makeTreeForSource.
*
* @param origin the source command node
* @param target the target command node
* @param source the command source
* @param originalToCopy a mutable map from original command nodes to their copies, used for redirects;
* should contain a mapping from origin to target
*/
private static void copyChildren(
CommandNode<FabricClientCommandSource> origin,
CommandNode<FabricClientCommandSource> target,
FabricClientCommandSource source,
Map<CommandNode<FabricClientCommandSource>, CommandNode<FabricClientCommandSource>> originalToCopy
) {
for (CommandNode<FabricClientCommandSource> child : origin.getChildren()) {
if (!child.canUse(source)) continue;
ArgumentBuilder<FabricClientCommandSource, ?> builder = child.createBuilder();
// Reset the unnecessary non-completion stuff from the builder
builder.requires(s -> true); // This is checked with the if check above.
if (builder.getCommand() != null) {
builder.executes(context -> 0);
}
// Set up redirects
if (builder.getRedirect() != null) {
builder.redirect(originalToCopy.get(builder.getRedirect()));
}
CommandNode<FabricClientCommandSource> result = builder.build();
originalToCopy.put(child, result);
target.addChild(result);
if (!child.getChildren().isEmpty()) {
copyChildren(child, result, source, originalToCopy);
}
}
}
}
| forge/src/main/java/team/teampotato/minegpt/forge/forged/impl/ClientCommandInternals.java | MCTeamPotato-MineGPT-00b1415 | [
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/command/ClientConfigCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\nimport team.teampotato.minegpt.screen.PingScreen;\n@OnlyIn(Dist.CLIENT)\npublic class ClientConfigCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 43.59248754795176
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/command/ClientCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\nimport team.teampotato.minegpt.screen.PingScreen;\n@OnlyIn(Dist.CLIENT)\npublic class ClientCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 43.59248754795176
},
{
"filename": "fabric/src/main/java/team/teampotato/minegpt/fabric/command/ClientConfigCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.config.Config;\nimport team.teampotato.minegpt.screen.PingScreen;\n@Environment(EnvType.CLIENT)\npublic class ClientConfigCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 42.7811124958545
},
{
"filename": "fabric/src/main/java/team/teampotato/minegpt/fabric/command/ClientCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.config.Config;\nimport team.teampotato.minegpt.screen.PingScreen;\n@Environment(EnvType.CLIENT)\npublic class ClientCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 42.7811124958545
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/command/ClientConfigCommand.java",
"retrieved_chunk": " context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.3\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.4\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.5\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.6\").formatted(Formatting.GREEN));\n return 1;\n }))\n .then(ClientCommandManager.literal(\"pingtest\")\n .executes(context -> {\n MinecraftClient.getInstance().execute(() -> {\n MinecraftClient.getInstance().setScreen(new PingScreen());",
"score": 32.27206652617555
}
] | java | register(ClientCommandManager.literal(SHORT_API_COMMAND_NAME).redirect(mainNode)); |
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package team.teampotato.minegpt.forge.forged.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Iterables;
import com.mojang.brigadier.AmbiguityConsumer;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.ParsedCommandNode;
import com.mojang.brigadier.exceptions.BuiltInExceptionProvider;
import com.mojang.brigadier.exceptions.CommandExceptionType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.tree.CommandNode;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraft.client.MinecraftClient;
import net.minecraft.command.CommandException;
import net.minecraft.text.Text;
import net.minecraft.text.Texts;
import team.teampotato.minegpt.forge.forged.api.ClientCommandManager;
import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;
import team.teampotato.minegpt.forge.forged.mixin.HelpCommandAccessor;
@OnlyIn(Dist.CLIENT)
public final class ClientCommandInternals {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientCommandInternals.class);
private static final String API_COMMAND_NAME = "fabric-command-api-v2:client";
private static final String SHORT_API_COMMAND_NAME = "fcc";
private static @Nullable CommandDispatcher<FabricClientCommandSource> activeDispatcher;
public static void setActiveDispatcher(@Nullable CommandDispatcher<FabricClientCommandSource> dispatcher) {
ClientCommandInternals.activeDispatcher = dispatcher;
}
public static @Nullable CommandDispatcher<FabricClientCommandSource> getActiveDispatcher() {
return activeDispatcher;
}
/**
* Executes a client-sided command. Callers should ensure that this is only called
* on slash-prefixed messages and the slash needs to be removed before calling.
* (This is the same requirement as {@code ClientPlayerEntity#sendCommand}.)
*
* @param command the command with slash removed
* @return true if the command should not be sent to the server, false otherwise
*/
public static boolean executeCommand(String command) {
MinecraftClient client = MinecraftClient.getInstance();
// The interface is implemented on ClientCommandSource with a mixin.
// noinspection ConstantConditions
FabricClientCommandSource commandSource = (FabricClientCommandSource) client.getNetworkHandler().getCommandSource();
client.getProfiler().push(command);
try {
// TODO: Check for server commands before executing.
// This requires parsing the command, checking if they match a server command
// and then executing the command with the parse results.
activeDispatcher.execute(command, commandSource);
return true;
} catch (CommandSyntaxException e) {
boolean ignored = isIgnoredException(e.getType());
if (ignored) {
LOGGER.debug("Syntax exception for client-sided command '{}'", command, e);
return false;
}
LOGGER.warn("Syntax exception for client-sided command '{}'", command, e);
commandSource.sendError(getErrorMessage(e));
return true;
} catch (CommandException e) {
LOGGER.warn("Error while executing client-sided command '{}'", command, e);
commandSource.sendError(e.getTextMessage());
return true;
} catch (RuntimeException e) {
LOGGER.warn("Error while executing client-sided command '{}'", command, e);
commandSource.sendError(Text.of(e.getMessage()));
return true;
} finally {
client.getProfiler().pop();
}
}
/**
* Tests whether a command syntax exception with the type
* should be ignored and the command sent to the server.
*
* @param type the exception type
* @return true if ignored, false otherwise
*/
private static boolean isIgnoredException(CommandExceptionType type) {
BuiltInExceptionProvider builtins = CommandSyntaxException.BUILT_IN_EXCEPTIONS;
// Only ignore unknown commands and node parse exceptions.
// The argument-related dispatcher exceptions are not ignored because
// they will only happen if the user enters a correct command.
return type == builtins.dispatcherUnknownCommand() || type == builtins.dispatcherParseException();
}
// See ChatInputSuggestor.formatException. That cannot be used directly as it returns an OrderedText instead of a Text.
private static Text getErrorMessage(CommandSyntaxException e) {
Text message = Texts.toText(e.getRawMessage());
String context = e.getContext();
return context != null ? Text.translatable("command.context.parse_error", message, context) : message;
}
/**
* Runs final initialization tasks such as {@link CommandDispatcher#findAmbiguities(AmbiguityConsumer)}
* on the command dispatcher. Also registers a {@code /fcc help} command if there are other commands present.
*/
public static void finalizeInit() {
if (!activeDispatcher.getRoot().getChildren().isEmpty()) {
// Register an API command if there are other commands;
// these helpers are not needed if there are no client commands
| LiteralArgumentBuilder<FabricClientCommandSource> help = ClientCommandManager.literal("help"); |
help.executes(ClientCommandInternals::executeRootHelp);
help.then(ClientCommandManager.argument("command", StringArgumentType.greedyString()).executes(ClientCommandInternals::executeArgumentHelp));
CommandNode<FabricClientCommandSource> mainNode = activeDispatcher.register(ClientCommandManager.literal(API_COMMAND_NAME).then(help));
activeDispatcher.register(ClientCommandManager.literal(SHORT_API_COMMAND_NAME).redirect(mainNode));
}
// noinspection CodeBlock2Expr
activeDispatcher.findAmbiguities((parent, child, sibling, inputs) -> {
LOGGER.warn("Ambiguity between arguments {} and {} with inputs: {}", activeDispatcher.getPath(child), activeDispatcher.getPath(sibling), inputs);
});
}
private static int executeRootHelp(CommandContext<FabricClientCommandSource> context) {
return executeHelp(activeDispatcher.getRoot(), context);
}
private static int executeArgumentHelp(CommandContext<FabricClientCommandSource> context) throws CommandSyntaxException {
ParseResults<FabricClientCommandSource> parseResults = activeDispatcher.parse(StringArgumentType.getString(context, "command"), context.getSource());
List<ParsedCommandNode<FabricClientCommandSource>> nodes = parseResults.getContext().getNodes();
if (nodes.isEmpty()) {
throw HelpCommandAccessor.getFailedException().create();
}
return executeHelp(Iterables.getLast(nodes).getNode(), context);
}
private static int executeHelp(CommandNode<FabricClientCommandSource> startNode, CommandContext<FabricClientCommandSource> context) {
Map<CommandNode<FabricClientCommandSource>, String> commands = activeDispatcher.getSmartUsage(startNode, context.getSource());
for (String command : commands.values()) {
context.getSource().sendFeedback(Text.literal("/" + command));
}
return commands.size();
}
public static void addCommands(CommandDispatcher<FabricClientCommandSource> target, FabricClientCommandSource source) {
Map<CommandNode<FabricClientCommandSource>, CommandNode<FabricClientCommandSource>> originalToCopy = new HashMap<>();
originalToCopy.put(activeDispatcher.getRoot(), target.getRoot());
copyChildren(activeDispatcher.getRoot(), target.getRoot(), source, originalToCopy);
}
/**
* Copies the child commands from origin to target, filtered by {@code child.canUse(source)}.
* Mimics vanilla's CommandManager.makeTreeForSource.
*
* @param origin the source command node
* @param target the target command node
* @param source the command source
* @param originalToCopy a mutable map from original command nodes to their copies, used for redirects;
* should contain a mapping from origin to target
*/
private static void copyChildren(
CommandNode<FabricClientCommandSource> origin,
CommandNode<FabricClientCommandSource> target,
FabricClientCommandSource source,
Map<CommandNode<FabricClientCommandSource>, CommandNode<FabricClientCommandSource>> originalToCopy
) {
for (CommandNode<FabricClientCommandSource> child : origin.getChildren()) {
if (!child.canUse(source)) continue;
ArgumentBuilder<FabricClientCommandSource, ?> builder = child.createBuilder();
// Reset the unnecessary non-completion stuff from the builder
builder.requires(s -> true); // This is checked with the if check above.
if (builder.getCommand() != null) {
builder.executes(context -> 0);
}
// Set up redirects
if (builder.getRedirect() != null) {
builder.redirect(originalToCopy.get(builder.getRedirect()));
}
CommandNode<FabricClientCommandSource> result = builder.build();
originalToCopy.put(child, result);
target.addChild(result);
if (!child.getChildren().isEmpty()) {
copyChildren(child, result, source, originalToCopy);
}
}
}
}
| forge/src/main/java/team/teampotato/minegpt/forge/forged/impl/ClientCommandInternals.java | MCTeamPotato-MineGPT-00b1415 | [
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/api/ClientCommandManager.java",
"retrieved_chunk": " *\n * <p>The precedence rules of client-sided and server-sided commands with the same name\n * are an implementation detail that is not guaranteed to remain the same in future versions.\n * The aim is to make commands from the server take precedence over client-sided commands\n * in a future version of this API.\n *\n * <h2>Example command</h2>\n * <pre>\n * {@code\n * ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> {",
"score": 35.105567089724474
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/api/ClientCommandRegistrationEvent.java",
"retrieved_chunk": "/**\n * Callback for when client commands are registered to the dispatcher.\n *\n * <p>To register some commands, you would register an event listener and implement the callback.\n *\n * <p>See {@link ClientCommandManager} for more details and an example.\n */\npublic interface ClientCommandRegistrationEvent {\n Event<ClientCommandRegistrationEvent> EVENT = EventFactory.createEventResult();\n /**",
"score": 33.857917103995064
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/api/ClientCommandManager.java",
"retrieved_chunk": "@OnlyIn(Dist.CLIENT)\npublic final class ClientCommandManager {\n private ClientCommandManager() {\n }\n /**\n * Gets the active command dispatcher that handles client command registration and execution.\n *\n * <p>May be null when not connected to a server (dedicated or integrated).</p>\n *\n * @return active dispatcher if present",
"score": 29.862326670844972
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/api/ClientCommandManager.java",
"retrieved_chunk": " * <p>Registrations can be done in handlers for {@link ClientCommandRegistrationEvent#EVENT}\n * (See example below.)\n *\n * <p>The commands are run on the client game thread by default.\n * Avoid doing any heavy calculations here as that can freeze the game's rendering.\n * For example, you can move heavy code to another thread.\n *\n * <p>This class also has alternatives to the server-side helper methods in\n * {@link net.minecraft.server.command.CommandManager}:\n * {@link #literal(String)} and {@link #argument(String, ArgumentType)}.",
"score": 29.78515261019874
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/api/ClientCommandManager.java",
"retrieved_chunk": "import net.minecraftforge.api.distmarker.Dist;\nimport net.minecraftforge.api.distmarker.OnlyIn;\nimport org.jetbrains.annotations.Nullable;\nimport team.teampotato.minegpt.forge.forged.impl.ClientCommandInternals;\n/**\n * Manages client-sided commands and provides some related helper methods.\n *\n * <p>Client-sided commands are fully executed on the client,\n * so players can use them in both singleplayer and multiplayer.\n *",
"score": 23.283421107114386
}
] | java | LiteralArgumentBuilder<FabricClientCommandSource> help = ClientCommandManager.literal("help"); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence() | ) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence"); |
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/RaceType.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character.race;\nimport java.util.HashMap;\npublic interface RaceType {\n\tString getName();\n\tint getSubRace();\n\tHashMap getAbilityScoreIncrease(int subRace);\n\tint getSize();\n\tint getSpeed();\n\tint getDarkvision();\n}",
"score": 35.88030512833637
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/Gnome.java",
"retrieved_chunk": "\t}\n\t@Override\n\tpublic HashMap getAbilityScoreIncrease(int subRace) {\n\t\tif (subRace == 2)\n\t\t\tabilityScoreIncrease.put(\"constitution\", 1);\n\t\treturn abilityScoreIncrease;\n\t}\n\t@Override\n\tpublic int getSize() {\n\t\t//size small",
"score": 33.99202979604453
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic void setDexterity(int dexterity) {\n\t\tthis.dexterity = dexterity;\n\t}\n\tpublic int getConstitution() {\n\t\treturn constitution;\n\t}\n\tpublic void setConstitution(int constitution) {\n\t\tthis.constitution = constitution;\n\t}",
"score": 33.38149465538369
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 32.35574821896709
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/Gnome.java",
"retrieved_chunk": "\t\tthis.subRace = subRace;\n\t\tabilityScoreIncrease.put(\"intelligence\", 2);\n\t}\n\t@Override\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t@Override\n\tpublic int getSubRace() {\n\t\treturn subRace;",
"score": 30.646849021587826
}
] | java | ) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence"); |
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package team.teampotato.minegpt.forge.forged.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Iterables;
import com.mojang.brigadier.AmbiguityConsumer;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.ParseResults;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.context.ParsedCommandNode;
import com.mojang.brigadier.exceptions.BuiltInExceptionProvider;
import com.mojang.brigadier.exceptions.CommandExceptionType;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.tree.CommandNode;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraft.client.MinecraftClient;
import net.minecraft.command.CommandException;
import net.minecraft.text.Text;
import net.minecraft.text.Texts;
import team.teampotato.minegpt.forge.forged.api.ClientCommandManager;
import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;
import team.teampotato.minegpt.forge.forged.mixin.HelpCommandAccessor;
@OnlyIn(Dist.CLIENT)
public final class ClientCommandInternals {
private static final Logger LOGGER = LoggerFactory.getLogger(ClientCommandInternals.class);
private static final String API_COMMAND_NAME = "fabric-command-api-v2:client";
private static final String SHORT_API_COMMAND_NAME = "fcc";
private static @Nullable CommandDispatcher<FabricClientCommandSource> activeDispatcher;
public static void setActiveDispatcher(@Nullable CommandDispatcher<FabricClientCommandSource> dispatcher) {
ClientCommandInternals.activeDispatcher = dispatcher;
}
public static @Nullable CommandDispatcher<FabricClientCommandSource> getActiveDispatcher() {
return activeDispatcher;
}
/**
* Executes a client-sided command. Callers should ensure that this is only called
* on slash-prefixed messages and the slash needs to be removed before calling.
* (This is the same requirement as {@code ClientPlayerEntity#sendCommand}.)
*
* @param command the command with slash removed
* @return true if the command should not be sent to the server, false otherwise
*/
public static boolean executeCommand(String command) {
MinecraftClient client = MinecraftClient.getInstance();
// The interface is implemented on ClientCommandSource with a mixin.
// noinspection ConstantConditions
FabricClientCommandSource commandSource = (FabricClientCommandSource) client.getNetworkHandler().getCommandSource();
client.getProfiler().push(command);
try {
// TODO: Check for server commands before executing.
// This requires parsing the command, checking if they match a server command
// and then executing the command with the parse results.
activeDispatcher.execute(command, commandSource);
return true;
} catch (CommandSyntaxException e) {
boolean ignored = isIgnoredException(e.getType());
if (ignored) {
LOGGER.debug("Syntax exception for client-sided command '{}'", command, e);
return false;
}
LOGGER.warn("Syntax exception for client-sided command '{}'", command, e);
commandSource.sendError(getErrorMessage(e));
return true;
} catch (CommandException e) {
LOGGER.warn("Error while executing client-sided command '{}'", command, e);
commandSource.sendError(e.getTextMessage());
return true;
} catch (RuntimeException e) {
LOGGER.warn("Error while executing client-sided command '{}'", command, e);
commandSource.sendError(Text.of(e.getMessage()));
return true;
} finally {
client.getProfiler().pop();
}
}
/**
* Tests whether a command syntax exception with the type
* should be ignored and the command sent to the server.
*
* @param type the exception type
* @return true if ignored, false otherwise
*/
private static boolean isIgnoredException(CommandExceptionType type) {
BuiltInExceptionProvider builtins = CommandSyntaxException.BUILT_IN_EXCEPTIONS;
// Only ignore unknown commands and node parse exceptions.
// The argument-related dispatcher exceptions are not ignored because
// they will only happen if the user enters a correct command.
return type == builtins.dispatcherUnknownCommand() || type == builtins.dispatcherParseException();
}
// See ChatInputSuggestor.formatException. That cannot be used directly as it returns an OrderedText instead of a Text.
private static Text getErrorMessage(CommandSyntaxException e) {
Text message = Texts.toText(e.getRawMessage());
String context = e.getContext();
return context != null ? Text.translatable("command.context.parse_error", message, context) : message;
}
/**
* Runs final initialization tasks such as {@link CommandDispatcher#findAmbiguities(AmbiguityConsumer)}
* on the command dispatcher. Also registers a {@code /fcc help} command if there are other commands present.
*/
public static void finalizeInit() {
if (!activeDispatcher.getRoot().getChildren().isEmpty()) {
// Register an API command if there are other commands;
// these helpers are not needed if there are no client commands
LiteralArgumentBuilder<FabricClientCommandSource> help = ClientCommandManager.literal("help");
help.executes(ClientCommandInternals::executeRootHelp);
help.then(ClientCommandManager.argument("command", StringArgumentType.greedyString()).executes(ClientCommandInternals::executeArgumentHelp));
CommandNode<FabricClientCommandSource> mainNode = activeDispatcher.register(ClientCommandManager.literal(API_COMMAND_NAME).then(help));
activeDispatcher.register(ClientCommandManager.literal(SHORT_API_COMMAND_NAME).redirect(mainNode));
}
// noinspection CodeBlock2Expr
activeDispatcher.findAmbiguities((parent, child, sibling, inputs) -> {
LOGGER.warn("Ambiguity between arguments {} and {} with inputs: {}", activeDispatcher.getPath(child), activeDispatcher.getPath(sibling), inputs);
});
}
private static int executeRootHelp(CommandContext<FabricClientCommandSource> context) {
return executeHelp(activeDispatcher.getRoot(), context);
}
private static int executeArgumentHelp(CommandContext<FabricClientCommandSource> context) throws CommandSyntaxException {
ParseResults<FabricClientCommandSource> parseResults = activeDispatcher.parse(StringArgumentType.getString(context, "command"), context.getSource());
List<ParsedCommandNode<FabricClientCommandSource>> nodes = parseResults.getContext().getNodes();
if (nodes.isEmpty()) {
throw | HelpCommandAccessor.getFailedException().create(); |
}
return executeHelp(Iterables.getLast(nodes).getNode(), context);
}
private static int executeHelp(CommandNode<FabricClientCommandSource> startNode, CommandContext<FabricClientCommandSource> context) {
Map<CommandNode<FabricClientCommandSource>, String> commands = activeDispatcher.getSmartUsage(startNode, context.getSource());
for (String command : commands.values()) {
context.getSource().sendFeedback(Text.literal("/" + command));
}
return commands.size();
}
public static void addCommands(CommandDispatcher<FabricClientCommandSource> target, FabricClientCommandSource source) {
Map<CommandNode<FabricClientCommandSource>, CommandNode<FabricClientCommandSource>> originalToCopy = new HashMap<>();
originalToCopy.put(activeDispatcher.getRoot(), target.getRoot());
copyChildren(activeDispatcher.getRoot(), target.getRoot(), source, originalToCopy);
}
/**
* Copies the child commands from origin to target, filtered by {@code child.canUse(source)}.
* Mimics vanilla's CommandManager.makeTreeForSource.
*
* @param origin the source command node
* @param target the target command node
* @param source the command source
* @param originalToCopy a mutable map from original command nodes to their copies, used for redirects;
* should contain a mapping from origin to target
*/
private static void copyChildren(
CommandNode<FabricClientCommandSource> origin,
CommandNode<FabricClientCommandSource> target,
FabricClientCommandSource source,
Map<CommandNode<FabricClientCommandSource>, CommandNode<FabricClientCommandSource>> originalToCopy
) {
for (CommandNode<FabricClientCommandSource> child : origin.getChildren()) {
if (!child.canUse(source)) continue;
ArgumentBuilder<FabricClientCommandSource, ?> builder = child.createBuilder();
// Reset the unnecessary non-completion stuff from the builder
builder.requires(s -> true); // This is checked with the if check above.
if (builder.getCommand() != null) {
builder.executes(context -> 0);
}
// Set up redirects
if (builder.getRedirect() != null) {
builder.redirect(originalToCopy.get(builder.getRedirect()));
}
CommandNode<FabricClientCommandSource> result = builder.build();
originalToCopy.put(child, result);
target.addChild(result);
if (!child.getChildren().isEmpty()) {
copyChildren(child, result, source, originalToCopy);
}
}
}
}
| forge/src/main/java/team/teampotato/minegpt/forge/forged/impl/ClientCommandInternals.java | MCTeamPotato-MineGPT-00b1415 | [
{
"filename": "common/src/main/java/team/teampotato/minegpt/command/ServerCommand.java",
"retrieved_chunk": "import java.util.Objects;\nimport java.util.concurrent.CompletableFuture;\npublic class ServerCommand {\n public static void registerCommand(CommandDispatcher<ServerCommandSource> dispatcher, CommandRegistryAccess registry, CommandManager.RegistrationEnvironment selection) {\n if (selection.dedicated) {\n dispatcher.register(CommandManager.literal(\"chatgpt\")\n .then(CommandManager.argument(\"message\", StringArgumentType.string())\n .executes(context -> {\n try {\n String message = StringArgumentType.getString(context, \"message\");",
"score": 23.874701815698334
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/command/ClientConfigCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\nimport team.teampotato.minegpt.screen.PingScreen;\n@OnlyIn(Dist.CLIENT)\npublic class ClientConfigCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 23.560768121779073
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/command/ClientCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.forge.forged.api.FabricClientCommandSource;\nimport team.teampotato.minegpt.screen.PingScreen;\n@OnlyIn(Dist.CLIENT)\npublic class ClientCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 23.560768121779073
},
{
"filename": "forge/src/main/java/team/teampotato/minegpt/forge/forged/mixin/HelpCommandAccessor.java",
"retrieved_chunk": "@Mixin(HelpCommand.class)\npublic interface HelpCommandAccessor {\n @Accessor(\"FAILED_EXCEPTION\")\n static SimpleCommandExceptionType getFailedException() {\n throw new AssertionError(\"mixin\");\n }\n}",
"score": 21.19118074009793
},
{
"filename": "fabric/src/main/java/team/teampotato/minegpt/fabric/command/ClientConfigCommand.java",
"retrieved_chunk": "import team.teampotato.minegpt.config.Config;\nimport team.teampotato.minegpt.screen.PingScreen;\n@Environment(EnvType.CLIENT)\npublic class ClientConfigCommand {\n public static void registerCommand(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registry) {\n dispatcher.register(ClientCommandManager.literal(\"mgpt\")\n .then(ClientCommandManager.literal(\"help\")\n .executes(context -> {\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.1\").formatted(Formatting.GREEN));\n context.getSource().sendFeedback(Text.translatable(\"minegpt.client.command.help.2\").formatted(Formatting.GREEN));",
"score": 21.122258221111817
}
] | java | HelpCommandAccessor.getFailedException().create(); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return | type.getSubRace(); |
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.wisdom = wisdom;\n\t}\n\tpublic int getCharisma() {\n\t\treturn charisma;\n\t}\n\tpublic void setCharisma(int charisma) {\n\t\tthis.charisma = charisma;\n\t}\n}",
"score": 28.86356241212955
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/Gnome.java",
"retrieved_chunk": "\t\tthis.subRace = subRace;\n\t\tabilityScoreIncrease.put(\"intelligence\", 2);\n\t}\n\t@Override\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t@Override\n\tpublic int getSubRace() {\n\t\treturn subRace;",
"score": 26.142343355760833
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/RaceType.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character.race;\nimport java.util.HashMap;\npublic interface RaceType {\n\tString getName();\n\tint getSubRace();\n\tHashMap getAbilityScoreIncrease(int subRace);\n\tint getSize();\n\tint getSpeed();\n\tint getDarkvision();\n}",
"score": 22.46067890376146
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 13.924243202105982
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character;\npublic class CharStats {\n\tprivate int strength;\n\tprivate int dexterity;\n\tprivate int constitution;\n\tprivate int intelligence;\n\tprivate int wisdom;\n\tprivate int charisma;\n\tprivate int level;\n\tpublic CharStats(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level) {",
"score": 13.70541283117388
}
] | java | type.getSubRace(); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease( | type.getSubRace()).containsKey("strength")){ |
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 31.57682844674813
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic int getSavingThrow(int stat, boolean proficient){\n\t\tif (proficient){\n\t\t\treturn getModifier(stat) + getProficiencyBonus(level);\n\t\t}\n\t\treturn getModifier(stat);\n\t}\n\tpublic int getProficiencyBonus(int lvl){\n\t\t//floor(lvl-1)+2\n\t\t//https://roll20.net/compendium/dnd5e/Character%20Advancement#content",
"score": 27.24203125432239
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\treturn (int) (Math.floor(lvl-1)+2);\n\t}\n\tpublic int getStrength() {\n\t\treturn strength;\n\t}\n\tpublic void setStrength(int strength) {\n\t\tthis.strength = strength;\n\t}\n\tpublic int getDexterity() {\n\t\treturn dexterity;",
"score": 26.344396210460626
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/RaceType.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character.race;\nimport java.util.HashMap;\npublic interface RaceType {\n\tString getName();\n\tint getSubRace();\n\tHashMap getAbilityScoreIncrease(int subRace);\n\tint getSize();\n\tint getSpeed();\n\tint getDarkvision();\n}",
"score": 14.597716628372517
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/Gnome.java",
"retrieved_chunk": "\t\tthis.subRace = subRace;\n\t\tabilityScoreIncrease.put(\"intelligence\", 2);\n\t}\n\t@Override\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t@Override\n\tpublic int getSubRace() {\n\t\treturn subRace;",
"score": 13.00838944297399
}
] | java | type.getSubRace()).containsKey("strength")){ |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats. | getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength"); |
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 34.062660169255665
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\treturn (int) (Math.floor(lvl-1)+2);\n\t}\n\tpublic int getStrength() {\n\t\treturn strength;\n\t}\n\tpublic void setStrength(int strength) {\n\t\tthis.strength = strength;\n\t}\n\tpublic int getDexterity() {\n\t\treturn dexterity;",
"score": 33.17985161366719
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic int getSavingThrow(int stat, boolean proficient){\n\t\tif (proficient){\n\t\t\treturn getModifier(stat) + getProficiencyBonus(level);\n\t\t}\n\t\treturn getModifier(stat);\n\t}\n\tpublic int getProficiencyBonus(int lvl){\n\t\t//floor(lvl-1)+2\n\t\t//https://roll20.net/compendium/dnd5e/Character%20Advancement#content",
"score": 28.64756082615768
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/RaceType.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character.race;\nimport java.util.HashMap;\npublic interface RaceType {\n\tString getName();\n\tint getSubRace();\n\tHashMap getAbilityScoreIncrease(int subRace);\n\tint getSize();\n\tint getSpeed();\n\tint getDarkvision();\n}",
"score": 23.137915671414458
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character;\npublic class CharStats {\n\tprivate int strength;\n\tprivate int dexterity;\n\tprivate int constitution;\n\tprivate int intelligence;\n\tprivate int wisdom;\n\tprivate int charisma;\n\tprivate int level;\n\tpublic CharStats(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level) {",
"score": 18.03551584974556
}
] | java | getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength"); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return | type.getSpeed(); |
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/RaceType.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character.race;\nimport java.util.HashMap;\npublic interface RaceType {\n\tString getName();\n\tint getSubRace();\n\tHashMap getAbilityScoreIncrease(int subRace);\n\tint getSize();\n\tint getSpeed();\n\tint getDarkvision();\n}",
"score": 28.199860563378728
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/Gnome.java",
"retrieved_chunk": "\t\treturn 1;\n\t}\n\t@Override\n\tpublic int getSpeed() {\n\t\t//walking speed 25 feet\n\t\treturn 25;\n\t}\n\t@Override\n\tpublic int getDarkvision() {\n\t\t//darkvision 60 feet",
"score": 17.701352520128708
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/Gnome.java",
"retrieved_chunk": "\t\tthis.subRace = subRace;\n\t\tabilityScoreIncrease.put(\"intelligence\", 2);\n\t}\n\t@Override\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t@Override\n\tpublic int getSubRace() {\n\t\treturn subRace;",
"score": 16.748771934471662
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/Gnome.java",
"retrieved_chunk": "\t}\n\t@Override\n\tpublic HashMap getAbilityScoreIncrease(int subRace) {\n\t\tif (subRace == 2)\n\t\t\tabilityScoreIncrease.put(\"constitution\", 1);\n\t\treturn abilityScoreIncrease;\n\t}\n\t@Override\n\tpublic int getSize() {\n\t\t//size small",
"score": 16.73477415064658
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\tpublic int getIntelligence() {\n\t\treturn intelligence;\n\t}\n\tpublic void setIntelligence(int intelligence) {\n\t\tthis.intelligence = intelligence;\n\t}\n\tpublic int getWisdom() {\n\t\treturn wisdom;\n\t}\n\tpublic void setWisdom(int wisdom) {",
"score": 11.002656757479624
}
] | java | type.getSpeed(); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return | stats.getModifier(stats.getCharisma()); |
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.wisdom = wisdom;\n\t}\n\tpublic int getCharisma() {\n\t\treturn charisma;\n\t}\n\tpublic void setCharisma(int charisma) {\n\t\tthis.charisma = charisma;\n\t}\n}",
"score": 40.20873694914205
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 36.65959619434465
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/RaceType.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character.race;\nimport java.util.HashMap;\npublic interface RaceType {\n\tString getName();\n\tint getSubRace();\n\tHashMap getAbilityScoreIncrease(int subRace);\n\tint getSize();\n\tint getSpeed();\n\tint getDarkvision();\n}",
"score": 31.08681368069316
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic int getSavingThrow(int stat, boolean proficient){\n\t\tif (proficient){\n\t\t\treturn getModifier(stat) + getProficiencyBonus(level);\n\t\t}\n\t\treturn getModifier(stat);\n\t}\n\tpublic int getProficiencyBonus(int lvl){\n\t\t//floor(lvl-1)+2\n\t\t//https://roll20.net/compendium/dnd5e/Character%20Advancement#content",
"score": 26.195501746456888
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/Gnome.java",
"retrieved_chunk": "\t}\n\t@Override\n\tpublic HashMap getAbilityScoreIncrease(int subRace) {\n\t\tif (subRace == 2)\n\t\t\tabilityScoreIncrease.put(\"constitution\", 1);\n\t\treturn abilityScoreIncrease;\n\t}\n\t@Override\n\tpublic int getSize() {\n\t\t//size small",
"score": 23.334563078323264
}
] | java | stats.getModifier(stats.getCharisma()); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return | stats.getModifier(stats.getStrength()); |
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 35.62421942763705
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\treturn (int) (Math.floor(lvl-1)+2);\n\t}\n\tpublic int getStrength() {\n\t\treturn strength;\n\t}\n\tpublic void setStrength(int strength) {\n\t\tthis.strength = strength;\n\t}\n\tpublic int getDexterity() {\n\t\treturn dexterity;",
"score": 35.27543693554353
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic int getSavingThrow(int stat, boolean proficient){\n\t\tif (proficient){\n\t\t\treturn getModifier(stat) + getProficiencyBonus(level);\n\t\t}\n\t\treturn getModifier(stat);\n\t}\n\tpublic int getProficiencyBonus(int lvl){\n\t\t//floor(lvl-1)+2\n\t\t//https://roll20.net/compendium/dnd5e/Character%20Advancement#content",
"score": 31.252962724890164
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/RaceType.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character.race;\nimport java.util.HashMap;\npublic interface RaceType {\n\tString getName();\n\tint getSubRace();\n\tHashMap getAbilityScoreIncrease(int subRace);\n\tint getSize();\n\tint getSpeed();\n\tint getDarkvision();\n}",
"score": 20.741169947592855
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/Gnome.java",
"retrieved_chunk": "\t\tthis.subRace = subRace;\n\t\tabilityScoreIncrease.put(\"intelligence\", 2);\n\t}\n\t@Override\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t@Override\n\tpublic int getSubRace() {\n\t\treturn subRace;",
"score": 16.363801959545988
}
] | java | stats.getModifier(stats.getStrength()); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
| return stats.getSavingThrow(stats.getStrength(), true); |
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic int getSavingThrow(int stat, boolean proficient){\n\t\tif (proficient){\n\t\t\treturn getModifier(stat) + getProficiencyBonus(level);\n\t\t}\n\t\treturn getModifier(stat);\n\t}\n\tpublic int getProficiencyBonus(int lvl){\n\t\t//floor(lvl-1)+2\n\t\t//https://roll20.net/compendium/dnd5e/Character%20Advancement#content",
"score": 36.69738593235347
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 34.48967377558415
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.wisdom = wisdom;\n\t}\n\tpublic int getCharisma() {\n\t\treturn charisma;\n\t}\n\tpublic void setCharisma(int charisma) {\n\t\tthis.charisma = charisma;\n\t}\n}",
"score": 34.17262423571634
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/race/RaceType.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character.race;\nimport java.util.HashMap;\npublic interface RaceType {\n\tString getName();\n\tint getSubRace();\n\tHashMap getAbilityScoreIncrease(int subRace);\n\tint getSize();\n\tint getSpeed();\n\tint getDarkvision();\n}",
"score": 23.137915671414458
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\treturn (int) (Math.floor(lvl-1)+2);\n\t}\n\tpublic int getStrength() {\n\t\treturn strength;\n\t}\n\tpublic void setStrength(int strength) {\n\t\tthis.strength = strength;\n\t}\n\tpublic int getDexterity() {\n\t\treturn dexterity;",
"score": 19.003325100387123
}
] | java | return stats.getSavingThrow(stats.getStrength(), true); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow( | stats.getCharisma(), false); |
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic int getSavingThrow(int stat, boolean proficient){\n\t\tif (proficient){\n\t\t\treturn getModifier(stat) + getProficiencyBonus(level);\n\t\t}\n\t\treturn getModifier(stat);\n\t}\n\tpublic int getProficiencyBonus(int lvl){\n\t\t//floor(lvl-1)+2\n\t\t//https://roll20.net/compendium/dnd5e/Character%20Advancement#content",
"score": 21.620659002105512
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\tpublic int getIntelligence() {\n\t\treturn intelligence;\n\t}\n\tpublic void setIntelligence(int intelligence) {\n\t\tthis.intelligence = intelligence;\n\t}\n\tpublic int getWisdom() {\n\t\treturn wisdom;\n\t}\n\tpublic void setWisdom(int wisdom) {",
"score": 20.921804468943414
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.wisdom = wisdom;\n\t}\n\tpublic int getCharisma() {\n\t\treturn charisma;\n\t}\n\tpublic void setCharisma(int charisma) {\n\t\tthis.charisma = charisma;\n\t}\n}",
"score": 17.58933356289516
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 17.13556257266872
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character;\npublic class CharStats {\n\tprivate int strength;\n\tprivate int dexterity;\n\tprivate int constitution;\n\tprivate int intelligence;\n\tprivate int wisdom;\n\tprivate int charisma;\n\tprivate int level;\n\tpublic CharStats(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level) {",
"score": 13.504743222895314
}
] | java | stats.getCharisma(), false); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
| return stats.getSavingThrow(stats.getDexterity(), false); |
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow(stats.getIntelligence(), true);
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic int getSavingThrow(int stat, boolean proficient){\n\t\tif (proficient){\n\t\t\treturn getModifier(stat) + getProficiencyBonus(level);\n\t\t}\n\t\treturn getModifier(stat);\n\t}\n\tpublic int getProficiencyBonus(int lvl){\n\t\t//floor(lvl-1)+2\n\t\t//https://roll20.net/compendium/dnd5e/Character%20Advancement#content",
"score": 37.05617989283976
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 32.42927929623317
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\treturn (int) (Math.floor(lvl-1)+2);\n\t}\n\tpublic int getStrength() {\n\t\treturn strength;\n\t}\n\tpublic void setStrength(int strength) {\n\t\tthis.strength = strength;\n\t}\n\tpublic int getDexterity() {\n\t\treturn dexterity;",
"score": 23.981565498270363
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.wisdom = wisdom;\n\t}\n\tpublic int getCharisma() {\n\t\treturn charisma;\n\t}\n\tpublic void setCharisma(int charisma) {\n\t\tthis.charisma = charisma;\n\t}\n}",
"score": 21.54818957858308
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character;\npublic class CharStats {\n\tprivate int strength;\n\tprivate int dexterity;\n\tprivate int constitution;\n\tprivate int intelligence;\n\tprivate int wisdom;\n\tprivate int charisma;\n\tprivate int level;\n\tpublic CharStats(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level) {",
"score": 14.974713266142608
}
] | java | return stats.getSavingThrow(stats.getDexterity(), false); |
package net.mexicanminion.dndminecraft.character;
import net.mexicanminion.dndminecraft.character.race.Gnome;
import net.mexicanminion.dndminecraft.character.race.RaceType;
public class PlayerChar {
CharStats stats;
RaceType type;
public PlayerChar(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level, int race, String name, int subRace) {
stats = new CharStats(strength, dexterity, constitution, intelligence, wisdom, charisma, level);
if (race == 1){
type = new Gnome(name, subRace);
}
}
public int getAC(){
return 10 + stats.getModifier(stats.getDexterity());
}
public int getInitiative(){
return stats.getModifier(stats.getDexterity());
}
public int getAblityScoreModifier(String stat){
switch (stat){
case "strength":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
case "dexterity":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
case "constitution":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
case "intelligence":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
case "wisdom":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
case "charisma":
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
default:
return 0;
}
}
public int getStrength() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("strength")){
return stats.getModifier(stats.getStrength()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("strength");
}
return stats.getModifier(stats.getStrength());
}
public int getDexterity() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("dexterity")){
return stats.getModifier(stats.getDexterity()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("dexterity");
}
return stats.getModifier(stats.getDexterity());
}
public int getConstitution() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("constitution")){
return stats.getModifier(stats.getConstitution()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("constitution");
}
return stats.getModifier(stats.getConstitution());
}
public int getIntelligence() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("intelligence")){
return stats.getModifier(stats.getIntelligence()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("intelligence");
}
return stats.getModifier(stats.getIntelligence());
}
public int getWisdom() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("wisdom")){
return stats.getModifier(stats.getWisdom()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("wisdom");
}
return stats.getModifier(stats.getWisdom());
}
public int getCharisma() {
if (type.getAbilityScoreIncrease(type.getSubRace()).containsKey("charisma")){
return stats.getModifier(stats.getCharisma()) + (int) type.getAbilityScoreIncrease(type.getSubRace()).get("charisma");
}
return stats.getModifier(stats.getCharisma());
}
public int getSavingThrow(String stat){
switch (stat.toLowerCase()){
case "strength":
return stats.getSavingThrow(stats.getStrength(), true);
case "dexterity":
return stats.getSavingThrow(stats.getDexterity(), false);
case "constitution":
return stats.getSavingThrow(stats.getConstitution(), false);
case "intelligence":
return stats.getSavingThrow | (stats.getIntelligence(), true); |
case "wisdom":
return stats.getSavingThrow(stats.getWisdom(), true);
case "charisma":
return stats.getSavingThrow(stats.getCharisma(), false);
default:
return -1;
}
}
public void setStrength(int strength) {
stats.setStrength(strength);
}
public void setDexterity(int dexterity) {
stats.setDexterity(dexterity);
}
public void setConstitution(int constitution) {
stats.setConstitution(constitution);
}
public void setIntelligence(int intelligence) {
stats.setIntelligence(intelligence);
}
public void setWisdom(int wisdom) {
stats.setWisdom(wisdom);
}
public void setCharisma(int charisma) {
stats.setCharisma(charisma);
}
public String getName(){
return type.getName();
}
public int getSubRace(){
return type.getSubRace();
}
public int getSize(){
return type.getSize();
}
public int getSpeed(){
return type.getSpeed();
}
public int getDarkvision(){
return type.getDarkvision();
}
}
| src/main/java/net/mexicanminion/dndminecraft/character/PlayerChar.java | mexicanminion-DND_Minecraft-5e7753b | [
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic int getSavingThrow(int stat, boolean proficient){\n\t\tif (proficient){\n\t\t\treturn getModifier(stat) + getProficiencyBonus(level);\n\t\t}\n\t\treturn getModifier(stat);\n\t}\n\tpublic int getProficiencyBonus(int lvl){\n\t\t//floor(lvl-1)+2\n\t\t//https://roll20.net/compendium/dnd5e/Character%20Advancement#content",
"score": 22.555352514155654
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\tthis.strength = strength;\n\t\tthis.dexterity = dexterity;\n\t\tthis.constitution = constitution;\n\t\tthis.intelligence = intelligence;\n\t\tthis.wisdom = wisdom;\n\t\tthis.charisma = charisma;\n\t\tthis.level = level;\n\t}\n\tpublic int getModifier(int stat){\n\t\treturn (int) Math.floor((stat - 10) / 2);",
"score": 21.27333877183989
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t\treturn (int) (Math.floor(lvl-1)+2);\n\t}\n\tpublic int getStrength() {\n\t\treturn strength;\n\t}\n\tpublic void setStrength(int strength) {\n\t\tthis.strength = strength;\n\t}\n\tpublic int getDexterity() {\n\t\treturn dexterity;",
"score": 19.636847223628262
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "\t}\n\tpublic void setDexterity(int dexterity) {\n\t\tthis.dexterity = dexterity;\n\t}\n\tpublic int getConstitution() {\n\t\treturn constitution;\n\t}\n\tpublic void setConstitution(int constitution) {\n\t\tthis.constitution = constitution;\n\t}",
"score": 16.085761861626693
},
{
"filename": "src/main/java/net/mexicanminion/dndminecraft/character/CharStats.java",
"retrieved_chunk": "package net.mexicanminion.dndminecraft.character;\npublic class CharStats {\n\tprivate int strength;\n\tprivate int dexterity;\n\tprivate int constitution;\n\tprivate int intelligence;\n\tprivate int wisdom;\n\tprivate int charisma;\n\tprivate int level;\n\tpublic CharStats(int strength, int dexterity, int constitution, int intelligence, int wisdom, int charisma, int level) {",
"score": 13.504743222895318
}
] | java | (stats.getIntelligence(), true); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend( | readResult, "selectApdu with AID: " + Utils.bytesToHex(command)); |
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " (byte) 0xe1, (byte) 0x03 // file identifier of the CC file\n };\n private static final byte[] SELECT_NDEF_FILE = {\n (byte) 0x00, // CLA\t- Class - Class of instruction\n (byte) 0xa4, // Instruction byte (INS) for Select command\n (byte) 0x00, // Parameter byte (P1), select by identifier\n (byte) 0x0c, // Parameter byte (P1), select by identifier\n (byte) 0x02, // Lc field\t- Number of bytes present in the data field of the command\n (byte) 0xE1, (byte) 0x04 // file identifier of the NDEF file retrieved from the CC file\n };",
"score": 24.355498417413326
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " (byte) 0x07, // Lc field\t- Number of bytes present in the data field of the command\n (byte) 0xD2, (byte) 0x76, (byte) 0x00, (byte) 0x00, (byte) 0x85, (byte) 0x01, (byte) 0x01, // NDEF Tag Application name D2 76 00 00 85 01 01\n (byte) 0x00 // Le field\t- Maximum number of bytes expected in the data field of the response to the command\n };\n private static final byte[] SELECT_CAPABILITY_CONTAINER = {\n (byte) 0x00, // CLA\t- Class - Class of instruction\n (byte) 0xa4, // INS\t- Instruction - Instruction code\n (byte) 0x00, // P1\t- Parameter 1 - Instruction parameter 1\n (byte) 0x0c, // P2\t- Parameter 2 - Instruction parameter 2\n (byte) 0x02, // Lc field\t- Number of bytes present in the data field of the command",
"score": 20.246740543994648
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " System.arraycopy(ndefPayload, 1, message, 0, ndefPayloadLength - 1);\n return URI_PREFIX_MAP[uriPrefix] + new String(message, StandardCharsets.UTF_8);\n }\n private static final byte[] SW_9000 = {\n (byte)0x90, // SW1\tStatus byte 1 - Command processing status\n (byte)0x00 // SW2\tStatus byte 2 - Command processing qualifier\n };\n /**\n * Method used to check if the last command return SW1SW2 == 9000\n *",
"score": 17.519412338420352
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " short ndefTnf = record[i].getTnf();\n byte[] ndefType = record[i].getType();\n byte[] ndefPayload = record[i].getPayload();\n // here we are trying to parse the content\n // Well known type - Text\n if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&\n Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {\n ndefText = ndefText + \"\\n\" + \"rec: \" + i +\n \" Well known Text payload\\n\" + new String(ndefPayload) + \" \\n\";\n ndefText = ndefText + Utils.parseTextrecordPayload(ndefPayload) + \" \\n\";",
"score": 16.939308519801592
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " * @param pByte\n * response to the last command\n * @return true if the status is 9000 false otherwise\n */\n public static boolean isSucceed(final byte[] pByte) {\n byte[] resultValue = Arrays.copyOfRange(pByte, pByte.length - 2, pByte.length);\n if (Arrays.equals(resultValue, SW_9000)) {\n return true;\n } else {\n return false;",
"score": 16.24419436944829
}
] | java | readResult, "selectApdu with AID: " + Utils.bytesToHex(command)); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
| writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command)); |
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " (byte) 0xe1, (byte) 0x03 // file identifier of the CC file\n };\n private static final byte[] SELECT_NDEF_FILE = {\n (byte) 0x00, // CLA\t- Class - Class of instruction\n (byte) 0xa4, // Instruction byte (INS) for Select command\n (byte) 0x00, // Parameter byte (P1), select by identifier\n (byte) 0x0c, // Parameter byte (P1), select by identifier\n (byte) 0x02, // Lc field\t- Number of bytes present in the data field of the command\n (byte) 0xE1, (byte) 0x04 // file identifier of the NDEF file retrieved from the CC file\n };",
"score": 27.995445625511604
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 23.479033773023794
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " (byte) 0x07, // Lc field\t- Number of bytes present in the data field of the command\n (byte) 0xD2, (byte) 0x76, (byte) 0x00, (byte) 0x00, (byte) 0x85, (byte) 0x01, (byte) 0x01, // NDEF Tag Application name D2 76 00 00 85 01 01\n (byte) 0x00 // Le field\t- Maximum number of bytes expected in the data field of the response to the command\n };\n private static final byte[] SELECT_CAPABILITY_CONTAINER = {\n (byte) 0x00, // CLA\t- Class - Class of instruction\n (byte) 0xa4, // INS\t- Instruction - Instruction code\n (byte) 0x00, // P1\t- Parameter 1 - Instruction parameter 1\n (byte) 0x0c, // P2\t- Parameter 2 - Instruction parameter 2\n (byte) 0x02, // Lc field\t- Number of bytes present in the data field of the command",
"score": 22.14369296864291
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " * @param pByte\n * response to the last command\n * @return true if the status is 9000 false otherwise\n */\n public static boolean isSucceed(final byte[] pByte) {\n byte[] resultValue = Arrays.copyOfRange(pByte, pByte.length - 2, pByte.length);\n if (Arrays.equals(resultValue, SW_9000)) {\n return true;\n } else {\n return false;",
"score": 21.331871852395327
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " //doVibrate();\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n // Inflate the layout for this fragment\n return inflater.inflate(R.layout.fragment_receive, container, false);\n }\n // This method is running in another thread when a card is discovered\n // !!!! This method cannot cannot direct interact with the UI Thread",
"score": 19.95008771564751
}
] | java | writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command)); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend( | readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect)); |
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " (byte) 0xe1, (byte) 0x03 // file identifier of the CC file\n };\n private static final byte[] SELECT_NDEF_FILE = {\n (byte) 0x00, // CLA\t- Class - Class of instruction\n (byte) 0xa4, // Instruction byte (INS) for Select command\n (byte) 0x00, // Parameter byte (P1), select by identifier\n (byte) 0x0c, // Parameter byte (P1), select by identifier\n (byte) 0x02, // Lc field\t- Number of bytes present in the data field of the command\n (byte) 0xE1, (byte) 0x04 // file identifier of the NDEF file retrieved from the CC file\n };",
"score": 24.355498417413326
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " (byte) 0x07, // Lc field\t- Number of bytes present in the data field of the command\n (byte) 0xD2, (byte) 0x76, (byte) 0x00, (byte) 0x00, (byte) 0x85, (byte) 0x01, (byte) 0x01, // NDEF Tag Application name D2 76 00 00 85 01 01\n (byte) 0x00 // Le field\t- Maximum number of bytes expected in the data field of the response to the command\n };\n private static final byte[] SELECT_CAPABILITY_CONTAINER = {\n (byte) 0x00, // CLA\t- Class - Class of instruction\n (byte) 0xa4, // INS\t- Instruction - Instruction code\n (byte) 0x00, // P1\t- Parameter 1 - Instruction parameter 1\n (byte) 0x0c, // P2\t- Parameter 2 - Instruction parameter 2\n (byte) 0x02, // Lc field\t- Number of bytes present in the data field of the command",
"score": 22.411514260141622
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " * @param pByte\n * response to the last command\n * @return true if the status is 9000 false otherwise\n */\n public static boolean isSucceed(final byte[] pByte) {\n byte[] resultValue = Arrays.copyOfRange(pByte, pByte.length - 2, pByte.length);\n if (Arrays.equals(resultValue, SW_9000)) {\n return true;\n } else {\n return false;",
"score": 19.95190674938032
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " String finalNdefText = ndefText;\n getActivity().runOnUiThread(() -> {\n readResult.setText(finalNdefText);\n });\n }\n }\n } else {\n getActivity().runOnUiThread(() -> {\n readResult.setText(\"There was an error in NDEF data\");\n });",
"score": 19.2532696544097
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " short ndefTnf = record[i].getTnf();\n byte[] ndefType = record[i].getType();\n byte[] ndefPayload = record[i].getPayload();\n // here we are trying to parse the content\n // Well known type - Text\n if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&\n Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {\n ndefText = ndefText + \"\\n\" + \"rec: \" + i +\n \" Well known Text payload\\n\" + new String(ndefPayload) + \" \\n\";\n ndefText = ndefText + Utils.parseTextrecordPayload(ndefPayload) + \" \\n\";",
"score": 19.010479666343677
}
] | java | readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect)); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println | ("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc)); |
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 40.06301487690361
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " if (mCcSelected && offset == 0 && le == CAPABILITY_CONTAINER_FILE.length) {\n System.arraycopy(CAPABILITY_CONTAINER_FILE, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));\n return responseApdu;\n } else if (mNdefSelected) {\n if (offset + le <= mNdefRecordFile.length) {\n System.arraycopy(mNdefRecordFile, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));",
"score": 37.52074390270148
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"commandApdu: \" + Utils.bytesToHex(commandApdu)); \n //if (Arrays.equals(SELECT_APP, commandApdu)) {\n // check if commandApdu qualifies for SELECT_APPLICATION\n if (Arrays.equals(SELECT_APPLICATION, commandApdu)) {\n mAppSelected = true;\n mCcSelected = false;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_CAPABILITY_CONTAINER",
"score": 32.76432357624679
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " return responseApdu;\n }\n }\n }\n // The tag should return different errors for different reasons\n // this emulation just returns the general error message\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(FAILURE_SW));\n return FAILURE_SW;\n }\n/*",
"score": 27.358281852649366
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " * @param pByte\n * response to the last command\n * @return true if the status is 9000 false otherwise\n */\n public static boolean isSucceed(final byte[] pByte) {\n byte[] resultValue = Arrays.copyOfRange(pByte, pByte.length - 2, pByte.length);\n if (Arrays.equals(resultValue, SW_9000)) {\n return true;\n } else {\n return false;",
"score": 26.058022570512566
}
] | java | ("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc)); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
| System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader)); |
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 52.64477343933625
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " if (mCcSelected && offset == 0 && le == CAPABILITY_CONTAINER_FILE.length) {\n System.arraycopy(CAPABILITY_CONTAINER_FILE, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));\n return responseApdu;\n } else if (mNdefSelected) {\n if (offset + le <= mNdefRecordFile.length) {\n System.arraycopy(mNdefRecordFile, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));",
"score": 43.2038425692799
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " //s1 += \" \" + b1;\n output = output + \" \" + s1;\n //System.out.println(s1);\n }\n return output;\n }\n public static byte[] convertIntToByteArray(int value, int numberOfBytes) {\n byte b[] = new byte[numberOfBytes];\n int i, shift;\n for (i = 0, shift = (b.length - 1) * 8; i < b.length; i++, shift -= 8) {",
"score": 35.91610455778747
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"commandApdu: \" + Utils.bytesToHex(commandApdu)); \n //if (Arrays.equals(SELECT_APP, commandApdu)) {\n // check if commandApdu qualifies for SELECT_APPLICATION\n if (Arrays.equals(SELECT_APPLICATION, commandApdu)) {\n mAppSelected = true;\n mCcSelected = false;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_CAPABILITY_CONTAINER",
"score": 29.86900625947536
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " * @param pByte\n * response to the last command\n * @return true if the status is 9000 false otherwise\n */\n public static boolean isSucceed(final byte[] pByte) {\n byte[] resultValue = Arrays.copyOfRange(pByte, pByte.length - 2, pByte.length);\n if (Arrays.equals(resultValue, SW_9000)) {\n return true;\n } else {\n return false;",
"score": 29.85085887835315
}
] | java | System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader)); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println | ("responseSelect: " + Utils.bytesToHex(responseSelect)); |
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 41.51564284010662
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " if (mCcSelected && offset == 0 && le == CAPABILITY_CONTAINER_FILE.length) {\n System.arraycopy(CAPABILITY_CONTAINER_FILE, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));\n return responseApdu;\n } else if (mNdefSelected) {\n if (offset + le <= mNdefRecordFile.length) {\n System.arraycopy(mNdefRecordFile, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));",
"score": 37.13594737994341
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"commandApdu: \" + Utils.bytesToHex(commandApdu)); \n //if (Arrays.equals(SELECT_APP, commandApdu)) {\n // check if commandApdu qualifies for SELECT_APPLICATION\n if (Arrays.equals(SELECT_APPLICATION, commandApdu)) {\n mAppSelected = true;\n mCcSelected = false;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_CAPABILITY_CONTAINER",
"score": 30.59250199714014
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " String finalNdefText = ndefText;\n getActivity().runOnUiThread(() -> {\n readResult.setText(finalNdefText);\n });\n }\n }\n } else {\n getActivity().runOnUiThread(() -> {\n readResult.setText(\"There was an error in NDEF data\");\n });",
"score": 27.43187132792423
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " } else if (mAppSelected && Arrays.equals(SELECT_CAPABILITY_CONTAINER, commandApdu)) {\n mCcSelected = true;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_NDEF_FILE\n } else if (mAppSelected && Arrays.equals(SELECT_NDEF_FILE, commandApdu)) {\n // NDEF\n mCcSelected = false;\n mNdefSelected = true;",
"score": 25.718311267191137
}
] | java | ("responseSelect: " + Utils.bytesToHex(responseSelect)); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult | ,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt); |
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 25.765102251702057
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " }\n public static byte[] hexStringToByteArray(String s) {\n int len = s.length();\n byte[] data = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)\n + Character.digit(s.charAt(i + 1), 16));\n }\n return data;\n }",
"score": 22.915916597353306
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " mNdefSelected = false;\n // default NDEF-message\n final String DEFAULT_MESSAGE = \"This is the default message from NfcHceNdelEmulator. If you want to change the message use the tab 'Send' to enter an individual message.\";\n NdefMessage ndefDefaultMessage = getNdefMessage(DEFAULT_MESSAGE);\n // the maximum length is 246 so do not extend this value\n int nlen = ndefDefaultMessage.getByteArrayLength();\n mNdefRecordFile = new byte[nlen + 2];\n mNdefRecordFile[0] = (byte)((nlen & 0xff00) / 256);\n mNdefRecordFile[1] = (byte)(nlen & 0xff);\n System.arraycopy(ndefDefaultMessage.toByteArray(), 0, mNdefRecordFile, 2, ndefDefaultMessage.getByteArrayLength());",
"score": 17.457388025420972
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " String finalNdefText = ndefText;\n getActivity().runOnUiThread(() -> {\n readResult.setText(finalNdefText);\n });\n }\n }\n } else {\n getActivity().runOnUiThread(() -> {\n readResult.setText(\"There was an error in NDEF data\");\n });",
"score": 16.489286205885122
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " // Use `runOnUiThread` method to change the UI from this method\n @Override\n public void onTagDiscovered(Tag tag) {\n // Read and or write to Tag here to the appropriate Tag Technology type class\n // in this example the card should be an Ndef Technology Type\n System.out.println(\"NFC tag discovered\");\n requireActivity().runOnUiThread(() -> {\n readResult.setText(\"\");\n });\n Ndef mNdef = Ndef.get(tag);",
"score": 15.495796796392488
}
] | java | ,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
| writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc)); |
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " (byte) 0xe1, (byte) 0x03 // file identifier of the CC file\n };\n private static final byte[] SELECT_NDEF_FILE = {\n (byte) 0x00, // CLA\t- Class - Class of instruction\n (byte) 0xa4, // Instruction byte (INS) for Select command\n (byte) 0x00, // Parameter byte (P1), select by identifier\n (byte) 0x0c, // Parameter byte (P1), select by identifier\n (byte) 0x02, // Lc field\t- Number of bytes present in the data field of the command\n (byte) 0xE1, (byte) 0x04 // file identifier of the NDEF file retrieved from the CC file\n };",
"score": 39.15622287478921
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 37.32165330061376
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " if (mCcSelected && offset == 0 && le == CAPABILITY_CONTAINER_FILE.length) {\n System.arraycopy(CAPABILITY_CONTAINER_FILE, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));\n return responseApdu;\n } else if (mNdefSelected) {\n if (offset + le <= mNdefRecordFile.length) {\n System.arraycopy(mNdefRecordFile, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));",
"score": 31.44944808286828
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"commandApdu: \" + Utils.bytesToHex(commandApdu)); \n //if (Arrays.equals(SELECT_APP, commandApdu)) {\n // check if commandApdu qualifies for SELECT_APPLICATION\n if (Arrays.equals(SELECT_APPLICATION, commandApdu)) {\n mAppSelected = true;\n mCcSelected = false;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_CAPABILITY_CONTAINER",
"score": 25.902561332840907
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " return responseApdu;\n }\n }\n }\n // The tag should return different errors for different reasons\n // this emulation just returns the general error message\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(FAILURE_SW));\n return FAILURE_SW;\n }\n/*",
"score": 23.240929913646035
}
] | java | writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc)); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData | = "00b000" + Utils.bytesToHex(cmdLenNew); |
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 37.58126348403758
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " }\n public static byte[] hexStringToByteArray(String s) {\n int len = s.length();\n byte[] data = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)\n + Character.digit(s.charAt(i + 1), 16));\n }\n return data;\n }",
"score": 32.467109649464376
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"commandApdu: \" + Utils.bytesToHex(commandApdu)); \n //if (Arrays.equals(SELECT_APP, commandApdu)) {\n // check if commandApdu qualifies for SELECT_APPLICATION\n if (Arrays.equals(SELECT_APPLICATION, commandApdu)) {\n mAppSelected = true;\n mCcSelected = false;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_CAPABILITY_CONTAINER",
"score": 31.559491518538117
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " if (mCcSelected && offset == 0 && le == CAPABILITY_CONTAINER_FILE.length) {\n System.arraycopy(CAPABILITY_CONTAINER_FILE, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));\n return responseApdu;\n } else if (mNdefSelected) {\n if (offset + le <= mNdefRecordFile.length) {\n System.arraycopy(mNdefRecordFile, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));",
"score": 27.328170760423873
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " } else if (mAppSelected && Arrays.equals(SELECT_CAPABILITY_CONTAINER, commandApdu)) {\n mCcSelected = true;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_NDEF_FILE\n } else if (mAppSelected && Arrays.equals(SELECT_NDEF_FILE, commandApdu)) {\n // NDEF\n mCcSelected = false;\n mNdefSelected = true;",
"score": 24.150094721266502
}
] | java | = "00b000" + Utils.bytesToHex(cmdLenNew); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[ | ] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2); |
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " }\n public static byte[] hexStringToByteArray(String s) {\n int len = s.length();\n byte[] data = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)\n + Character.digit(s.charAt(i + 1), 16));\n }\n return data;\n }",
"score": 31.157468862188757
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 27.45873869641441
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/NdefHostApduServiceOrg.java",
"retrieved_chunk": " int nlen = ndefMessage.getByteArrayLength();\n mNdefRecordFile = new byte[nlen + 2];\n mNdefRecordFile[0] = (byte)((nlen & 0xff00) / 256);\n mNdefRecordFile[1] = (byte)(nlen & 0xff);\n System.arraycopy(ndefMessage.toByteArray(), 0, mNdefRecordFile, 2, ndefMessage.getByteArrayLength());\n }\n /**\n * NFC Forum Tag Type 4として振る舞う処理を行う。\n * C-APDUを受け取り、対応するR-APDUを返す。\n */",
"score": 18.082043699287205
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/NdefHostApduService.java",
"retrieved_chunk": " int nlen = ndefDefaultMessage.getByteArrayLength();\n mNdefRecordFile = new byte[nlen + 2];\n mNdefRecordFile[0] = (byte)((nlen & 0xff00) / 256);\n mNdefRecordFile[1] = (byte)(nlen & 0xff);\n System.arraycopy(ndefDefaultMessage.toByteArray(), 0, mNdefRecordFile, 2, ndefDefaultMessage.getByteArrayLength());\n }\n private NdefMessage getNdefMessage(String ndefData) {\n if (ndefData.length() == 0) {\n return null;\n }",
"score": 18.022067284431948
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"commandApdu: \" + Utils.bytesToHex(commandApdu)); \n //if (Arrays.equals(SELECT_APP, commandApdu)) {\n // check if commandApdu qualifies for SELECT_APPLICATION\n if (Arrays.equals(SELECT_APPLICATION, commandApdu)) {\n mAppSelected = true;\n mCcSelected = false;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_CAPABILITY_CONTAINER",
"score": 16.873294391638595
}
] | java | ] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
| writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) ); |
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 35.35048375485003
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " }\n public static byte[] hexStringToByteArray(String s) {\n int len = s.length();\n byte[] data = new byte[len / 2];\n for (int i = 0; i < len; i += 2) {\n data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)\n + Character.digit(s.charAt(i + 1), 16));\n }\n return data;\n }",
"score": 34.97494315397829
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"commandApdu: \" + Utils.bytesToHex(commandApdu)); \n //if (Arrays.equals(SELECT_APP, commandApdu)) {\n // check if commandApdu qualifies for SELECT_APPLICATION\n if (Arrays.equals(SELECT_APPLICATION, commandApdu)) {\n mAppSelected = true;\n mCcSelected = false;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_CAPABILITY_CONTAINER",
"score": 24.216392955088356
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " if (mCcSelected && offset == 0 && le == CAPABILITY_CONTAINER_FILE.length) {\n System.arraycopy(CAPABILITY_CONTAINER_FILE, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));\n return responseApdu;\n } else if (mNdefSelected) {\n if (offset + le <= mNdefRecordFile.length) {\n System.arraycopy(mNdefRecordFile, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));",
"score": 20.850474472020565
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " } else if (mAppSelected && Arrays.equals(SELECT_CAPABILITY_CONTAINER, commandApdu)) {\n mCcSelected = true;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_NDEF_FILE\n } else if (mAppSelected && Arrays.equals(SELECT_NDEF_FILE, commandApdu)) {\n // NDEF\n mCcSelected = false;\n mNdefSelected = true;",
"score": 20.83923564953601
}
] | java | writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) ); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
| if (!Utils.isSucceed(responseSelect)) { |
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen);
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 44.236633314584104
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " if (mCcSelected && offset == 0 && le == CAPABILITY_CONTAINER_FILE.length) {\n System.arraycopy(CAPABILITY_CONTAINER_FILE, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));\n return responseApdu;\n } else if (mNdefSelected) {\n if (offset + le <= mNdefRecordFile.length) {\n System.arraycopy(mNdefRecordFile, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));",
"score": 41.13534024164771
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"commandApdu: \" + Utils.bytesToHex(commandApdu)); \n //if (Arrays.equals(SELECT_APP, commandApdu)) {\n // check if commandApdu qualifies for SELECT_APPLICATION\n if (Arrays.equals(SELECT_APPLICATION, commandApdu)) {\n mAppSelected = true;\n mCcSelected = false;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_CAPABILITY_CONTAINER",
"score": 35.204539062928966
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " } else if (mAppSelected && Arrays.equals(SELECT_CAPABILITY_CONTAINER, commandApdu)) {\n mCcSelected = true;\n mNdefSelected = false;\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for SELECT_NDEF_FILE\n } else if (mAppSelected && Arrays.equals(SELECT_NDEF_FILE, commandApdu)) {\n // NDEF\n mCcSelected = false;\n mNdefSelected = true;",
"score": 29.377420904886648
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " String finalNdefText = ndefText;\n getActivity().runOnUiThread(() -> {\n readResult.setText(finalNdefText);\n });\n }\n }\n } else {\n getActivity().runOnUiThread(() -> {\n readResult.setText(\"There was an error in NDEF data\");\n });",
"score": 27.43187132792423
}
] | java | if (!Utils.isSucceed(responseSelect)) { |
package de.androidcrypto.nfchcendefemulator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;
/**
* A simple {@link Fragment} subclass.
* Use the {@link SendFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class SendFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
RadioButton rbTimestamp, rbMessage, rbUrl;
TextView tvTimestamp;
boolean isTimestamp = false; // start/default
com.google.android.material.textfield.TextInputLayout dataToSendLayout;
com.google.android.material.textfield.TextInputEditText dataToSend;
//private final String DEFAULT_URL = "https://www.google.de/maps/@34.7967917,-111.765671,3a,66.6y,15.7h,102.19t/data=!3m6!1e1!3m4!1sFV61wUEyLNwFi6zHHaKMcg!2e0!7i16384!8i8192";
private final String DEFAULT_URL = "https://github.com/AndroidCrypto?tab=repositories";
public SendFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment SendFragment.
*/
// TODO: Rename and change types and number of parameters
public static SendFragment newInstance(String param1, String param2) {
SendFragment fragment = new SendFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
// AID is setup in apduservice.xml
// original AID: F0394148148100
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_send, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
tvTimestamp = getView().findViewById(R.id.tvTimestamp);
rbTimestamp = getView().findViewById(R.id.rbTimestamp);
rbMessage = getView().findViewById(R.id.rbMessage);
rbUrl = getView().findViewById(R.id.rbUrl);
dataToSendLayout = getView().findViewById(R.id.etDataToSendsLayout);
dataToSendLayout.setEnabled(false);
dataToSend = getView().findViewById(R.id.etDataToSend);
dataToSendLayout.setEndIconOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String dataToSendString = dataToSend.getText().toString();
if (TextUtils.isEmpty(dataToSendString)) {
Toast.makeText(view.getContext(), "Enter data to send", Toast.LENGTH_SHORT).show();
return;
}
if (rbMessage.isChecked()) {
String messageWithTimestamp = dataToSendString + " on " +
| Utils.getTimestamp(); |
Intent intent = new Intent(view.getContext(), MyHostApduService.class);
intent.putExtra("ndefMessage", messageWithTimestamp);
Toast.makeText(view.getContext(), "This message is send as NDEF message: " + messageWithTimestamp, Toast.LENGTH_SHORT).show();
requireActivity().startService(intent);
}
if (rbUrl.isChecked()) {
// check for https:// at the beginning
if (!dataToSendString.substring(0, 8).toLowerCase().equals("https://")) {
Toast.makeText(view.getContext(), "The URL needs to start with https://", Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(view.getContext(), MyHostApduService.class);
intent.putExtra("ndefUrl", dataToSendString);
Toast.makeText(view.getContext(), "This URL is send as NDEF message: " + dataToSendString, Toast.LENGTH_SHORT).show();
requireActivity().startService(intent);
}
}
});
rbTimestamp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (rbTimestamp.isChecked()) {
dataToSendLayout.setEnabled(false);
dataToSend.setText("");
isTimestamp = true;
Toast.makeText(view.getContext(), "An actual is send as NDEF message", Toast.LENGTH_SHORT).show();
}
}
});
rbMessage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (rbMessage.isChecked()) {
dataToSendLayout.setEnabled(true);
dataToSend.setText("");
isTimestamp = false;
}
}
});
rbUrl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (rbUrl.isChecked()) {
dataToSendLayout.setEnabled(true);
dataToSend.setText(DEFAULT_URL);
isTimestamp = false;
}
}
});
// start with timestamp
ndefWithTimestamp(view.getContext());
}
private void ndefWithTimestamp(Context context) {
PackageManager pm = context.getPackageManager();
Timer t = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
if (isTimestamp) {
Date dt = Calendar.getInstance().getTime();
//Log.d(TAG, "Set time as " + dt.toString());
tvTimestamp.setText(dt.toString());
if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)) {
Intent intent = new Intent(context, MyHostApduService.class);
intent.putExtra("ndefMessage", dt.toString());
context.startService(intent);
}
}
}
};
//t.scheduleAtFixedRate(task, 0, 1000); // every second
//t.scheduleAtFixedRate(task, 0, 60000); // every minute
t.scheduleAtFixedRate(task, 0, 2000); // every 2 seconds
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/SendFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java",
"retrieved_chunk": " Toast.LENGTH_SHORT).show();\n });\n }\n private void showWirelessSettings() {\n Toast.makeText(this.getContext(), \"You need to enable NFC\", Toast.LENGTH_SHORT).show();\n Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);\n startActivity(intent);\n }\n @Override\n public void onResume() {",
"score": 35.66989614260818
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " }\n }\n }\n private void showWirelessSettings() {\n Toast.makeText(this.getContext(), \"You need to enable NFC\", Toast.LENGTH_SHORT).show();\n Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);\n startActivity(intent);\n }\n @Override\n public void onResume() {",
"score": 32.29871460520527
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java",
"retrieved_chunk": " }\n String tagId = Utils.bytesToHex(tag.getId());\n writeToUiAppend(readResult, \"TagId: \" + tagId);\n try {\n isoDep = IsoDep.get(tag);\n if (isoDep != null) {\n getActivity().runOnUiThread(() -> {\n Toast.makeText(this.getContext(),\n \"NFC tag is IsoDep compatible\",\n Toast.LENGTH_SHORT).show();",
"score": 29.206685400760893
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java",
"retrieved_chunk": " private void writeToUiAppendReverse(TextView textView, String message) {\n getActivity().runOnUiThread(() -> {\n String newString = message + \"\\n\" + textView.getText().toString();\n textView.setText(newString);\n });\n }\n private void writeToUiToast(String message) {\n getActivity().runOnUiThread(() -> {\n Toast.makeText(this.getContext(),\n message,",
"score": 26.680816429564594
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java",
"retrieved_chunk": " mParam2 = getArguments().getString(ARG_PARAM2);\n }\n mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());\n }\n @Override\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\n readResult = getView().findViewById(R.id.tvReceiveReadResult);\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,",
"score": 18.88632018498411
}
] | java | Utils.getTimestamp(); |
package com.mineblock11.simplebroadcast.data;
import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.util.Identifier;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class ConfigurationManager {
public static final HashMap<Identifier, MessageType> MESSAGE_TYPE_REGISTRY = new HashMap<>();
public static final HashMap<Identifier, BroadcastMessage> MESSAGE_PRESET_REGISTRY = new HashMap<>();
// public static final HashMap<Identifier> MESSAGE_POOL_REGISTRY = new HashMap<>();
// public static final HashMap<Identifier, Object> SCHEDULE_REGISTRY = new HashMap<>();
static {
var $default = new MessageType.SimpleBroadcastDefaultMessageType();
ConfigurationManager.MESSAGE_TYPE_REGISTRY.put(new Identifier("minecraft:vanilla"), new MessageType.VanillaMessageType());
ConfigurationManager.MESSAGE_TYPE_REGISTRY.put(new Identifier("simplebroadcast:default"), $default);
ConfigurationManager.MESSAGE_TYPE_REGISTRY.put(new Identifier("minecraft:plain"), new MessageType.PlainMessageType());
ConfigurationManager.MESSAGE_PRESET_REGISTRY.put(new Identifier("simplebroadcast:hello"), new BroadcastMessage("Hello World!", $default, $default.getDefaultLocation()));
}
private static File getConfigurationFile() {
if (FabricLoader.getInstance().isDevelopmentEnvironment()) {
return new File("simple-broadcast-debug-config.json");
} else {
return FabricLoader.getInstance().getConfigDir().resolve("simple-broadcast.json").toFile();
}
}
public static void saveConfig() {
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().disableHtmlEscaping().create();
JsonObject config = new JsonObject();
JsonArray arrayOfMessageTypes = new JsonArray();
for (Map.Entry<Identifier, MessageType> identifierMessageTypeEntry : MESSAGE_TYPE_REGISTRY.entrySet()) {
JsonObject object = gson.toJsonTree(identifierMessageTypeEntry.getValue()).getAsJsonObject();
object.addProperty("id", identifierMessageTypeEntry.getKey().toString());
arrayOfMessageTypes.add(object);
}
config.add("message_types", arrayOfMessageTypes);
JsonArray arrayOfMessagePresets = new JsonArray();
for (Map.Entry<Identifier, BroadcastMessage> identifierBroadcastMessageEntry : MESSAGE_PRESET_REGISTRY.entrySet()) {
JsonObject object = gson.toJsonTree(identifierBroadcastMessageEntry.getValue()).getAsJsonObject();
object.remove("messageType");
object.addProperty | ("messageType", identifierBroadcastMessageEntry.getValue().getMessageType().getID().toString()); |
object.addProperty("id", identifierBroadcastMessageEntry.getKey().toString());
arrayOfMessagePresets.add(object);
}
config.add("message_presets", arrayOfMessagePresets);
String json = gson.toJson(config);
try {
Files.writeString(Path.of(getConfigurationFile().getPath()), json);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void loadConfig() {
File configurationFile = getConfigurationFile();
if (!configurationFile.exists()) saveConfig();
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().disableHtmlEscaping().create();
try {
// message_types
JsonObject config = gson.fromJson(new JsonReader(new FileReader(configurationFile)), JsonObject.class);
JsonArray arrayOfMessageTypes = config.getAsJsonArray("message_types");
ConfigurationManager.MESSAGE_TYPE_REGISTRY.clear();
for (JsonElement arrayOfMessageType : arrayOfMessageTypes) {
JsonObject obj = arrayOfMessageType.getAsJsonObject();
Identifier ID = Identifier.tryParse(obj.get("id").getAsString());
obj.remove("id");
MessageType type = gson.fromJson(obj, MessageType.CustomMessageType.class);
ConfigurationManager.MESSAGE_TYPE_REGISTRY.put(ID, type);
}
if(!config.has("message_presets")) {
config.add("message_presets", new JsonArray());
}
JsonArray arrayOfMessagePresets = config.getAsJsonArray("message_presets");
ConfigurationManager.MESSAGE_PRESET_REGISTRY.clear();
for (JsonElement arrayOfMessagePreset : arrayOfMessagePresets) {
JsonObject obj = arrayOfMessagePreset.getAsJsonObject();
Identifier messageTypeID = Identifier.tryParse(obj.get("messageType").getAsString());
Identifier ID = Identifier.tryParse(obj.get("id").getAsString());
obj.remove("messageType");
obj.remove("id");
BroadcastMessage message = gson.fromJson(obj, BroadcastMessage.class);
message.setMessageType(ConfigurationManager.MESSAGE_TYPE_REGISTRY.get(messageTypeID));
ConfigurationManager.MESSAGE_PRESET_REGISTRY.put(ID, message);
}
// TODO: Schedules + Message Pools
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| src/main/java/com/mineblock11/simplebroadcast/data/ConfigurationManager.java | mineblock11-SimpleBroadcast-47157bd | [
{
"filename": "src/main/java/com/mineblock11/simplebroadcast/data/BroadcastMessage.java",
"retrieved_chunk": " public Identifier getID() {\n for (var entry : ConfigurationManager.MESSAGE_PRESET_REGISTRY.entrySet()) {\n if (entry.getValue().equals(this)) {\n return entry.getKey();\n }\n }\n return null;\n }\n public void setMessageType(MessageType messageType) {\n this.messageType = messageType;",
"score": 32.816499359445025
},
{
"filename": "src/main/java/com/mineblock11/simplebroadcast/data/MessageType.java",
"retrieved_chunk": " }\n @Nullable\n public Identifier getID() {\n for (var entry : ConfigurationManager.MESSAGE_TYPE_REGISTRY.entrySet()) {\n if (entry.getValue().equals(this)) {\n return entry.getKey();\n }\n }\n return null;\n }",
"score": 23.87071262091974
},
{
"filename": "src/main/java/com/mineblock11/simplebroadcast/commands/SimpleBroadcastCommands.java",
"retrieved_chunk": " } else {\n sendFeedback(commandContext, \"<color:gray>\" + type.getID() + \"<r><color:gold> has the following prefix:<r> \");\n }\n return Command.SINGLE_SUCCESS;\n }\n private int createMessageType(CommandContext<ServerCommandSource> commandContext) {\n Identifier id = IdentifierArgumentType.getIdentifier(commandContext, \"id\");\n sendFeedback(commandContext, \"<color:gold>Created new broadcast message type: <color:gray>\" + id);\n MessageType.CustomMessageType messageType = new MessageType.CustomMessageType(null, null, null);\n ConfigurationManager.MESSAGE_TYPE_REGISTRY.put(id, messageType);",
"score": 12.398687130040425
},
{
"filename": "src/main/java/com/mineblock11/simplebroadcast/data/BroadcastMessage.java",
"retrieved_chunk": "import net.minecraft.util.Identifier;\nimport org.jetbrains.annotations.NotNull;\nimport org.jetbrains.annotations.Nullable;\npublic class BroadcastMessage {\n private String contents;\n private MessageType messageType;\n private BroadcastLocation broadcastLocation;\n public BroadcastMessage(String contents, MessageType messageType, @NotNull BroadcastLocation broadcastLocation) {\n this.contents = contents;\n this.messageType = messageType;",
"score": 12.067139026588464
},
{
"filename": "src/main/java/com/mineblock11/simplebroadcast/commands/SimpleBroadcastCommands.java",
"retrieved_chunk": " return Command.SINGLE_SUCCESS;\n }\n private int getPresetType(CommandContext<ServerCommandSource> commandContext) {\n Identifier ID = IdentifierArgumentType.getIdentifier(commandContext, \"id\");\n BroadcastMessage preset = ConfigurationManager.MESSAGE_PRESET_REGISTRY.get(IdentifierArgumentType.getIdentifier(commandContext, \"id\"));\n sendFeedback(commandContext, \"<color:gray>\" + ID + \"<color:gold> uses the <color:gray>\" + preset.getMessageType().getID() + \"<color:gold> message type.\");\n return Command.SINGLE_SUCCESS;\n }\n private int setPresetType(CommandContext<ServerCommandSource> commandContext) {\n Identifier ID = IdentifierArgumentType.getIdentifier(commandContext, \"id\");",
"score": 9.739927103901332
}
] | java | ("messageType", identifierBroadcastMessageEntry.getValue().getMessageType().getID().toString()); |
package de.androidcrypto.nfchcendefemulator;
import static android.content.Context.VIBRATOR_SERVICE;
import android.content.Context;
import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ReceiveExtendedFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ReceiveExtendedFragment extends Fragment implements NfcAdapter.ReaderCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public ReceiveExtendedFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ReceiveFragment.
*/
// TODO: Rename and change types and number of parameters
public static ReceiveExtendedFragment newInstance(String param1, String param2) {
ReceiveExtendedFragment fragment = new ReceiveExtendedFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
TextView readResult;
private NfcAdapter mNfcAdapter;
String dumpExportString = "";
String tagIdString = "";
String tagTypeString = "";
private static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 100;
Context contextSave;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.getContext());
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
readResult = getView().findViewById(R.id.tvReceiveReadResult);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_receive_extended, container, false);
}
// This method is running in another thread when a card is discovered
// !!!! This method cannot cannot direct interact with the UI Thread
// Use `runOnUiThread` method to change the UI from this method
@Override
public void onTagDiscovered(Tag tag) {
// Read and or write to Tag here to the appropriate Tag Technology type class
// in this example the card should be an Ndef Technology Type
System.out.println("NFC tag discovered");
getActivity().runOnUiThread(() -> {
readResult.setText("");
});
IsoDep isoDep = null;
writeToUiAppend(readResult, "Tag found");
String[] techList = tag.getTechList();
for (int i = 0; i < techList.length; i++) {
writeToUiAppend(readResult, "TechList: " + techList[i]);
}
String tagId = Utils.bytesToHex(tag.getId());
writeToUiAppend(readResult, "TagId: " + tagId);
try {
isoDep = IsoDep.get(tag);
if (isoDep != null) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
"NFC tag is IsoDep compatible",
Toast.LENGTH_SHORT).show();
});
isoDep.connect();
dumpExportString = "";
getActivity().runOnUiThread(() -> {
//readResult.setText("");
});
writeToUiAppend(readResult, "IsoDep reading");
String nfcaContent = "IsoDep reading" + "\n";
// now we run the select command with AID
String nfcHceNdefAid = "D2760000850101";
byte[] aid = Utils.hexStringToByteArray(nfcHceNdefAid);
byte[] command = selectApdu(aid);
byte[] responseSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "selectApdu with AID: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "selectApdu response: " + Utils.bytesToHex(responseSelect));
if (responseSelect == null) {
writeToUiAppend(readResult, "selectApdu with AID fails (null)");
} else {
writeToUiAppend(readResult, "responseSelect length: " + responseSelect.length + " data: " + Utils.bytesToHex(responseSelect));
System.out.println("responseSelect: " + Utils.bytesToHex(responseSelect));
}
if (!Utils.isSucceed(responseSelect)) {
writeToUiAppend(readResult, "responseSelect is not 90 00 - aborted");
System.out.println("responseSelect is not 90 00 - aborted ");
return;
}
// sending cc select = get the capability container
String selectCapabilityContainer = "00a4000c02e103";
command = Utils.hexStringToByteArray(selectCapabilityContainer);
byte[] responseSelectCc = isoDep.transceive(command);
writeToUiAppend(readResult, "select CC: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "select CC response: " + Utils.bytesToHex(responseSelectCc));
writeToUiAppend(readResult, "responseSelect length: " + responseSelectCc.length + " data: " + Utils.bytesToHex(responseSelectCc));
System.out.println("responseSelectCc: " + Utils.bytesToHex(responseSelectCc));
if (!Utils.isSucceed(responseSelectCc)) {
writeToUiAppend(readResult, "responseSelectCc is not 90 00 - aborted");
System.out.println("responseSelectCc is not 90 00 - aborted ");
return;
}
// Sending ReadBinary from CC...
String sendBinareFromCc = "00b000000f";
command = Utils.hexStringToByteArray(sendBinareFromCc);
byte[] responseSendBinaryFromCc = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryFromCc: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
writeToUiAppend(readResult, "sendBinaryFromCc response length: " + responseSendBinaryFromCc.length + " data: " + Utils.bytesToHex(responseSendBinaryFromCc));
System.out.println("sendBinaryFromCc response: " + Utils.bytesToHex(responseSendBinaryFromCc));
if (!Utils.isSucceed(responseSendBinaryFromCc)) {
writeToUiAppend(readResult, "responseSendBinaryFromCc is not 90 00 - aborted");
System.out.println("responseSendBinaryFromCc is not 90 00 - aborted ");
return;
}
// Capability Container header:
byte[] capabilityContainerHeader = Arrays.copyOfRange(responseSendBinaryFromCc, 0, responseSendBinaryFromCc.length - 2);
writeToUiAppend(readResult, "capabilityContainerHeader length: " + capabilityContainerHeader.length + " data: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + Utils.bytesToHex(capabilityContainerHeader));
System.out.println("capabilityContainerHeader: " + new String(capabilityContainerHeader));
// Sending NDEF Select...
String sendNdefSelect = "00a4000c02e104";
command = Utils.hexStringToByteArray(sendNdefSelect);
byte[] responseSendNdefSelect = isoDep.transceive(command);
writeToUiAppend(readResult, "sendNdefSelect: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
writeToUiAppend(readResult, "sendNdefSelect response length: " + responseSendNdefSelect.length + " data: " + Utils.bytesToHex(responseSendNdefSelect));
System.out.println("sendNdefSelect response: " + Utils.bytesToHex(responseSendNdefSelect));
if (!Utils.isSucceed(responseSendNdefSelect)) {
writeToUiAppend(readResult, "responseSendNdefSelect is not 90 00 - aborted");
System.out.println("responseSendNdefSelect is not 90 00 - aborted ");
return;
}
// Sending ReadBinary NLEN...
String sendReadBinaryNlen = "00b0000002";
command = Utils.hexStringToByteArray(sendReadBinaryNlen);
byte[] responseSendBinaryNlen = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNlen: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
writeToUiAppend(readResult, "sendBinaryNlen response length: " + responseSendBinaryNlen.length + " data: " + Utils.bytesToHex(responseSendBinaryNlen));
System.out.println("sendBinaryNlen response: " + Utils.bytesToHex(responseSendBinaryNlen));
if (!Utils.isSucceed(responseSendBinaryNlen)) {
writeToUiAppend(readResult, "responseSendBinaryNlen is not 90 00 - aborted");
System.out.println("responseSendBinaryNlen is not 90 00 - aborted ");
return;
}
// Sending ReadBinary, get NDEF data...
byte[] ndefLen = Arrays.copyOfRange(responseSendBinaryNlen, 0, 2);
byte[ | ] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen); |
int ndefLenInt = new BigInteger(ndefLen).intValue();
writeToUiAppend(readResult,"ndefLen: " + Utils.bytesToHex(ndefLen) + " len (dec): " + ndefLenInt);
int ndefLenIntRequest = ndefLenInt + 2;
//byte[] cmdLenNew = BigInteger.valueOf(ndefLenIntRequest).toByteArray();
byte[] cmdLenNew = Utils.convertIntToByteArray(ndefLenIntRequest, 2);
writeToUiAppend(readResult,"ndefLen new (dec): " + ndefLenIntRequest + " data: " + Utils.bytesToHex(cmdLenNew) );
String sendReadBinaryNdefData = "00b000" + Utils.bytesToHex(cmdLenNew);
//String sendReadBinaryNdefData = "00b000000f";
//String sendReadBinaryNdefData = "00b0000092";
command = Utils.hexStringToByteArray(sendReadBinaryNdefData);
byte[] responseSendBinaryNdefData = isoDep.transceive(command);
writeToUiAppend(readResult, "sendBinaryNdefData: " + Utils.bytesToHex(command));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response length: " + responseSendBinaryNdefData.length + " data: " + Utils.bytesToHex(responseSendBinaryNdefData));
writeToUiAppend(readResult, "sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + Utils.bytesToHex(responseSendBinaryNdefData));
System.out.println("sendBinaryNdefData response: " + new String(responseSendBinaryNdefData));
if (!Utils.isSucceed(responseSendBinaryNdefData)) {
writeToUiAppend(readResult, "responseSendBinaryNdefData is not 90 00 - aborted");
System.out.println("responseSendBinaryNdefData is not 90 00 - aborted ");
return;
}
byte[] ndefMessage = Arrays.copyOfRange(responseSendBinaryNdefData, 0, responseSendBinaryNdefData.length - 2);
writeToUiAppend(readResult, "ndefMessage length: " + ndefMessage.length + " data: " + Utils.bytesToHex(ndefMessage));
writeToUiAppend(readResult, "ndefMessage: " + new String(ndefMessage));
System.out.println("ndefMessage: " + new String(ndefMessage));
// strip off the first 2 bytes
byte[] ndefMessageStrip = Arrays.copyOfRange(ndefMessage, 9, ndefMessage.length);
//String ndefMessageParsed = Utils.parseTextrecordPayload(ndefMessageStrip);
String ndefMessageParsed = new String(ndefMessageStrip);
writeToUiAppend(readResult, "ndefMessage parsed: " + ndefMessageParsed);
System.out.println("ndefMessage parsed: " + ndefMessageParsed);
// try to get a NdefMessage from the byte array
byte[] ndefMessageByteArray = Arrays.copyOfRange(ndefMessage, 2, ndefMessage.length);
try {
NdefMessage ndefMessageFromTag = new NdefMessage(ndefMessageByteArray);
NdefRecord[] ndefRecords = ndefMessageFromTag.getRecords();
NdefRecord ndefRecord;
int ndefRecordsCount = ndefRecords.length;
if (ndefRecordsCount > 0) {
for (int i = 0; i < ndefRecordsCount; i++) {
short ndefTnf = ndefRecords[i].getTnf();
byte[] ndefType = ndefRecords[i].getType();
byte[] ndefPayload = ndefRecords[i].getPayload();
// here we are trying to parse the content
// Well known type - Text
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_TEXT)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Text payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseTextrecordPayload(ndefPayload));
}
// Well known type - Uri
if (ndefTnf == NdefRecord.TNF_WELL_KNOWN &&
Arrays.equals(ndefType, NdefRecord.RTD_URI)) {
writeToUiAppend(readResult, "rec: " + i +
" Well known Uri payload\n" + new String(ndefPayload) + " \n");
writeToUiAppend(readResult, Utils.parseUrirecordPayload(ndefPayload) + " \n");
}
}
dumpExportString = readResult.getText().toString();
}
//dumpExportString = readResult.getText().toString();
} catch (FormatException e) {
e.printStackTrace();
}
doVibrate();
} else {
writeToUiAppend(readResult, "IsoDep == null");
}
} catch (IOException e) {
writeToUiAppend(readResult, "ERROR IOException: " + e);
e.printStackTrace();
}
}
// https://stackoverflow.com/a/51338700/8166854
private byte[] selectApdu(byte[] aid) {
byte[] commandApdu = new byte[6 + aid.length];
commandApdu[0] = (byte) 0x00; // CLA
commandApdu[1] = (byte) 0xA4; // INS
commandApdu[2] = (byte) 0x04; // P1
commandApdu[3] = (byte) 0x00; // P2
commandApdu[4] = (byte) (aid.length & 0x0FF); // Lc
System.arraycopy(aid, 0, commandApdu, 5, aid.length);
commandApdu[commandApdu.length - 1] = (byte) 0x00; // Le
return commandApdu;
}
private void doVibrate() {
if (getActivity() != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
((Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE)).vibrate(VibrationEffect.createOneShot(150, 10));
} else {
Vibrator v = (Vibrator) getActivity().getSystemService(VIBRATOR_SERVICE);
v.vibrate(200);
}
}
}
private void writeToUiAppend(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = textView.getText().toString() + "\n" + message;
textView.setText(newString);
dumpExportString = newString;
});
}
private void writeToUiAppendReverse(TextView textView, String message) {
getActivity().runOnUiThread(() -> {
String newString = message + "\n" + textView.getText().toString();
textView.setText(newString);
});
}
private void writeToUiToast(String message) {
getActivity().runOnUiThread(() -> {
Toast.makeText(this.getContext(),
message,
Toast.LENGTH_SHORT).show();
});
}
private void showWirelessSettings() {
Toast.makeText(this.getContext(), "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
@Override
public void onResume() {
super.onResume();
if (mNfcAdapter != null) {
if (!mNfcAdapter.isEnabled())
showWirelessSettings();
Bundle options = new Bundle();
// Work around for some broken Nfc firmware implementations that poll the card too fast
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
// Enable ReaderMode for all types of card and disable platform sounds
// the option NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK is NOT set
// to get the data of the tag afer reading
mNfcAdapter.enableReaderMode(this.getActivity(),
this,
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
}
}
@Override
public void onPause() {
super.onPause();
if (mNfcAdapter != null)
mNfcAdapter.disableReaderMode(this.getActivity());
}
} | app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveExtendedFragment.java | MichaelsPlayground-NfcHceNdefEmulator-fa2ca23 | [
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(SUCCESS_SW));\n return SUCCESS_SW;\n // check if commandApdu qualifies for // READ_BINARY\n } else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\n // READ_BINARY\n // get the offset an le (length) data\n //System.out.println(\"** \" + Utils.bytesToHex(commandApdu) + \" in else if (commandApdu[0] == (byte)0x00 && commandApdu[1] == (byte)0xb0) {\");\n int offset = (0x00ff & commandApdu[2]) * 256 + (0x00ff & commandApdu[3]);\n int le = 0x00ff & commandApdu[4];\n byte[] responseApdu = new byte[le + SUCCESS_SW.length];",
"score": 34.23771685179903
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " * @param pByte\n * response to the last command\n * @return true if the status is 9000 false otherwise\n */\n public static boolean isSucceed(final byte[] pByte) {\n byte[] resultValue = Arrays.copyOfRange(pByte, pByte.length - 2, pByte.length);\n if (Arrays.equals(resultValue, SW_9000)) {\n return true;\n } else {\n return false;",
"score": 23.52233230219125
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/MyHostApduService.java",
"retrieved_chunk": " if (mCcSelected && offset == 0 && le == CAPABILITY_CONTAINER_FILE.length) {\n System.arraycopy(CAPABILITY_CONTAINER_FILE, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));\n return responseApdu;\n } else if (mNdefSelected) {\n if (offset + le <= mNdefRecordFile.length) {\n System.arraycopy(mNdefRecordFile, offset, responseApdu, 0, le);\n System.arraycopy(SUCCESS_SW, 0, responseApdu, le, SUCCESS_SW.length);\n Log.d((TAG), \"responseApdu: \" + Utils.bytesToHex(responseApdu));",
"score": 21.823159638450147
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/Utils.java",
"retrieved_chunk": " //s1 += \" \" + b1;\n output = output + \" \" + s1;\n //System.out.println(s1);\n }\n return output;\n }\n public static byte[] convertIntToByteArray(int value, int numberOfBytes) {\n byte b[] = new byte[numberOfBytes];\n int i, shift;\n for (i = 0, shift = (b.length - 1) * 8; i < b.length; i++, shift -= 8) {",
"score": 20.90682293165504
},
{
"filename": "app/src/main/java/de/androidcrypto/nfchcendefemulator/ReceiveFragment.java",
"retrieved_chunk": " // Use `runOnUiThread` method to change the UI from this method\n @Override\n public void onTagDiscovered(Tag tag) {\n // Read and or write to Tag here to the appropriate Tag Technology type class\n // in this example the card should be an Ndef Technology Type\n System.out.println(\"NFC tag discovered\");\n requireActivity().runOnUiThread(() -> {\n readResult.setText(\"\");\n });\n Ndef mNdef = Ndef.get(tag);",
"score": 20.221710899460245
}
] | java | ] cmdLen = Utils.hexStringToByteArray(sendReadBinaryNlen); |
package io.polivakha.mojo.properties;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import io.polivakha.mojo.properties.models.FileResource;
import io.polivakha.mojo.properties.models.Resource;
import io.polivakha.mojo.properties.models.UrlResource;
import io.polivakha.mojo.properties.utils.PathParser;
/**
* The read-project-properties goal reads property files and URLs and stores the properties as project properties. It
* serves as an alternate to specifying properties in pom.xml. It is especially useful when making properties defined in
* a runtime resource available at build time.
*
* @author <a href="mailto:[email protected]">Zarar Siddiqi</a>
* @author <a href="mailto:[email protected]">Krystian Nowak</a>
* @author Mikhail Polivakha
*/
@Mojo( name = "read-project-properties", defaultPhase = LifecyclePhase.NONE, threadSafe = true )
public class ReadPropertiesMojo extends AbstractMojo {
@Parameter( defaultValue = "${project}", readonly = true, required = true )
private MavenProject project;
/**
* The properties files that will be used when reading properties.
*/
@Parameter
private File[] files = new File[0];
@Parameter(name = "includes", required = false, alias = "includes")
private String[] includes = new String[0];
private final PathParser pathParser;
public ReadPropertiesMojo() {
this.pathParser = new PathParser();
}
/**
* @param files The files to set for tests.
*/
public void setFiles( File[] files ) {
if (files == null) {
this.files = new File[0];
} else {
this.files = new File[files.length];
System.arraycopy( files, 0, this.files, 0, files.length );
}
}
public void setIncludes(String[] includes) {
this.includes = includes;
}
/**
* The URLs that will be used when reading properties. These may be non-standard URLs of the form
* <code>classpath:com/company/resource.properties</code>. Note that the type is not <code>URL</code> for this
* reason and therefore will be explicitly checked by this Mojo.
*/
@Parameter
private String[] urls = new String[0];
/**
* If the plugin should be quiet if any of the files was not found
*/
@Parameter( defaultValue = "false" )
private boolean quiet;
/**
* Prefix that will be added before name of each property.
* Can be useful for separating properties with same name from different files.
*/
@Parameter
private String keyPrefix = null;
public void setKeyPrefix( String keyPrefix ) {
this.keyPrefix = keyPrefix;
}
@Parameter( defaultValue = "false", property = "prop.skipLoadProperties" )
private boolean skipLoadProperties;
/**
* Boolean flag that says, should the plugin log duplicated proeprties or not
*/
@Parameter( defaultValue = "false", property = "logOverridingProperties", required = false)
private boolean logOverridingProperties;
public void setLogOverridingProperties(boolean logOverridingProperties) {
this.logOverridingProperties = logOverridingProperties;
}
/**
* Used for resolving property placeholders.
*/
private final PropertyResolver resolver = new PropertyResolver();
/** {@inheritDoc} */
public void execute() throws MojoExecutionException, MojoFailureException {
setKeyPrefix();
if ( !skipLoadProperties ) {
loadFiles();
loadUrls();
loadFilesByPattern();
resolveProperties();
} else {
getLog().warn( "The properties are ignored" );
}
}
private void loadFiles() throws MojoExecutionException {
for ( File file : files ) {
load( new FileResource( file ) );
}
}
private void loadFilesByPattern() throws MojoExecutionException {
if (includes == null) {
return;
}
for (String antPattern : includes) {
if (antPattern == null || antPattern.isEmpty()) {
throw new MojoExecutionException("Provided <pattern/> element value is empty. Please, put corresponding ant path pattern in this element");
}
try (Stream<Path> pathStream = pathParser.streamFilesMatchingAntPath(antPattern)) {
List<FileResource> fileResources = pathStream.map(Path::toFile)
.peek(it -> getLog().debug(String.format("Found potential properties file '%s' by ant path pattern : '%s'", it, antPattern)))
.map(FileResource::new)
.collect(Collectors.toList());
for (FileResource fileResource : fileResources) {
loadProperties(fileResource);
}
} catch (IOException e) {
throw new MojoExecutionException("Error while traversing file tree to find properties files by ant pattern", e);
}
}
}
private void loadUrls() throws MojoExecutionException {
for ( String url : urls ) {
load( new UrlResource( url ) );
}
}
private void load( Resource resource ) throws MojoExecutionException {
if ( | resource.canBeOpened() ) { |
loadProperties( resource );
} else {
missing( resource );
}
}
private void loadProperties( Resource resource ) throws MojoExecutionException {
try {
getLog().debug( "Loading properties from " + resource );
try ( InputStream stream = resource.getInputStream() ) {
Properties properties = new Properties();
properties.load( stream );
Properties projectProperties = project.getProperties();
for ( String key : properties.stringPropertyNames() ) {
String propertyFinalName = keyPrefix + key;
checkIsPropertyAlreadyDefined(projectProperties, propertyFinalName);
projectProperties.put(propertyFinalName, properties.get( key ) );
}
}
} catch ( IOException e ) {
throw new MojoExecutionException( "Error reading properties from " + resource, e );
}
}
private void setKeyPrefix() {
if ( keyPrefix == null ) {
keyPrefix = "";
}
}
private void checkIsPropertyAlreadyDefined(Properties definedProperties, String newPropertyKey) {
if (logOverridingProperties && getLog().isInfoEnabled() && definedProperties.containsKey(newPropertyKey) ) {
getLog().info( String.format("Property %s is already defined. Value was overridden in Properties", newPropertyKey) );
}
}
private void missing( Resource resource ) throws MojoExecutionException {
if ( quiet ) {
getLog().info( "Quiet processing - ignoring properties cannot be loaded from " + resource );
} else {
throw new MojoExecutionException( "Properties could not be loaded from " + resource );
}
}
private void resolveProperties() throws MojoExecutionException, MojoFailureException {
Properties environment = loadSystemEnvironmentPropertiesWhenDefined();
Properties projectProperties = project.getProperties();
for (Object key : projectProperties.keySet()) {
projectProperties.setProperty( (String) key, getPropertyValue( (String) key, projectProperties, environment ) );
}
}
private Properties loadSystemEnvironmentPropertiesWhenDefined() throws MojoExecutionException {
boolean useEnvVariables = project.getProperties()
.values()
.stream()
.anyMatch(o -> ((String) o).startsWith("${env."));
Properties environment = null;
if ( useEnvVariables ) {
try {
environment = getSystemEnvVars();
} catch ( IOException e ) {
throw new MojoExecutionException( "Error getting system environment variables: ", e );
}
}
return environment;
}
private String getPropertyValue( String propertyName, Properties mavenPropertiesFromResource, Properties processEnvironment) throws MojoFailureException {
try {
return resolver.getPropertyValue(propertyName, mavenPropertiesFromResource, processEnvironment);
} catch (IllegalArgumentException e) {
throw new MojoFailureException(e.getMessage());
}
}
/**
* Override-able for test purposes.
*
* @return The shell environment variables, can be empty but never <code>null</code>.
* @throws IOException If the environment variables could not be queried from the shell.
*/
Properties getSystemEnvVars() throws IOException {
return CommandLineUtils.getSystemEnvVars();
}
/**
* Default scope for test access.
*
* @param quiet Set to <code>true</code> if missing files can be skipped.
*/
void setQuiet( boolean quiet )
{
this.quiet = quiet;
}
/**
*
* @param skipLoadProperties Set to <code>true</code> if you don't want to load properties.
*/
void setSkipLoadProperties( boolean skipLoadProperties )
{
this.skipLoadProperties = skipLoadProperties;
}
/**
* Default scope for test access.
*
* @param project The test project.
*/
void setProject( MavenProject project )
{
this.project = project;
}
}
| src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java | Mikhail2048-properties-maven-plugin-2ab2e8e | [
{
"filename": "src/main/java/io/polivakha/mojo/properties/models/UrlResource.java",
"retrieved_chunk": " private final URL url;\n private boolean isMissingClasspathResouce = false;\n private String classpathUrl;\n public UrlResource( String url ) throws MojoExecutionException {\n if ( url.startsWith( CLASSPATH_PREFIX ) ) {\n String resource = url.substring( CLASSPATH_PREFIX.length() );\n if ( resource.startsWith( SLASH_PREFIX ) ) {\n resource = resource.substring( 1 );\n }\n this.url = getClass().getClassLoader().getResource( resource );",
"score": 43.62785087406999
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/models/UrlResource.java",
"retrieved_chunk": " if ( this.url == null ) {\n isMissingClasspathResouce = true;\n classpathUrl = url;\n }\n } else {\n try {\n this.url = new URL( url );\n } catch ( MalformedURLException e ) {\n throw new MojoExecutionException( \"Badly formed URL \" + url + \" - \" + e.getMessage() );\n }",
"score": 20.476053482360403
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/models/UrlResource.java",
"retrieved_chunk": " return false;\n }\n return true;\n }\n protected InputStream openStream() throws IOException {\n return new BufferedInputStream( url.openStream() );\n }\n public String toString() {\n if ( !isMissingClasspathResouce ) {\n return \"URL \" + url.toString();",
"score": 17.62981830992032
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/AbstractWritePropertiesMojo.java",
"retrieved_chunk": " }\n }\n }\n /**\n * @throws MojoExecutionException {@link MojoExecutionException}\n */\n protected void validateOutputFile() throws MojoExecutionException {\n if (outputFile.isDirectory()) {\n throw new MojoExecutionException(\"outputFile must be a file and not a directory\");\n }",
"score": 16.604593446007364
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/loader/PropertiesLoader.java",
"retrieved_chunk": "package io.polivakha.mojo.properties.loader;\nimport java.util.List;\nimport java.util.Properties;\n/**\n * Represents an abstract resource loader that is capable to load properties from some resource\n *\n * @param <RESOURCE> - the abstract resource from which properties should be loaded\n * @author Mikhail Polivakha\n */\npublic interface PropertiesLoader<RESOURCE> {",
"score": 16.404233705172288
}
] | java | resource.canBeOpened() ) { |
package io.polivakha.mojo.properties;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import io.polivakha.mojo.properties.models.FileResource;
import io.polivakha.mojo.properties.models.Resource;
import io.polivakha.mojo.properties.models.UrlResource;
import io.polivakha.mojo.properties.utils.PathParser;
/**
* The read-project-properties goal reads property files and URLs and stores the properties as project properties. It
* serves as an alternate to specifying properties in pom.xml. It is especially useful when making properties defined in
* a runtime resource available at build time.
*
* @author <a href="mailto:[email protected]">Zarar Siddiqi</a>
* @author <a href="mailto:[email protected]">Krystian Nowak</a>
* @author Mikhail Polivakha
*/
@Mojo( name = "read-project-properties", defaultPhase = LifecyclePhase.NONE, threadSafe = true )
public class ReadPropertiesMojo extends AbstractMojo {
@Parameter( defaultValue = "${project}", readonly = true, required = true )
private MavenProject project;
/**
* The properties files that will be used when reading properties.
*/
@Parameter
private File[] files = new File[0];
@Parameter(name = "includes", required = false, alias = "includes")
private String[] includes = new String[0];
private final PathParser pathParser;
public ReadPropertiesMojo() {
this.pathParser = new PathParser();
}
/**
* @param files The files to set for tests.
*/
public void setFiles( File[] files ) {
if (files == null) {
this.files = new File[0];
} else {
this.files = new File[files.length];
System.arraycopy( files, 0, this.files, 0, files.length );
}
}
public void setIncludes(String[] includes) {
this.includes = includes;
}
/**
* The URLs that will be used when reading properties. These may be non-standard URLs of the form
* <code>classpath:com/company/resource.properties</code>. Note that the type is not <code>URL</code> for this
* reason and therefore will be explicitly checked by this Mojo.
*/
@Parameter
private String[] urls = new String[0];
/**
* If the plugin should be quiet if any of the files was not found
*/
@Parameter( defaultValue = "false" )
private boolean quiet;
/**
* Prefix that will be added before name of each property.
* Can be useful for separating properties with same name from different files.
*/
@Parameter
private String keyPrefix = null;
public void setKeyPrefix( String keyPrefix ) {
this.keyPrefix = keyPrefix;
}
@Parameter( defaultValue = "false", property = "prop.skipLoadProperties" )
private boolean skipLoadProperties;
/**
* Boolean flag that says, should the plugin log duplicated proeprties or not
*/
@Parameter( defaultValue = "false", property = "logOverridingProperties", required = false)
private boolean logOverridingProperties;
public void setLogOverridingProperties(boolean logOverridingProperties) {
this.logOverridingProperties = logOverridingProperties;
}
/**
* Used for resolving property placeholders.
*/
private final PropertyResolver resolver = new PropertyResolver();
/** {@inheritDoc} */
public void execute() throws MojoExecutionException, MojoFailureException {
setKeyPrefix();
if ( !skipLoadProperties ) {
loadFiles();
loadUrls();
loadFilesByPattern();
resolveProperties();
} else {
getLog().warn( "The properties are ignored" );
}
}
private void loadFiles() throws MojoExecutionException {
for ( File file : files ) {
load( new FileResource( file ) );
}
}
private void loadFilesByPattern() throws MojoExecutionException {
if (includes == null) {
return;
}
for (String antPattern : includes) {
if (antPattern == null || antPattern.isEmpty()) {
throw new MojoExecutionException("Provided <pattern/> element value is empty. Please, put corresponding ant path pattern in this element");
}
try (Stream | <Path> pathStream = pathParser.streamFilesMatchingAntPath(antPattern)) { |
List<FileResource> fileResources = pathStream.map(Path::toFile)
.peek(it -> getLog().debug(String.format("Found potential properties file '%s' by ant path pattern : '%s'", it, antPattern)))
.map(FileResource::new)
.collect(Collectors.toList());
for (FileResource fileResource : fileResources) {
loadProperties(fileResource);
}
} catch (IOException e) {
throw new MojoExecutionException("Error while traversing file tree to find properties files by ant pattern", e);
}
}
}
private void loadUrls() throws MojoExecutionException {
for ( String url : urls ) {
load( new UrlResource( url ) );
}
}
private void load( Resource resource ) throws MojoExecutionException {
if ( resource.canBeOpened() ) {
loadProperties( resource );
} else {
missing( resource );
}
}
private void loadProperties( Resource resource ) throws MojoExecutionException {
try {
getLog().debug( "Loading properties from " + resource );
try ( InputStream stream = resource.getInputStream() ) {
Properties properties = new Properties();
properties.load( stream );
Properties projectProperties = project.getProperties();
for ( String key : properties.stringPropertyNames() ) {
String propertyFinalName = keyPrefix + key;
checkIsPropertyAlreadyDefined(projectProperties, propertyFinalName);
projectProperties.put(propertyFinalName, properties.get( key ) );
}
}
} catch ( IOException e ) {
throw new MojoExecutionException( "Error reading properties from " + resource, e );
}
}
private void setKeyPrefix() {
if ( keyPrefix == null ) {
keyPrefix = "";
}
}
private void checkIsPropertyAlreadyDefined(Properties definedProperties, String newPropertyKey) {
if (logOverridingProperties && getLog().isInfoEnabled() && definedProperties.containsKey(newPropertyKey) ) {
getLog().info( String.format("Property %s is already defined. Value was overridden in Properties", newPropertyKey) );
}
}
private void missing( Resource resource ) throws MojoExecutionException {
if ( quiet ) {
getLog().info( "Quiet processing - ignoring properties cannot be loaded from " + resource );
} else {
throw new MojoExecutionException( "Properties could not be loaded from " + resource );
}
}
private void resolveProperties() throws MojoExecutionException, MojoFailureException {
Properties environment = loadSystemEnvironmentPropertiesWhenDefined();
Properties projectProperties = project.getProperties();
for (Object key : projectProperties.keySet()) {
projectProperties.setProperty( (String) key, getPropertyValue( (String) key, projectProperties, environment ) );
}
}
private Properties loadSystemEnvironmentPropertiesWhenDefined() throws MojoExecutionException {
boolean useEnvVariables = project.getProperties()
.values()
.stream()
.anyMatch(o -> ((String) o).startsWith("${env."));
Properties environment = null;
if ( useEnvVariables ) {
try {
environment = getSystemEnvVars();
} catch ( IOException e ) {
throw new MojoExecutionException( "Error getting system environment variables: ", e );
}
}
return environment;
}
private String getPropertyValue( String propertyName, Properties mavenPropertiesFromResource, Properties processEnvironment) throws MojoFailureException {
try {
return resolver.getPropertyValue(propertyName, mavenPropertiesFromResource, processEnvironment);
} catch (IllegalArgumentException e) {
throw new MojoFailureException(e.getMessage());
}
}
/**
* Override-able for test purposes.
*
* @return The shell environment variables, can be empty but never <code>null</code>.
* @throws IOException If the environment variables could not be queried from the shell.
*/
Properties getSystemEnvVars() throws IOException {
return CommandLineUtils.getSystemEnvVars();
}
/**
* Default scope for test access.
*
* @param quiet Set to <code>true</code> if missing files can be skipped.
*/
void setQuiet( boolean quiet )
{
this.quiet = quiet;
}
/**
*
* @param skipLoadProperties Set to <code>true</code> if you don't want to load properties.
*/
void setSkipLoadProperties( boolean skipLoadProperties )
{
this.skipLoadProperties = skipLoadProperties;
}
/**
* Default scope for test access.
*
* @param project The test project.
*/
void setProject( MavenProject project )
{
this.project = project;
}
}
| src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java | Mikhail2048-properties-maven-plugin-2ab2e8e | [
{
"filename": "src/main/java/io/polivakha/mojo/properties/utils/PathParser.java",
"retrieved_chunk": " *\n * @param antPathPattern - ant path pattern, must not be null\n * @return Stream of {@link Path}'s, that are files (not directories), that match provided ant path.\n * It is the responsibility of the caller method to close the stream\n *\n * @throws IOException in case of any file system errors\n */\n public Stream<Path> streamFilesMatchingAntPath(String antPathPattern) throws IOException {\n Assert.notNull(antPathPattern, \"Provided ant path is null\");\n String s = extractExactDirectory(Path.of(antPathPattern));",
"score": 38.94238135630734
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/AbstractWritePropertiesMojo.java",
"retrieved_chunk": " getLog().error(\"Error writing properties: \" + file);\n throw new MojoExecutionException(e.getMessage(), e);\n }\n }\n private void storeWithoutTimestamp(StoreProperties properties, File outputFile) throws IOException {\n try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {\n if (isSort()) {\n properties.sortedStore(fileOutputStream, null);\n } else {\n properties.store(fileOutputStream, null);",
"score": 22.288785732246787
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/models/UrlResource.java",
"retrieved_chunk": " if ( this.url == null ) {\n isMissingClasspathResouce = true;\n classpathUrl = url;\n }\n } else {\n try {\n this.url = new URL( url );\n } catch ( MalformedURLException e ) {\n throw new MojoExecutionException( \"Badly formed URL \" + url + \" - \" + e.getMessage() );\n }",
"score": 21.983297129605784
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/utils/PathParser.java",
"retrieved_chunk": " Assert.notNull(path, \"Passed path must not be null\");\n if (path.toString().isEmpty()) {\n return \"/\";\n }\n String stringPath = path.normalize().toString();\n return extractMostExactDirectoryFromNormalizedPath(stringPath);\n }\n private String extractMostExactDirectoryFromNormalizedPath(String stringPath) {\n StringBuilder result = new StringBuilder(\"/\");\n int leftPointer = 1;",
"score": 21.581422749774788
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/WriteProjectProperties.java",
"retrieved_chunk": " for (Object key : systemProperties.keySet()) {\n String value = systemProperties.getProperty( (String) key);\n if (projProperties.get(key) != null) {\n projProperties.put(key, value);\n }\n }\n writeProperties(projProperties, getOutputFile());\n }\n}",
"score": 19.847476148782967
}
] | java | <Path> pathStream = pathParser.streamFilesMatchingAntPath(antPattern)) { |
package io.polivakha.mojo.properties;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
public class PropertyResolver {
public String getPropertyValue(String key, Properties mavenProjectProperties, Properties environment) {
return this.getPropertyValue(key, mavenProjectProperties, environment, new CircularDefinitionPreventer());
}
/**
* Retrieves a property value, replacing values like ${token} using the Properties to look them up. Shamelessly
* adapted from:
* http://maven.apache.org/plugins/maven-war-plugin/xref/org/apache/maven/plugin/war/PropertyUtils.html It will
* leave unresolved properties alone, trying for System properties, and environment variables and implements
* reparsing (in the case that the value of a property contains a key), and will not loop endlessly on a pair like
* test = ${test}
*
* @param key property key
* @param mavenProjectProperties project properties
* @param environment environment variables
* @return resolved property value, or property placeholder, if it was not resolved
* @throws IllegalArgumentException when properties are circularly defined
*/
private String getPropertyValue(String key, Properties mavenProjectProperties, Properties environment, CircularDefinitionPreventer circularDefinitionPreventer) {
if (circularDefinitionPreventer.isPropertyAlreadyVisited(key)) {
| circularDefinitionPreventer.throwCircularDefinitionException(); |
}
String rawValue = fromPropertiesThenSystemThenEnvironment(key, mavenProjectProperties, environment);
if (StringUtils.isEmpty(rawValue)) {
return null;
}
ExpansionBuffer buffer = new ExpansionBuffer(rawValue);
String newKey;
while ((newKey = buffer.extractNextPropertyKey()) != null) {
buffer.moveResolvedPartToNextProperty();
String newValue = getPropertyValue(newKey, mavenProjectProperties, environment, circularDefinitionPreventer.cloneWithAdditionalKey(key));
if (newValue == null) {
buffer.add("${" + newKey + "}");
} else {
buffer.add(newValue);
}
}
return buffer.getFullyResolved();
}
private String fromPropertiesThenSystemThenEnvironment( String key, Properties properties, Properties environment ) {
String value = StringUtils.defaultIfEmpty(
properties.getProperty(key),
System.getProperty(key)
);
// try environment variable
if ( value == null && key.startsWith( "env." ) && environment != null ) {
value = environment.getProperty( key.substring( 4 ) );
}
return value;
}
}
| src/main/java/io/polivakha/mojo/properties/PropertyResolver.java | Mikhail2048-properties-maven-plugin-2ab2e8e | [
{
"filename": "src/main/java/io/polivakha/mojo/properties/CircularDefinitionPreventer.java",
"retrieved_chunk": " /**\n * Checks if property is already visited\n * @param key - key which defines the property\n * @return true if property was already visited during value resolution, false otherwise\n */\n public boolean isPropertyAlreadyVisited(String key) {\n return keysUsed.contains(key);\n }\n /**\n * Check that the expanded property does not provide a circular definition.",
"score": 56.59058773669769
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/CircularDefinitionPreventer.java",
"retrieved_chunk": " * For instance:\n * <p>\n * some.key = ${some.property}\n * some.property = ${some.key}\n * <p>\n * This is a circular properties definition\n * @param key The key.\n * @return {@link CircularDefinitionPreventer}\n */\n public CircularDefinitionPreventer cloneWithAdditionalKey( String key ) {",
"score": 51.56851621725144
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java",
"retrieved_chunk": " projectProperties.setProperty( (String) key, getPropertyValue( (String) key, projectProperties, environment ) );\n }\n }\n private Properties loadSystemEnvironmentPropertiesWhenDefined() throws MojoExecutionException {\n boolean useEnvVariables = project.getProperties()\n .values()\n .stream()\n .anyMatch(o -> ((String) o).startsWith(\"${env.\"));\n Properties environment = null;\n if ( useEnvVariables ) {",
"score": 47.1545976887802
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/CircularDefinitionPreventer.java",
"retrieved_chunk": " var keysUsedCopy = new LinkedHashSet<>(keysUsed);\n keysUsedCopy.add(key);\n return new CircularDefinitionPreventer(keysUsedCopy);\n }\n public void throwCircularDefinitionException() {\n StringBuilder buffer = new StringBuilder( \"Circular property definition detected: \\n\");\n keysUsed.forEach(key -> buffer.append(key).append(\" --> \"));\n buffer.append(keysUsed.stream().findFirst());\n throw new PropertyCircularDefinitionException( buffer.toString() );\n }",
"score": 34.477444249489366
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java",
"retrieved_chunk": " if ( quiet ) {\n getLog().info( \"Quiet processing - ignoring properties cannot be loaded from \" + resource );\n } else {\n throw new MojoExecutionException( \"Properties could not be loaded from \" + resource );\n }\n }\n private void resolveProperties() throws MojoExecutionException, MojoFailureException {\n Properties environment = loadSystemEnvironmentPropertiesWhenDefined();\n Properties projectProperties = project.getProperties();\n for (Object key : projectProperties.keySet()) {",
"score": 33.8922614529352
}
] | java | circularDefinitionPreventer.throwCircularDefinitionException(); |
package io.polivakha.mojo.properties;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import io.polivakha.mojo.properties.models.FileResource;
import io.polivakha.mojo.properties.models.Resource;
import io.polivakha.mojo.properties.models.UrlResource;
import io.polivakha.mojo.properties.utils.PathParser;
/**
* The read-project-properties goal reads property files and URLs and stores the properties as project properties. It
* serves as an alternate to specifying properties in pom.xml. It is especially useful when making properties defined in
* a runtime resource available at build time.
*
* @author <a href="mailto:[email protected]">Zarar Siddiqi</a>
* @author <a href="mailto:[email protected]">Krystian Nowak</a>
* @author Mikhail Polivakha
*/
@Mojo( name = "read-project-properties", defaultPhase = LifecyclePhase.NONE, threadSafe = true )
public class ReadPropertiesMojo extends AbstractMojo {
@Parameter( defaultValue = "${project}", readonly = true, required = true )
private MavenProject project;
/**
* The properties files that will be used when reading properties.
*/
@Parameter
private File[] files = new File[0];
@Parameter(name = "includes", required = false, alias = "includes")
private String[] includes = new String[0];
private final PathParser pathParser;
public ReadPropertiesMojo() {
this.pathParser = new PathParser();
}
/**
* @param files The files to set for tests.
*/
public void setFiles( File[] files ) {
if (files == null) {
this.files = new File[0];
} else {
this.files = new File[files.length];
System.arraycopy( files, 0, this.files, 0, files.length );
}
}
public void setIncludes(String[] includes) {
this.includes = includes;
}
/**
* The URLs that will be used when reading properties. These may be non-standard URLs of the form
* <code>classpath:com/company/resource.properties</code>. Note that the type is not <code>URL</code> for this
* reason and therefore will be explicitly checked by this Mojo.
*/
@Parameter
private String[] urls = new String[0];
/**
* If the plugin should be quiet if any of the files was not found
*/
@Parameter( defaultValue = "false" )
private boolean quiet;
/**
* Prefix that will be added before name of each property.
* Can be useful for separating properties with same name from different files.
*/
@Parameter
private String keyPrefix = null;
public void setKeyPrefix( String keyPrefix ) {
this.keyPrefix = keyPrefix;
}
@Parameter( defaultValue = "false", property = "prop.skipLoadProperties" )
private boolean skipLoadProperties;
/**
* Boolean flag that says, should the plugin log duplicated proeprties or not
*/
@Parameter( defaultValue = "false", property = "logOverridingProperties", required = false)
private boolean logOverridingProperties;
public void setLogOverridingProperties(boolean logOverridingProperties) {
this.logOverridingProperties = logOverridingProperties;
}
/**
* Used for resolving property placeholders.
*/
private final PropertyResolver resolver = new PropertyResolver();
/** {@inheritDoc} */
public void execute() throws MojoExecutionException, MojoFailureException {
setKeyPrefix();
if ( !skipLoadProperties ) {
loadFiles();
loadUrls();
loadFilesByPattern();
resolveProperties();
} else {
getLog().warn( "The properties are ignored" );
}
}
private void loadFiles() throws MojoExecutionException {
for ( File file : files ) {
load( new FileResource( file ) );
}
}
private void loadFilesByPattern() throws MojoExecutionException {
if (includes == null) {
return;
}
for (String antPattern : includes) {
if (antPattern == null || antPattern.isEmpty()) {
throw new MojoExecutionException("Provided <pattern/> element value is empty. Please, put corresponding ant path pattern in this element");
}
try (Stream<Path> pathStream = pathParser.streamFilesMatchingAntPath(antPattern)) {
List<FileResource> fileResources = pathStream.map(Path::toFile)
.peek(it -> getLog().debug(String.format("Found potential properties file '%s' by ant path pattern : '%s'", it, antPattern)))
.map(FileResource::new)
.collect(Collectors.toList());
for (FileResource fileResource : fileResources) {
loadProperties(fileResource);
}
} catch (IOException e) {
throw new MojoExecutionException("Error while traversing file tree to find properties files by ant pattern", e);
}
}
}
private void loadUrls() throws MojoExecutionException {
for ( String url : urls ) {
load( new UrlResource( url ) );
}
}
private void load( Resource resource ) throws MojoExecutionException {
if ( resource.canBeOpened() ) {
loadProperties( resource );
} else {
missing( resource );
}
}
private void loadProperties( Resource resource ) throws MojoExecutionException {
try {
getLog().debug( "Loading properties from " + resource );
try | ( InputStream stream = resource.getInputStream() ) { |
Properties properties = new Properties();
properties.load( stream );
Properties projectProperties = project.getProperties();
for ( String key : properties.stringPropertyNames() ) {
String propertyFinalName = keyPrefix + key;
checkIsPropertyAlreadyDefined(projectProperties, propertyFinalName);
projectProperties.put(propertyFinalName, properties.get( key ) );
}
}
} catch ( IOException e ) {
throw new MojoExecutionException( "Error reading properties from " + resource, e );
}
}
private void setKeyPrefix() {
if ( keyPrefix == null ) {
keyPrefix = "";
}
}
private void checkIsPropertyAlreadyDefined(Properties definedProperties, String newPropertyKey) {
if (logOverridingProperties && getLog().isInfoEnabled() && definedProperties.containsKey(newPropertyKey) ) {
getLog().info( String.format("Property %s is already defined. Value was overridden in Properties", newPropertyKey) );
}
}
private void missing( Resource resource ) throws MojoExecutionException {
if ( quiet ) {
getLog().info( "Quiet processing - ignoring properties cannot be loaded from " + resource );
} else {
throw new MojoExecutionException( "Properties could not be loaded from " + resource );
}
}
private void resolveProperties() throws MojoExecutionException, MojoFailureException {
Properties environment = loadSystemEnvironmentPropertiesWhenDefined();
Properties projectProperties = project.getProperties();
for (Object key : projectProperties.keySet()) {
projectProperties.setProperty( (String) key, getPropertyValue( (String) key, projectProperties, environment ) );
}
}
private Properties loadSystemEnvironmentPropertiesWhenDefined() throws MojoExecutionException {
boolean useEnvVariables = project.getProperties()
.values()
.stream()
.anyMatch(o -> ((String) o).startsWith("${env."));
Properties environment = null;
if ( useEnvVariables ) {
try {
environment = getSystemEnvVars();
} catch ( IOException e ) {
throw new MojoExecutionException( "Error getting system environment variables: ", e );
}
}
return environment;
}
private String getPropertyValue( String propertyName, Properties mavenPropertiesFromResource, Properties processEnvironment) throws MojoFailureException {
try {
return resolver.getPropertyValue(propertyName, mavenPropertiesFromResource, processEnvironment);
} catch (IllegalArgumentException e) {
throw new MojoFailureException(e.getMessage());
}
}
/**
* Override-able for test purposes.
*
* @return The shell environment variables, can be empty but never <code>null</code>.
* @throws IOException If the environment variables could not be queried from the shell.
*/
Properties getSystemEnvVars() throws IOException {
return CommandLineUtils.getSystemEnvVars();
}
/**
* Default scope for test access.
*
* @param quiet Set to <code>true</code> if missing files can be skipped.
*/
void setQuiet( boolean quiet )
{
this.quiet = quiet;
}
/**
*
* @param skipLoadProperties Set to <code>true</code> if you don't want to load properties.
*/
void setSkipLoadProperties( boolean skipLoadProperties )
{
this.skipLoadProperties = skipLoadProperties;
}
/**
* Default scope for test access.
*
* @param project The test project.
*/
void setProject( MavenProject project )
{
this.project = project;
}
}
| src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java | Mikhail2048-properties-maven-plugin-2ab2e8e | [
{
"filename": "src/main/java/io/polivakha/mojo/properties/loader/AbstractPropertiesLoader.java",
"retrieved_chunk": " @Override\n public Properties loadProperties(List<RESOURCE> resources) {\n Properties result = new Properties();\n for (RESOURCE resource : resources) {\n Properties properties = loadInternally(resource);\n result.putAll(properties);\n }\n return result;\n }\n /**",
"score": 36.913506228930906
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/models/UrlResource.java",
"retrieved_chunk": " private final URL url;\n private boolean isMissingClasspathResouce = false;\n private String classpathUrl;\n public UrlResource( String url ) throws MojoExecutionException {\n if ( url.startsWith( CLASSPATH_PREFIX ) ) {\n String resource = url.substring( CLASSPATH_PREFIX.length() );\n if ( resource.startsWith( SLASH_PREFIX ) ) {\n resource = resource.substring( 1 );\n }\n this.url = getClass().getClassLoader().getResource( resource );",
"score": 36.023115265344046
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/loader/PropertiesLoader.java",
"retrieved_chunk": "package io.polivakha.mojo.properties.loader;\nimport java.util.List;\nimport java.util.Properties;\n/**\n * Represents an abstract resource loader that is capable to load properties from some resource\n *\n * @param <RESOURCE> - the abstract resource from which properties should be loaded\n * @author Mikhail Polivakha\n */\npublic interface PropertiesLoader<RESOURCE> {",
"score": 30.069919556999217
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/loader/PropertiesLoader.java",
"retrieved_chunk": " /**\n * Loading the properties from the specified resources. Note that the order of {@code resources}\n * list elements <b>matters</b>, because each next resource, in case of conflict, will override\n * the properties loaded from previous resource. for example, if there is a property 'abc' defined in\n * 3 resources, then the value of 'abc' property in the last resource in the passed list will be contained\n * in the returned {@link Properties} object.\n *\n * @param resources - resources list, from which the {@link Properties} should be loaded\n * @return Properties object, containing the loaded properties\n */",
"score": 27.296456457762183
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/models/Resource.java",
"retrieved_chunk": "package io.polivakha.mojo.properties.models;\nimport java.io.IOException;\nimport java.io.InputStream;\npublic abstract class Resource {\n private InputStream stream;\n public abstract boolean canBeOpened();\n protected abstract InputStream openStream() throws IOException;\n public InputStream getInputStream() throws IOException {\n if ( stream == null ) {\n stream = openStream();",
"score": 21.665173452259634
}
] | java | ( InputStream stream = resource.getInputStream() ) { |
package io.polivakha.mojo.properties;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
public class PropertyResolver {
public String getPropertyValue(String key, Properties mavenProjectProperties, Properties environment) {
return this.getPropertyValue(key, mavenProjectProperties, environment, new CircularDefinitionPreventer());
}
/**
* Retrieves a property value, replacing values like ${token} using the Properties to look them up. Shamelessly
* adapted from:
* http://maven.apache.org/plugins/maven-war-plugin/xref/org/apache/maven/plugin/war/PropertyUtils.html It will
* leave unresolved properties alone, trying for System properties, and environment variables and implements
* reparsing (in the case that the value of a property contains a key), and will not loop endlessly on a pair like
* test = ${test}
*
* @param key property key
* @param mavenProjectProperties project properties
* @param environment environment variables
* @return resolved property value, or property placeholder, if it was not resolved
* @throws IllegalArgumentException when properties are circularly defined
*/
private String getPropertyValue(String key, Properties mavenProjectProperties, Properties environment, CircularDefinitionPreventer circularDefinitionPreventer) {
if (circularDefinitionPreventer.isPropertyAlreadyVisited(key)) {
circularDefinitionPreventer.throwCircularDefinitionException();
}
String rawValue = fromPropertiesThenSystemThenEnvironment(key, mavenProjectProperties, environment);
if (StringUtils.isEmpty(rawValue)) {
return null;
}
ExpansionBuffer buffer = new ExpansionBuffer(rawValue);
String newKey;
while ((newKey = buffer.extractNextPropertyKey()) != null) {
buffer.moveResolvedPartToNextProperty();
String | newValue = getPropertyValue(newKey, mavenProjectProperties, environment, circularDefinitionPreventer.cloneWithAdditionalKey(key)); |
if (newValue == null) {
buffer.add("${" + newKey + "}");
} else {
buffer.add(newValue);
}
}
return buffer.getFullyResolved();
}
private String fromPropertiesThenSystemThenEnvironment( String key, Properties properties, Properties environment ) {
String value = StringUtils.defaultIfEmpty(
properties.getProperty(key),
System.getProperty(key)
);
// try environment variable
if ( value == null && key.startsWith( "env." ) && environment != null ) {
value = environment.getProperty( key.substring( 4 ) );
}
return value;
}
}
| src/main/java/io/polivakha/mojo/properties/PropertyResolver.java | Mikhail2048-properties-maven-plugin-2ab2e8e | [
{
"filename": "src/main/java/io/polivakha/mojo/properties/CircularDefinitionPreventer.java",
"retrieved_chunk": " var keysUsedCopy = new LinkedHashSet<>(keysUsed);\n keysUsedCopy.add(key);\n return new CircularDefinitionPreventer(keysUsedCopy);\n }\n public void throwCircularDefinitionException() {\n StringBuilder buffer = new StringBuilder( \"Circular property definition detected: \\n\");\n keysUsed.forEach(key -> buffer.append(key).append(\" --> \"));\n buffer.append(keysUsed.stream().findFirst());\n throw new PropertyCircularDefinitionException( buffer.toString() );\n }",
"score": 35.50476027031904
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java",
"retrieved_chunk": " projectProperties.setProperty( (String) key, getPropertyValue( (String) key, projectProperties, environment ) );\n }\n }\n private Properties loadSystemEnvironmentPropertiesWhenDefined() throws MojoExecutionException {\n boolean useEnvVariables = project.getProperties()\n .values()\n .stream()\n .anyMatch(o -> ((String) o).startsWith(\"${env.\"));\n Properties environment = null;\n if ( useEnvVariables ) {",
"score": 29.770106928784067
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/WriteProjectProperties.java",
"retrieved_chunk": " for (Object key : systemProperties.keySet()) {\n String value = systemProperties.getProperty( (String) key);\n if (projProperties.get(key) != null) {\n projProperties.put(key, value);\n }\n }\n writeProperties(projProperties, getOutputFile());\n }\n}",
"score": 20.01660973160296
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/CircularDefinitionPreventer.java",
"retrieved_chunk": " * For instance:\n * <p>\n * some.key = ${some.property}\n * some.property = ${some.key}\n * <p>\n * This is a circular properties definition\n * @param key The key.\n * @return {@link CircularDefinitionPreventer}\n */\n public CircularDefinitionPreventer cloneWithAdditionalKey( String key ) {",
"score": 19.24696832095117
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java",
"retrieved_chunk": " try {\n environment = getSystemEnvVars();\n } catch ( IOException e ) {\n throw new MojoExecutionException( \"Error getting system environment variables: \", e );\n }\n }\n return environment;\n }\n private String getPropertyValue( String propertyName, Properties mavenPropertiesFromResource, Properties processEnvironment) throws MojoFailureException {\n try {",
"score": 18.553714973444983
}
] | java | newValue = getPropertyValue(newKey, mavenProjectProperties, environment, circularDefinitionPreventer.cloneWithAdditionalKey(key)); |
package io.polivakha.mojo.properties;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
public class PropertyResolver {
public String getPropertyValue(String key, Properties mavenProjectProperties, Properties environment) {
return this.getPropertyValue(key, mavenProjectProperties, environment, new CircularDefinitionPreventer());
}
/**
* Retrieves a property value, replacing values like ${token} using the Properties to look them up. Shamelessly
* adapted from:
* http://maven.apache.org/plugins/maven-war-plugin/xref/org/apache/maven/plugin/war/PropertyUtils.html It will
* leave unresolved properties alone, trying for System properties, and environment variables and implements
* reparsing (in the case that the value of a property contains a key), and will not loop endlessly on a pair like
* test = ${test}
*
* @param key property key
* @param mavenProjectProperties project properties
* @param environment environment variables
* @return resolved property value, or property placeholder, if it was not resolved
* @throws IllegalArgumentException when properties are circularly defined
*/
private String getPropertyValue(String key, Properties mavenProjectProperties, Properties environment, CircularDefinitionPreventer circularDefinitionPreventer) {
if ( | circularDefinitionPreventer.isPropertyAlreadyVisited(key)) { |
circularDefinitionPreventer.throwCircularDefinitionException();
}
String rawValue = fromPropertiesThenSystemThenEnvironment(key, mavenProjectProperties, environment);
if (StringUtils.isEmpty(rawValue)) {
return null;
}
ExpansionBuffer buffer = new ExpansionBuffer(rawValue);
String newKey;
while ((newKey = buffer.extractNextPropertyKey()) != null) {
buffer.moveResolvedPartToNextProperty();
String newValue = getPropertyValue(newKey, mavenProjectProperties, environment, circularDefinitionPreventer.cloneWithAdditionalKey(key));
if (newValue == null) {
buffer.add("${" + newKey + "}");
} else {
buffer.add(newValue);
}
}
return buffer.getFullyResolved();
}
private String fromPropertiesThenSystemThenEnvironment( String key, Properties properties, Properties environment ) {
String value = StringUtils.defaultIfEmpty(
properties.getProperty(key),
System.getProperty(key)
);
// try environment variable
if ( value == null && key.startsWith( "env." ) && environment != null ) {
value = environment.getProperty( key.substring( 4 ) );
}
return value;
}
}
| src/main/java/io/polivakha/mojo/properties/PropertyResolver.java | Mikhail2048-properties-maven-plugin-2ab2e8e | [
{
"filename": "src/main/java/io/polivakha/mojo/properties/CircularDefinitionPreventer.java",
"retrieved_chunk": " /**\n * Checks if property is already visited\n * @param key - key which defines the property\n * @return true if property was already visited during value resolution, false otherwise\n */\n public boolean isPropertyAlreadyVisited(String key) {\n return keysUsed.contains(key);\n }\n /**\n * Check that the expanded property does not provide a circular definition.",
"score": 56.59058773669769
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/CircularDefinitionPreventer.java",
"retrieved_chunk": " * For instance:\n * <p>\n * some.key = ${some.property}\n * some.property = ${some.key}\n * <p>\n * This is a circular properties definition\n * @param key The key.\n * @return {@link CircularDefinitionPreventer}\n */\n public CircularDefinitionPreventer cloneWithAdditionalKey( String key ) {",
"score": 51.56851621725144
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java",
"retrieved_chunk": " projectProperties.setProperty( (String) key, getPropertyValue( (String) key, projectProperties, environment ) );\n }\n }\n private Properties loadSystemEnvironmentPropertiesWhenDefined() throws MojoExecutionException {\n boolean useEnvVariables = project.getProperties()\n .values()\n .stream()\n .anyMatch(o -> ((String) o).startsWith(\"${env.\"));\n Properties environment = null;\n if ( useEnvVariables ) {",
"score": 47.1545976887802
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java",
"retrieved_chunk": " if ( quiet ) {\n getLog().info( \"Quiet processing - ignoring properties cannot be loaded from \" + resource );\n } else {\n throw new MojoExecutionException( \"Properties could not be loaded from \" + resource );\n }\n }\n private void resolveProperties() throws MojoExecutionException, MojoFailureException {\n Properties environment = loadSystemEnvironmentPropertiesWhenDefined();\n Properties projectProperties = project.getProperties();\n for (Object key : projectProperties.keySet()) {",
"score": 33.8922614529352
},
{
"filename": "src/main/java/io/polivakha/mojo/properties/ReadPropertiesMojo.java",
"retrieved_chunk": " try {\n environment = getSystemEnvVars();\n } catch ( IOException e ) {\n throw new MojoExecutionException( \"Error getting system environment variables: \", e );\n }\n }\n return environment;\n }\n private String getPropertyValue( String propertyName, Properties mavenPropertiesFromResource, Properties processEnvironment) throws MojoFailureException {\n try {",
"score": 33.43820449584602
}
] | java | circularDefinitionPreventer.isPropertyAlreadyVisited(key)) { |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.QueryResult;
import com.microsoft.lst_bench.exec.FileExec;
import com.microsoft.lst_bench.exec.StatementExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.StringUtils;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Custom task executor implementation that allows users to execute dependent tasks. We call a
* dependent task a task that iteratively executes a) a statement that is expected to return a
* result; and b) a statement repeatedly that is expected to use that result. The result of the
* first statement is stored in an intermediate object that can be specific to the connection. The
* expected object for a JDBC connection is of type List<Map<String, Object>>, handling of other
* objects would need to be added to the if-clause that checks the instance of the object.
*/
public class DependentTaskExecutor extends TaskExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(DependentTaskExecutor.class);
private final CustomTaskExecutorArguments arguments;
private final int DEFAULT_BATCH_SIZE = 1;
public DependentTaskExecutor(
SQLTelemetryRegistry telemetryRegistry,
String experimentStartTime,
CustomTaskExecutorArguments arguments) {
super(telemetryRegistry, experimentStartTime);
this.arguments = arguments;
}
@Override
public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)
throws ClientException {
int batch_size;
if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {
batch_size = DEFAULT_BATCH_SIZE;
} else {
batch_size = this.arguments.getDependentTaskBatchSize().intValue();
}
QueryResult queryResult = null;
for (FileExec file : task.getFiles()) {
Instant fileStartTime = Instant.now();
if (file.getStatements().size() != 1) {
writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);
throw new ClientException(
"For dependent task execution, statements have to be in separate files.");
}
StatementExec statement = file.getStatements().get(0);
try {
if (queryResult == null) {
// Execute first query that retrieves the iterable input for the second query.
Instant statementStartTime = Instant.now();
queryResult =
connection.executeQuery(
StringUtils.replaceParameters(statement, values).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
if (queryResult == null || queryResult.containsEmptyResultColumnOnly()) {
// Reset queryResult variable if result is (intentionally) empty.
queryResult = null;
}
} else {
// Execute second query repeatedly with the parameters extracted from the first query.
Integer | size = queryResult.getValueListSize(); |
for (int j = 0; j < size; j += batch_size) {
int localMax = (j + batch_size) > size ? size : (j + batch_size);
Map<String, Object> localValues = new HashMap<>(values);
localValues.putAll(queryResult.getStringMappings(j, localMax));
Instant statementStartTime = Instant.now();
connection.execute(
StringUtils.replaceParameters(statement, localValues).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
}
// Reset query result.
queryResult = null;
}
} catch (Exception e) {
LOGGER.error("Exception executing file: " + file.getId());
writeStatementEvent(
fileStartTime,
file.getId(),
Status.FAILURE,
/* payload= */ e.getMessage() + "; " + e.getStackTrace());
throw e;
}
writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);
}
}
}
| src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " }\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);",
"score": 42.33483916060886
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " Instant startTime, String id, Status status, String payload) {\n EventInfo eventInfo = null;\n if (payload != null) {\n eventInfo =\n ImmutableEventInfo.of(\n experimentStartTime,\n startTime,\n Instant.now(),\n id,\n EventType.EXEC_STATEMENT,",
"score": 28.440443653110925
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": " if (str == null) {\n return null;\n }\n return \"'\" + str + \"'\";\n }\n public static StatementExec replaceParameters(\n StatementExec statement, Map<String, Object> parameterValues) {\n if (parameterValues == null || parameterValues.isEmpty()) {\n // Nothing to do\n return statement;",
"score": 26.065126926480634
},
{
"filename": "src/main/java/com/microsoft/lst_bench/client/JDBCConnection.java",
"retrieved_chunk": " if (last_error != null) {\n String last_error_msg =\n \"Query retries (\"\n + this.max_num_retries\n + \") unsuccessful. Error occurred while executing the following query: \"\n + sqlText\n + \"; stack trace: \"\n + ExceptionUtils.getStackTrace(last_error);\n LOGGER.warn(last_error_msg);\n throw new ClientException(last_error_msg);",
"score": 24.119382519946143
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 23.52361496394271
}
] | java | size = queryResult.getValueListSize(); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.QueryResult;
import com.microsoft.lst_bench.exec.FileExec;
import com.microsoft.lst_bench.exec.StatementExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.StringUtils;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Custom task executor implementation that allows users to execute dependent tasks. We call a
* dependent task a task that iteratively executes a) a statement that is expected to return a
* result; and b) a statement repeatedly that is expected to use that result. The result of the
* first statement is stored in an intermediate object that can be specific to the connection. The
* expected object for a JDBC connection is of type List<Map<String, Object>>, handling of other
* objects would need to be added to the if-clause that checks the instance of the object.
*/
public class DependentTaskExecutor extends TaskExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(DependentTaskExecutor.class);
private final CustomTaskExecutorArguments arguments;
private final int DEFAULT_BATCH_SIZE = 1;
public DependentTaskExecutor(
SQLTelemetryRegistry telemetryRegistry,
String experimentStartTime,
CustomTaskExecutorArguments arguments) {
super(telemetryRegistry, experimentStartTime);
this.arguments = arguments;
}
@Override
public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)
throws ClientException {
int batch_size;
if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {
batch_size = DEFAULT_BATCH_SIZE;
} else {
batch_size = this.arguments.getDependentTaskBatchSize().intValue();
}
QueryResult queryResult = null;
for (FileExec file : task.getFiles()) {
Instant fileStartTime = Instant.now();
if | (file.getStatements().size() != 1) { |
writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);
throw new ClientException(
"For dependent task execution, statements have to be in separate files.");
}
StatementExec statement = file.getStatements().get(0);
try {
if (queryResult == null) {
// Execute first query that retrieves the iterable input for the second query.
Instant statementStartTime = Instant.now();
queryResult =
connection.executeQuery(
StringUtils.replaceParameters(statement, values).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
if (queryResult == null || queryResult.containsEmptyResultColumnOnly()) {
// Reset queryResult variable if result is (intentionally) empty.
queryResult = null;
}
} else {
// Execute second query repeatedly with the parameters extracted from the first query.
Integer size = queryResult.getValueListSize();
for (int j = 0; j < size; j += batch_size) {
int localMax = (j + batch_size) > size ? size : (j + batch_size);
Map<String, Object> localValues = new HashMap<>(values);
localValues.putAll(queryResult.getStringMappings(j, localMax));
Instant statementStartTime = Instant.now();
connection.execute(
StringUtils.replaceParameters(statement, localValues).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
}
// Reset query result.
queryResult = null;
}
} catch (Exception e) {
LOGGER.error("Exception executing file: " + file.getId());
writeStatementEvent(
fileStartTime,
file.getId(),
Status.FAILURE,
/* payload= */ e.getMessage() + "; " + e.getStackTrace());
throw e;
}
writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);
}
}
}
| src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " this.experimentStartTime = experimentStartTime;\n this.telemetryRegistry = telemetryRegistry;\n }\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n try {\n for (StatementExec statement : file.getStatements()) {\n Instant statementStartTime = Instant.now();",
"score": 46.95846057066456
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/BenchmarkConfig.java",
"retrieved_chunk": " Map<String, String> metadata,\n Map<String, Object> arguments,\n WorkloadExec workload) {\n this.id = id;\n this.repetitions = repetitions;\n this.metadata = Collections.unmodifiableMap(metadata == null ? new HashMap<>() : metadata);\n this.arguments = Collections.unmodifiableMap(arguments == null ? new HashMap<>() : arguments);\n this.workload = workload;\n }\n public String getId() {",
"score": 43.8648643490938
},
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " Map<String, FileExec> idToFile = new HashMap<>();\n for (FileExec file : files) {\n idToFile.put(file.getId(), file);\n }\n int counter;\n if (Boolean.TRUE.equals(task.isPermuteOrder())) {\n counter =\n taskTemplateIdToPermuteOrderCounter.compute(\n taskTemplate.getId(), (k, v) -> v == null ? 1 : v + 1);\n } else {",
"score": 31.8477757094809
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " Instant startTime, String id, Status status, String payload) {\n EventInfo eventInfo = null;\n if (payload != null) {\n eventInfo =\n ImmutableEventInfo.of(\n experimentStartTime,\n startTime,\n Instant.now(),\n id,\n EventType.EXEC_STATEMENT,",
"score": 31.07602528438182
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " if (task.getTimeTravelPhaseId() != null) {\n Instant ttPhaseEndTime = this.phaseIdToEndTime.get(task.getTimeTravelPhaseId());\n if (ttPhaseEndTime == null) {\n throw new RuntimeException(\n \"Time travel phase identifier not found: \" + task.getTimeTravelPhaseId());\n }\n // We round to the next second to make sure we are capturing the changes in case\n // are consecutive phases\n String timeTravelValue =\n DateTimeFormatter.AS_OF_FORMATTER.format(",
"score": 28.25992567199492
}
] | java | (file.getStatements().size() != 1) { |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.QueryResult;
import com.microsoft.lst_bench.exec.FileExec;
import com.microsoft.lst_bench.exec.StatementExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.StringUtils;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Custom task executor implementation that allows users to execute dependent tasks. We call a
* dependent task a task that iteratively executes a) a statement that is expected to return a
* result; and b) a statement repeatedly that is expected to use that result. The result of the
* first statement is stored in an intermediate object that can be specific to the connection. The
* expected object for a JDBC connection is of type List<Map<String, Object>>, handling of other
* objects would need to be added to the if-clause that checks the instance of the object.
*/
public class DependentTaskExecutor extends TaskExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(DependentTaskExecutor.class);
private final CustomTaskExecutorArguments arguments;
private final int DEFAULT_BATCH_SIZE = 1;
public DependentTaskExecutor(
SQLTelemetryRegistry telemetryRegistry,
String experimentStartTime,
CustomTaskExecutorArguments arguments) {
super(telemetryRegistry, experimentStartTime);
this.arguments = arguments;
}
@Override
public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)
throws ClientException {
int batch_size;
if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {
batch_size = DEFAULT_BATCH_SIZE;
} else {
batch_size = this.arguments.getDependentTaskBatchSize().intValue();
}
QueryResult queryResult = null;
for (FileExec file : task.getFiles()) {
Instant fileStartTime = Instant.now();
if (file.getStatements().size() != 1) {
writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);
throw new ClientException(
"For dependent task execution, statements have to be in separate files.");
}
StatementExec statement = file.getStatements().get(0);
try {
if (queryResult == null) {
// Execute first query that retrieves the iterable input for the second query.
Instant statementStartTime = Instant.now();
queryResult =
connection.executeQuery(
StringUtils.replaceParameters(statement, values).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
if (queryResult == null || queryResult.containsEmptyResultColumnOnly()) {
// Reset queryResult variable if result is (intentionally) empty.
queryResult = null;
}
} else {
// Execute second query repeatedly with the parameters extracted from the first query.
Integer size = queryResult.getValueListSize();
for (int j = 0; j < size; j += batch_size) {
int localMax = (j + batch_size) > size ? size : (j + batch_size);
Map<String, Object> localValues = new HashMap<>(values);
localValues | .putAll(queryResult.getStringMappings(j, localMax)); |
Instant statementStartTime = Instant.now();
connection.execute(
StringUtils.replaceParameters(statement, localValues).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
}
// Reset query result.
queryResult = null;
}
} catch (Exception e) {
LOGGER.error("Exception executing file: " + file.getId());
writeStatementEvent(
fileStartTime,
file.getId(),
Status.FAILURE,
/* payload= */ e.getMessage() + "; " + e.getStackTrace());
throw e;
}
writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);
}
}
}
| src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/client/QueryResult.java",
"retrieved_chunk": " valueList.put(rsmd.getColumnName(j), new ArrayList<>());\n }\n while (rs.next()) {\n for (int j = 1; j <= rsmd.getColumnCount(); j++) {\n valueList.get(rsmd.getColumnName(j)).add(rs.getObject(j));\n }\n }\n }\n public Integer getValueListSize() {\n Integer size = null;",
"score": 86.88917477572781
},
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " Map<String, TaskTemplate> idToTaskTemplate,\n ExperimentConfig experimentConfig,\n Map<String, Integer> taskTemplateIdToPermuteOrderCounter,\n Map<String, Integer> taskTemplateIdToParameterValuesCounter) {\n List<TaskExec> tasks = new ArrayList<>();\n for (int j = 0; j < session.getTasks().size(); j++) {\n Task task = session.getTasks().get(j);\n String taskId = task.getTemplateId() + \"_\" + j;\n TaskExec taskExec =\n createTaskExec(",
"score": 77.54425519563523
},
{
"filename": "src/main/java/com/microsoft/lst_bench/client/QueryResult.java",
"retrieved_chunk": " private final Map<String, List<Object>> valueList;\n private static final String RESULT = \"Result\";\n public QueryResult() {\n this.valueList = new HashMap<>();\n }\n // TODO: Determine whether this can be done lazily i.e., after the statement has finished\n // executing and the query is not timed anymore.\n public void populate(ResultSet rs) throws SQLException {\n ResultSetMetaData rsmd = rs.getMetaData();\n for (int j = 1; j <= rsmd.getColumnCount(); j++) {",
"score": 61.52054298543937
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/FileParser.java",
"retrieved_chunk": " }\n try (BufferedReader br =\n new BufferedReader(\n new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8))) {\n String header = br.readLine();\n String line = null;\n for (int j = 1; j <= counter; j++) {\n line = br.readLine();\n }\n if (line == null) {",
"score": 61.0274367685147
},
{
"filename": "src/main/java/com/microsoft/lst_bench/client/QueryResult.java",
"retrieved_chunk": " return true;\n }\n return false;\n }\n public Map<String, Object> getStringMappings(int listMin, int listMax) {\n Map<String, Object> result = new HashMap<>();\n for (String key : this.valueList.keySet()) {\n List<String> localList =\n this.valueList.get(key).subList(listMin, listMax).stream()\n .map(s -> s.toString())",
"score": 26.753050409142418
}
] | java | .putAll(queryResult.getStringMappings(j, localMax)); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.exec.FileExec;
import com.microsoft.lst_bench.exec.StatementExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.StringUtils;
import java.time.Instant;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default executor for tasks. Iterates over all files and all the statements contained in those
* files and executes them sequentially.
*/
public class TaskExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutor.class);
protected final SQLTelemetryRegistry telemetryRegistry;
protected final String experimentStartTime;
public TaskExecutor(SQLTelemetryRegistry telemetryRegistry, String experimentStartTime) {
this.experimentStartTime = experimentStartTime;
this.telemetryRegistry = telemetryRegistry;
}
public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)
throws ClientException {
for (FileExec file : task.getFiles()) {
Instant fileStartTime = Instant.now();
try {
for (StatementExec statement : file.getStatements()) {
Instant statementStartTime = Instant.now();
try {
connection.execute(StringUtils.replaceParameters(statement, values).getStatement());
} catch (Exception e) {
LOGGER.error("Exception executing statement: " + statement.getId());
writeStatementEvent(
statementStartTime,
| statement.getId(),
Status.FAILURE,
e.getMessage() + "; | " + e.getStackTrace());
throw e;
}
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
}
} catch (Exception e) {
LOGGER.error("Exception executing file: " + file.getId());
writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);
throw e;
}
writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);
}
}
protected final EventInfo writeFileEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_FILE, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
protected final EventInfo writeStatementEvent(
Instant startTime, String id, Status status, String payload) {
EventInfo eventInfo = null;
if (payload != null) {
eventInfo =
ImmutableEventInfo.of(
experimentStartTime,
startTime,
Instant.now(),
id,
EventType.EXEC_STATEMENT,
status)
.withPayload(payload);
} else {
eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_STATEMENT, status);
}
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " StringUtils.replaceParameters(statement, localValues).getStatement());\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n // Reset query result.\n queryResult = null;\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeStatementEvent(",
"score": 90.30398885350509
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " // Execute first query that retrieves the iterable input for the second query.\n Instant statementStartTime = Instant.now();\n queryResult =\n connection.executeQuery(\n StringUtils.replaceParameters(statement, values).getStatement());\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n if (queryResult == null || queryResult.containsEmptyResultColumnOnly()) {\n // Reset queryResult variable if result is (intentionally) empty.\n queryResult = null;",
"score": 67.92740464791947
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " Instant taskStartTime = Instant.now();\n try {\n taskExecutor.executeTask(connection, task, values);\n } catch (Exception e) {\n LOGGER.error(\"Exception executing task: \" + task.getId());\n writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);\n throw e;\n }\n writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);\n }",
"score": 65.76407040153342
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java",
"retrieved_chunk": " Status.SUCCESS,\n new ObjectMapper().writeValueAsString(experimentMetadata));\n } catch (Exception e) {\n LOGGER.error(\"Exception executing experiment: \" + config.getId());\n writeExperimentEvent(\n repetitionStartTime,\n config.getId(),\n Status.FAILURE,\n new ObjectMapper().writeValueAsString(experimentMetadata));\n throw e;",
"score": 46.712842846092336
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java",
"retrieved_chunk": " }\n checkResults(executor.invokeAll(threads));\n eventInfo = writePhaseEvent(phaseStartTime, phase.getId(), Status.SUCCESS);\n } catch (Exception e) {\n LOGGER.error(\"Exception executing phase: \" + phase.getId());\n writePhaseEvent(phaseStartTime, phase.getId(), Status.FAILURE);\n throw e;\n } finally {\n telemetryRegistry.flush();\n }",
"score": 45.6282822576017
}
] | java | statement.getId(),
Status.FAILURE,
e.getMessage() + "; |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.util;
import com.microsoft.lst_bench.exec.FileExec;
import com.microsoft.lst_bench.exec.ImmutableFileExec;
import com.microsoft.lst_bench.exec.ImmutableStatementExec;
import com.microsoft.lst_bench.exec.StatementExec;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.text.StringSubstitutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Utility class for string operations. */
public class StringUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(StringUtils.class);
private StringUtils() {
// Defeat instantiation
}
public static String format(String format, Map<String, Object> values) {
return StringSubstitutor.replace(format, values);
}
public static String quote(String str) {
if (str == null) {
return null;
}
return "'" + str + "'";
}
public static StatementExec replaceParameters(
StatementExec statement, Map<String, Object> parameterValues) {
if (parameterValues == null || parameterValues.isEmpty()) {
// Nothing to do
return statement;
}
return ImmutableStatementExec.of(
| statement.getId(), StringUtils.format(statement.getStatement(), parameterValues)); |
}
public static FileExec replaceParameters(FileExec file, Map<String, Object> parameterValues) {
if (parameterValues == null || parameterValues.isEmpty()) {
// Nothing to do
return file;
}
return ImmutableFileExec.of(
file.getId(),
file.getStatements().stream()
.map(s -> replaceParameters(s, parameterValues))
.collect(Collectors.toList()));
}
public static FileExec replaceRegex(FileExec f, String regex, String replacement) {
Pattern pattern = Pattern.compile(regex);
return ImmutableFileExec.of(
f.getId(),
f.getStatements().stream()
.map(
s ->
ImmutableStatementExec.of(
s.getId(), pattern.matcher(s.getStatement()).replaceAll(replacement)))
.collect(Collectors.toList()));
}
/**
* Reads the contents of the `sourceFile` and replaces any environment variables if present. If
* the environment variable is not set, the default value is used if specified. All other
* parameters are ignored.
*/
public static String replaceEnvVars(File sourceFile) throws IOException {
if (sourceFile == null || !sourceFile.isFile()) {
// Nothing to do.
LOGGER.debug("replaceEnvVars received a null or missing file.");
return null;
}
StringSubstitutor envSub = new StringSubstitutor(System.getenv());
return envSub.replace(FileUtils.readFileToString(sourceFile, StandardCharsets.UTF_8));
}
}
| src/main/java/com/microsoft/lst_bench/util/StringUtils.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " // the task template)\n parameterValues.putAll(experimentConfig.getParameterValues());\n }\n return files.stream()\n .map(f -> StringUtils.replaceParameters(f, parameterValues))\n .collect(Collectors.toList());\n }\n}",
"score": 43.147491054022396
},
{
"filename": "src/main/java/com/microsoft/lst_bench/telemetry/SQLTelemetryRegistry.java",
"retrieved_chunk": " // Create the tables if they don't exist.\n if (executeDdl) {\n executeDdl(ddlFile, parameterValues);\n }\n }\n private void executeDdl(String ddlFile, Map<String, Object> parameterValues)\n throws ClientException {\n LOGGER.info(\"Creating new logging tables...\");\n try (Connection connection = connectionManager.createConnection()) {\n List<StatementExec> ddlFileStatements = SQLParser.getStatements(ddlFile).getStatements();",
"score": 41.506052899134275
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 40.416931646786004
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " StringUtils.replaceParameters(statement, localValues).getStatement());\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n // Reset query result.\n queryResult = null;\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeStatementEvent(",
"score": 39.993144411601136
},
{
"filename": "src/main/java/com/microsoft/lst_bench/telemetry/SQLTelemetryRegistry.java",
"retrieved_chunk": " for (StatementExec query : ddlFileStatements) {\n String currentQuery = StringUtils.replaceParameters(query, parameterValues).getStatement();\n connection.execute(currentQuery);\n }\n }\n LOGGER.info(\"Logging tables created.\");\n }\n /** Inserts an event into the stream. */\n public void writeEvent(EventInfo eventInfo) {\n eventsStream.add(eventInfo);",
"score": 38.158960575368646
}
] | java | statement.getId(), StringUtils.format(statement.getStatement(), parameterValues)); |
package com.minivv.pilot.state;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.minivv.pilot.action.BasePilotPluginAction;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.AppSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@State(
name = "chatGptPilot.idea.plugin",
storages = {@Storage("setting.xml")}
)
public class AppSettingsStorage implements PersistentStateComponent<AppSettings> {
private AppSettings settings = new AppSettings();
private final String idPrefix = "chatGptPilot_";
private final DefaultActionGroup actionGroup = new DefaultActionGroup("gpt pilot", true);
@Nullable
@Override
public AppSettings getState() {
if (settings == null) {
settings = new AppSettings();
}
return settings;
}
@Override
public void loadState(@NotNull AppSettings state) {
settings = state;
if(settings.prompts != null && settings.prompts.getPrompts().isEmpty()) {
AppSettings.addDefaultPrompts(settings.prompts);
}
}
public static AppSettingsStorage getInstance() {
return ApplicationManager.getApplication().getService(AppSettingsStorage.class);
}
public static @NotNull Project getProject() {
return ApplicationManager.getApplication().getService(ProjectManager.class).getOpenProjects()[0];
}
// public void registerActions() {
// ActionManager actionManager = ActionManager.getInstance();
// clear(actionGroup);
// AnAction popupMenu = actionManager.getAction("EditorPopupMenu");
// for (Prompt prompt : this.settings.prompts.getPrompts()) {
// BasePilotPluginAction newAction = new BasePilotPluginAction(prompt.getOption(), prompt.getIndex()) {
// @Override
// public String addStatement(String code) {
// return prompt.getSnippet().replace("{query}", code);
// }
// };
// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);
// actionGroup.add(newAction);
// }
// ((DefaultActionGroup) popupMenu).add(actionGroup);
// }
public void registerActions() {
ActionManager actionManager = ActionManager.getInstance();
DefaultActionGroup popupMenu = (DefaultActionGroup) actionManager.getAction("EditorPopupMenu");
clear(popupMenu, actionGroup);
for (Prompt prompt : this.settings.prompts.getPrompts()) {
AnAction oldAction = actionManager.getAction(idPrefix + prompt.getOption());
if (oldAction != null) {
actionManager.unregisterAction(idPrefix + prompt.getOption());
}
oldAction = new BasePilotPluginAction | (prompt.getOption()) { |
@Override
public String addStatement(String code) {
return prompt.getSnippet().replace("{query}", code);
}
};
actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);
actionGroup.add(oldAction);
}
popupMenu.add(actionGroup);
}
private static void clear(DefaultActionGroup popupMenu, DefaultActionGroup actionGroup) {
popupMenu.remove(actionGroup);
AnAction[] childActionsOrStubs = actionGroup.getChildActionsOrStubs();
for (AnAction childActionsOrStub : childActionsOrStubs) {
actionGroup.remove(childActionsOrStub);
}
}
// public void unregisterActions() {
// ActionManager actionManager = ActionManager.getInstance();
// for (Prompt prompt : this.settings.prompts.getPrompts()) {
// actionManager.unregisterAction(idPrefix + prompt.getIndex());
// }
// }
public void unregisterActions() {
ActionManager actionManager = ActionManager.getInstance();
for (Prompt prompt : this.settings.prompts.getPrompts()) {
actionManager.unregisterAction(idPrefix + prompt.getOption());
}
}
} | src/main/java/com/minivv/pilot/state/AppSettingsStorage.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " return prompts;\n }\n public void setPrompts(List<Prompt> prompts) {\n this.prompts = prompts;\n }\n// public boolean add(Prompt o) {\n// if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()) || Objects.equals(prompt.getIndex(),o.getIndex()))) {\n// return false;\n// }\n// return prompts.add(o);",
"score": 34.39425464507772
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " }\n return prompts.add(o);\n }\n public int size() {\n return prompts.size();\n }\n public Map<String, String> asMap() {\n HashMap<String, String> stringStringHashMap = new HashMap<>();\n for (Prompt prompt : prompts) {\n stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());",
"score": 33.543855376491706
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "// }\n// public void add(String s, String to,int index) {\n// prompts.add(new Prompt(s, to,index));\n// }\n public void add(String s, String to) {\n prompts.add(new Prompt(s, to));\n }\n public boolean add(Prompt o) {\n if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {\n return false;",
"score": 29.54338442492571
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 27.97663762494173
},
{
"filename": "src/main/java/com/minivv/pilot/utils/GPTClient.java",
"retrieved_chunk": " .prompt(code)\n .model(settings.gptModel)\n .maxTokens(settings.gptMaxTokens)\n .temperature(0.3)\n .presencePenalty(0.0)\n .frequencyPenalty(0.0)\n .bestOf(1)\n .stream(false)\n .echo(false)\n .build();",
"score": 14.141506606480675
}
] | java | (prompt.getOption()) { |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.QueryResult;
import com.microsoft.lst_bench.exec.FileExec;
import com.microsoft.lst_bench.exec.StatementExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.StringUtils;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Custom task executor implementation that allows users to execute dependent tasks. We call a
* dependent task a task that iteratively executes a) a statement that is expected to return a
* result; and b) a statement repeatedly that is expected to use that result. The result of the
* first statement is stored in an intermediate object that can be specific to the connection. The
* expected object for a JDBC connection is of type List<Map<String, Object>>, handling of other
* objects would need to be added to the if-clause that checks the instance of the object.
*/
public class DependentTaskExecutor extends TaskExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(DependentTaskExecutor.class);
private final CustomTaskExecutorArguments arguments;
private final int DEFAULT_BATCH_SIZE = 1;
public DependentTaskExecutor(
SQLTelemetryRegistry telemetryRegistry,
String experimentStartTime,
CustomTaskExecutorArguments arguments) {
super(telemetryRegistry, experimentStartTime);
this.arguments = arguments;
}
@Override
public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)
throws ClientException {
int batch_size;
if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {
batch_size = DEFAULT_BATCH_SIZE;
} else {
batch_size = this.arguments.getDependentTaskBatchSize().intValue();
}
QueryResult queryResult = null;
for (FileExec file : task.getFiles()) {
Instant fileStartTime = Instant.now();
if (file.getStatements().size() != 1) {
writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);
throw new ClientException(
"For dependent task execution, statements have to be in separate files.");
}
StatementExec statement = file.getStatements().get(0);
try {
if (queryResult == null) {
// Execute first query that retrieves the iterable input for the second query.
Instant statementStartTime = Instant.now();
queryResult =
connection.executeQuery(
StringUtils.replaceParameters(statement, values).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
| if (queryResult == null || queryResult.containsEmptyResultColumnOnly()) { |
// Reset queryResult variable if result is (intentionally) empty.
queryResult = null;
}
} else {
// Execute second query repeatedly with the parameters extracted from the first query.
Integer size = queryResult.getValueListSize();
for (int j = 0; j < size; j += batch_size) {
int localMax = (j + batch_size) > size ? size : (j + batch_size);
Map<String, Object> localValues = new HashMap<>(values);
localValues.putAll(queryResult.getStringMappings(j, localMax));
Instant statementStartTime = Instant.now();
connection.execute(
StringUtils.replaceParameters(statement, localValues).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
}
// Reset query result.
queryResult = null;
}
} catch (Exception e) {
LOGGER.error("Exception executing file: " + file.getId());
writeStatementEvent(
fileStartTime,
file.getId(),
Status.FAILURE,
/* payload= */ e.getMessage() + "; " + e.getStackTrace());
throw e;
}
writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);
}
}
}
| src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 56.94898660679003
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " }\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);",
"score": 51.34643424671064
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " this.experimentStartTime = experimentStartTime;\n this.telemetryRegistry = telemetryRegistry;\n }\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n try {\n for (StatementExec statement : file.getStatements()) {\n Instant statementStartTime = Instant.now();",
"score": 41.90177682317887
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " Instant startTime, String id, Status status, String payload) {\n EventInfo eventInfo = null;\n if (payload != null) {\n eventInfo =\n ImmutableEventInfo.of(\n experimentStartTime,\n startTime,\n Instant.now(),\n id,\n EventType.EXEC_STATEMENT,",
"score": 41.84084495971732
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": " }\n return ImmutableStatementExec.of(\n statement.getId(), StringUtils.format(statement.getStatement(), parameterValues));\n }\n public static FileExec replaceParameters(FileExec file, Map<String, Object> parameterValues) {\n if (parameterValues == null || parameterValues.isEmpty()) {\n // Nothing to do\n return file;\n }\n return ImmutableFileExec.of(",
"score": 37.31102134997721
}
] | java | if (queryResult == null || queryResult.containsEmptyResultColumnOnly()) { |
package com.minivv.pilot.model;
import java.util.*;
public class Prompts extends DomainObject {
private List<Prompt> prompts = new ArrayList<>();
public Prompts() {
}
public Prompts(List<Prompt> prompts) {
this.prompts = prompts;
}
public List<Prompt> getPrompts() {
return prompts;
}
public void setPrompts(List<Prompt> prompts) {
this.prompts = prompts;
}
// public boolean add(Prompt o) {
// if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()) || Objects.equals(prompt.getIndex(),o.getIndex()))) {
// return false;
// }
// return prompts.add(o);
// }
// public void add(String s, String to,int index) {
// prompts.add(new Prompt(s, to,index));
// }
public void add(String s, String to) {
prompts.add(new Prompt(s, to));
}
public boolean add(Prompt o) {
if (prompts.stream | ().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) { |
return false;
}
return prompts.add(o);
}
public int size() {
return prompts.size();
}
public Map<String, String> asMap() {
HashMap<String, String> stringStringHashMap = new HashMap<>();
for (Prompt prompt : prompts) {
stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());
}
return stringStringHashMap;
}
public void clear() {
this.prompts = new ArrayList<>();
}
} | src/main/java/com/minivv/pilot/model/Prompts.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " Prompts prompts = addDefaultPrompts(new Prompts());\n Map<String, String> stringStringMap = prompts.asMap();\n _prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));\n _prompts.addAll(prompts.getPrompts());\n }\n @Transient\n public static Prompts addDefaultPrompts(Prompts prompts) {\n prompts.add(Prompt.of(\"Readable\", \"help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}\"));\n prompts.add(Prompt.of(\"List Steps\", \"help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}\"));\n prompts.add(Prompt.of(\"Explain\", \"帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}\"));",
"score": 40.0429131519586
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " @Override\n public String addStatement(String code) {\n return prompt.getSnippet().replace(\"{query}\", code);\n }\n };\n actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);\n actionGroup.add(oldAction);\n }\n popupMenu.add(actionGroup);\n }",
"score": 39.87007693477423
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 37.9384100896752
},
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " prompts.add(Prompt.of(\"步骤注释\", \"帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}\"));\n prompts.add(Prompt.of(\"emptyForYou\", \"balabala{query}\"));\n return prompts;\n }\n}",
"score": 34.42754848189268
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// @Override\n// public String addStatement(String code) {\n// return prompt.getSnippet().replace(\"{query}\", code);\n// }\n// };\n// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);\n// actionGroup.add(newAction);\n// }\n// ((DefaultActionGroup) popupMenu).add(actionGroup);\n// }",
"score": 33.74097131015408
}
] | java | ().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) { |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.exec.FileExec;
import com.microsoft.lst_bench.exec.StatementExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.StringUtils;
import java.time.Instant;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default executor for tasks. Iterates over all files and all the statements contained in those
* files and executes them sequentially.
*/
public class TaskExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutor.class);
protected final SQLTelemetryRegistry telemetryRegistry;
protected final String experimentStartTime;
public TaskExecutor(SQLTelemetryRegistry telemetryRegistry, String experimentStartTime) {
this.experimentStartTime = experimentStartTime;
this.telemetryRegistry = telemetryRegistry;
}
public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)
throws ClientException {
for (FileExec file : task.getFiles()) {
Instant fileStartTime = Instant.now();
try {
for (StatementExec statement : file.getStatements()) {
Instant statementStartTime = Instant.now();
try {
connection.execute(StringUtils.replaceParameters(statement, values).getStatement());
} catch (Exception e) {
LOGGER.error("Exception executing statement: " | + statement.getId()); |
writeStatementEvent(
statementStartTime,
statement.getId(),
Status.FAILURE,
e.getMessage() + "; " + e.getStackTrace());
throw e;
}
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
}
} catch (Exception e) {
LOGGER.error("Exception executing file: " + file.getId());
writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);
throw e;
}
writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);
}
}
protected final EventInfo writeFileEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_FILE, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
protected final EventInfo writeStatementEvent(
Instant startTime, String id, Status status, String payload) {
EventInfo eventInfo = null;
if (payload != null) {
eventInfo =
ImmutableEventInfo.of(
experimentStartTime,
startTime,
Instant.now(),
id,
EventType.EXEC_STATEMENT,
status)
.withPayload(payload);
} else {
eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_STATEMENT, status);
}
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n if (file.getStatements().size() != 1) {\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw new ClientException(\n \"For dependent task execution, statements have to be in separate files.\");\n }\n StatementExec statement = file.getStatements().get(0);\n try {\n if (queryResult == null) {",
"score": 75.07510164334896
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " StringUtils.replaceParameters(statement, localValues).getStatement());\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n // Reset query result.\n queryResult = null;\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeStatementEvent(",
"score": 71.69903045713785
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " Instant taskStartTime = Instant.now();\n try {\n taskExecutor.executeTask(connection, task, values);\n } catch (Exception e) {\n LOGGER.error(\"Exception executing task: \" + task.getId());\n writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);\n throw e;\n }\n writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);\n }",
"score": 69.02794989229523
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " // Execute first query that retrieves the iterable input for the second query.\n Instant statementStartTime = Instant.now();\n queryResult =\n connection.executeQuery(\n StringUtils.replaceParameters(statement, values).getStatement());\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n if (queryResult == null || queryResult.containsEmptyResultColumnOnly()) {\n // Reset queryResult variable if result is (intentionally) empty.\n queryResult = null;",
"score": 65.25695464426038
},
{
"filename": "src/main/java/com/microsoft/lst_bench/sql/SQLParser.java",
"retrieved_chunk": " new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8))) {\n int i = 0;\n for (; ; ) {\n String statement;\n try {\n statement = nextStatement(br);\n } catch (IOException e) {\n throw new RuntimeException(\"Error while reading next statement\", e);\n }\n if (statement == null) {",
"score": 43.85108990229705
}
] | java | + statement.getId()); |
package com.minivv.pilot.ui;
import com.intellij.openapi.diagnostic.Logger;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.AppSettings;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PromptsTable extends JTable {
private static final Logger LOG = Logger.getInstance(PromptsTable.class);
private static final int NAME_COLUMN = 0;
private static final int VALUE_COLUMN = 1;
private final PromptTableModel promptTableModel = new PromptTableModel();
public final List<Prompt> prompts = new ArrayList<>();
public PromptsTable() {
setModel(promptTableModel);
DefaultCellEditor editor = new DefaultCellEditor(new JTextField());
this.setCellEditor(editor);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
public void reset(AppSettings settings) {
obtainPrompts(prompts, settings);
promptTableModel.fireTableDataChanged();
}
public boolean isModified(AppSettings settings) {
final ArrayList<Prompt> _prompts = new ArrayList<>();
obtainPrompts(_prompts, settings);
return !_prompts.equals(prompts);
}
private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {
prompts.clear();
prompts.addAll(settings.prompts.getPrompts());
}
public void addPrompt(Prompt prompt) {
prompts.add(prompt);
promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);
}
public void commit(AppSettings settings) {
settings.prompts.setPrompts(new ArrayList<>(this.prompts));
}
public void removeSelectedPrompts() {
int[] selectedRows = getSelectedRows();
if (selectedRows.length == 0) return;
Arrays.sort(selectedRows);
final int originalRow = selectedRows[0];
for (int i = selectedRows.length - 1; i >= 0; i--) {
final int selectedRow = selectedRows[i];
if (isValidRow(selectedRow)) {
prompts.remove(selectedRow);
promptTableModel.fireTableRowsDeleted(selectedRow, selectedRow);
}
}
promptTableModel.fireTableDataChanged();
if (originalRow < getRowCount()) {
setRowSelectionInterval(originalRow, originalRow);
} else if (getRowCount() > 0) {
final int index = getRowCount() - 1;
setRowSelectionInterval(index, index);
}
}
private boolean isValidRow(int selectedRow) {
return selectedRow >= 0 && selectedRow < prompts.size();
}
public void resetDefaultAliases() {
AppSettings.resetDefaultPrompts(prompts);
promptTableModel.fireTableDataChanged();
}
public boolean editPrompt() {
if (getSelectedRowCount() != 1) {
return false;
}
//进入行内编辑模式
return editCellAt(getSelectedRow(), getSelectedColumn());
}
private class PromptTableModel extends AbstractTableModel {
@Override
public int getColumnCount() {
return 2;
}
@Override
public int getRowCount() {
return prompts.size();
}
@Override
public Class getColumnClass(int columnIndex) {
return String.class;
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
String str = (String) value;
if (str.length() != 0) {
//修改prompts中的值
if (columnIndex == NAME_COLUMN) {
prompts.get(rowIndex).setOption(str);
} else if (columnIndex == VALUE_COLUMN) {
prompts.get | (rowIndex).setSnippet(str); |
}
promptTableModel.fireTableDataChanged();
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
final Prompt pair = prompts.get(rowIndex);
switch (columnIndex) {
case NAME_COLUMN:
return pair.getOption();
case VALUE_COLUMN:
return pair.getSnippet();
}
LOG.error("Wrong indices");
return null;
}
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case NAME_COLUMN:
return "Option";
case VALUE_COLUMN:
return "Snippet";
}
return null;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
}
}
| src/main/java/com/minivv/pilot/ui/PromptsTable.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "//\t\tthis.index = index;\n//\t}\n//\tpublic static Prompt of(String name, String value,int index) {\n//\t\treturn new Prompt(name, value,index);\n//\t}\n\tpublic Prompt(String option, String snippet) {\n\t\tthis.option = option;\n\t\tthis.snippet = snippet;\n\t}\n\tpublic static Prompt of(String name, String value) {",
"score": 19.220568146782963
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "\t\treturn new Prompt(name, value);\n\t}\n\tpublic String getOption() {\n\t\treturn option;\n\t}\n\tpublic void setOption(String option) {\n\t\tthis.option = option;\n\t}\n\tpublic String getSnippet() {\n\t\treturn snippet;",
"score": 18.257495019983672
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "// }\n// public void add(String s, String to,int index) {\n// prompts.add(new Prompt(s, to,index));\n// }\n public void add(String s, String to) {\n prompts.add(new Prompt(s, to));\n }\n public boolean add(Prompt o) {\n if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {\n return false;",
"score": 15.30153281040124
},
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " public Prompts prompts = new Prompts();\n public AppSettings() {\n this.addDefaultPrompts(this.prompts);\n }\n @NotNull\n public static Project getProject() {\n return AppSettingsStorage.getProject();\n }\n @NotNull\n public static AppSettings get() {",
"score": 14.12223143588177
},
{
"filename": "src/main/java/com/minivv/pilot/utils/GPTClient.java",
"retrieved_chunk": " }\n return choices.get(0).getText();\n }\n}",
"score": 14.11495454293188
}
] | java | (rowIndex).setSnippet(str); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.QueryResult;
import com.microsoft.lst_bench.exec.FileExec;
import com.microsoft.lst_bench.exec.StatementExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.StringUtils;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Custom task executor implementation that allows users to execute dependent tasks. We call a
* dependent task a task that iteratively executes a) a statement that is expected to return a
* result; and b) a statement repeatedly that is expected to use that result. The result of the
* first statement is stored in an intermediate object that can be specific to the connection. The
* expected object for a JDBC connection is of type List<Map<String, Object>>, handling of other
* objects would need to be added to the if-clause that checks the instance of the object.
*/
public class DependentTaskExecutor extends TaskExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(DependentTaskExecutor.class);
private final CustomTaskExecutorArguments arguments;
private final int DEFAULT_BATCH_SIZE = 1;
public DependentTaskExecutor(
SQLTelemetryRegistry telemetryRegistry,
String experimentStartTime,
CustomTaskExecutorArguments arguments) {
super(telemetryRegistry, experimentStartTime);
this.arguments = arguments;
}
@Override
public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)
throws ClientException {
int batch_size;
if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {
batch_size = DEFAULT_BATCH_SIZE;
} else {
batch_size = this.arguments.getDependentTaskBatchSize().intValue();
}
QueryResult queryResult = null;
for (FileExec file : task.getFiles()) {
Instant fileStartTime = Instant.now();
if (file.getStatements().size() != 1) {
writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);
throw new ClientException(
"For dependent task execution, statements have to be in separate files.");
}
StatementExec statement = file.getStatements().get(0);
try {
if (queryResult == null) {
// Execute first query that retrieves the iterable input for the second query.
Instant statementStartTime = Instant.now();
queryResult =
connection.executeQuery(
StringUtils.replaceParameters(statement, values).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
if (queryResult == null || queryResult.containsEmptyResultColumnOnly()) {
// Reset queryResult variable if result is (intentionally) empty.
queryResult = null;
}
} else {
// Execute second query repeatedly with the parameters extracted from the first query.
Integer size = queryResult.getValueListSize();
for (int j = 0; j < size; j += batch_size) {
int localMax = (j + batch_size) > size ? size : (j + batch_size);
Map<String, Object> localValues = new HashMap<>(values);
localValues.putAll(queryResult.getStringMappings(j, localMax));
Instant statementStartTime = Instant.now();
connection.execute(
StringUtils.replaceParameters(statement, localValues).getStatement());
writeStatementEvent(
statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);
}
// Reset query result.
queryResult = null;
}
} catch (Exception e) {
LOGGER.error("Exception executing file: " + file.getId());
writeStatementEvent(
fileStartTime,
| file.getId(),
Status.FAILURE,
/* payload= */ e.getMessage() + "; | " + e.getStackTrace());
throw e;
}
writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);
}
}
}
| src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " }\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);",
"score": 74.41233881463152
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 57.55401356565055
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java",
"retrieved_chunk": " Status.SUCCESS,\n new ObjectMapper().writeValueAsString(experimentMetadata));\n } catch (Exception e) {\n LOGGER.error(\"Exception executing experiment: \" + config.getId());\n writeExperimentEvent(\n repetitionStartTime,\n config.getId(),\n Status.FAILURE,\n new ObjectMapper().writeValueAsString(experimentMetadata));\n throw e;",
"score": 46.20389936243817
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java",
"retrieved_chunk": " }\n checkResults(executor.invokeAll(threads));\n eventInfo = writePhaseEvent(phaseStartTime, phase.getId(), Status.SUCCESS);\n } catch (Exception e) {\n LOGGER.error(\"Exception executing phase: \" + phase.getId());\n writePhaseEvent(phaseStartTime, phase.getId(), Status.FAILURE);\n throw e;\n } finally {\n telemetryRegistry.flush();\n }",
"score": 45.1543062281278
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " Instant taskStartTime = Instant.now();\n try {\n taskExecutor.executeTask(connection, task, values);\n } catch (Exception e) {\n LOGGER.error(\"Exception executing task: \" + task.getId());\n writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);\n throw e;\n }\n writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);\n }",
"score": 44.29572980972426
}
] | java | file.getId(),
Status.FAILURE,
/* payload= */ e.getMessage() + "; |
package com.minivv.pilot.model;
import java.util.*;
public class Prompts extends DomainObject {
private List<Prompt> prompts = new ArrayList<>();
public Prompts() {
}
public Prompts(List<Prompt> prompts) {
this.prompts = prompts;
}
public List<Prompt> getPrompts() {
return prompts;
}
public void setPrompts(List<Prompt> prompts) {
this.prompts = prompts;
}
// public boolean add(Prompt o) {
// if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()) || Objects.equals(prompt.getIndex(),o.getIndex()))) {
// return false;
// }
// return prompts.add(o);
// }
// public void add(String s, String to,int index) {
// prompts.add(new Prompt(s, to,index));
// }
public void add(String s, String to) {
prompts.add(new Prompt(s, to));
}
public boolean add(Prompt o) {
if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {
return false;
}
return prompts.add(o);
}
public int size() {
return prompts.size();
}
public Map<String, String> asMap() {
HashMap<String, String> stringStringHashMap = new HashMap<>();
for (Prompt prompt : prompts) {
| stringStringHashMap.put(prompt.getOption(), prompt.getSnippet()); |
}
return stringStringHashMap;
}
public void clear() {
this.prompts = new ArrayList<>();
}
} | src/main/java/com/minivv/pilot/model/Prompts.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 33.83575719944036
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " @Override\n public String addStatement(String code) {\n return prompt.getSnippet().replace(\"{query}\", code);\n }\n };\n actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);\n actionGroup.add(oldAction);\n }\n popupMenu.add(actionGroup);\n }",
"score": 28.37903454941659
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// actionManager.unregisterAction(idPrefix + prompt.getIndex());\n// }\n// }\n public void unregisterActions() {\n ActionManager actionManager = ActionManager.getInstance();\n for (Prompt prompt : this.settings.prompts.getPrompts()) {\n actionManager.unregisterAction(idPrefix + prompt.getOption());\n }\n }\n}",
"score": 26.41609416101708
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " public void registerActions() {\n ActionManager actionManager = ActionManager.getInstance();\n DefaultActionGroup popupMenu = (DefaultActionGroup) actionManager.getAction(\"EditorPopupMenu\");\n clear(popupMenu, actionGroup);\n for (Prompt prompt : this.settings.prompts.getPrompts()) {\n AnAction oldAction = actionManager.getAction(idPrefix + prompt.getOption());\n if (oldAction != null) {\n actionManager.unregisterAction(idPrefix + prompt.getOption());\n }\n oldAction = new BasePilotPluginAction(prompt.getOption()) {",
"score": 25.28142291397324
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// @Override\n// public String addStatement(String code) {\n// return prompt.getSnippet().replace(\"{query}\", code);\n// }\n// };\n// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);\n// actionGroup.add(newAction);\n// }\n// ((DefaultActionGroup) popupMenu).add(actionGroup);\n// }",
"score": 25.207886712648097
}
] | java | stringStringHashMap.put(prompt.getOption(), prompt.getSnippet()); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/** Utility class with methods to parse auxiliary files for the benchmark. */
public class FileParser {
private static final ObjectMapper yamlMapper = new YAMLMapper();
private FileParser() {
// Defeat instantiation
}
public static List<String> getPermutationOrder(String permutationOrdersDirectory, int counter) {
File directory = new File(permutationOrdersDirectory);
File[] files = directory.listFiles();
if (files == null) {
throw new IllegalArgumentException(
"Cannot find permutation order files in directory: " + permutationOrdersDirectory);
}
if (counter >= files.length) {
throw new IllegalArgumentException(
"Cannot find permutation order file with index: " + counter);
}
File file = files[counter];
List<String> permutationOrder = new ArrayList<>();
try (BufferedReader br =
new BufferedReader(
new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8))) {
String filename;
while ((filename = br.readLine()) != null) {
if (filename.startsWith("#") || filename.startsWith("--") || filename.isEmpty()) {
continue;
}
permutationOrder.add(filename);
}
} catch (IOException e) {
throw new RuntimeException(
"Cannot read permutation order file: " + file.getAbsolutePath(), e);
}
return permutationOrder;
}
public static Map<String, Object> getParameterValues(String parameterValuesFile, int counter) {
Map<String, Object> values = new HashMap<>();
File file = new File(parameterValuesFile);
if (!file.exists()) {
throw new IllegalArgumentException(
"Cannot find parameter values file: " + parameterValuesFile);
}
try (BufferedReader br =
new BufferedReader(
new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8))) {
String header = br.readLine();
String line = null;
for (int j = 1; j <= counter; j++) {
line = br.readLine();
}
if (line == null) {
throw new IllegalArgumentException("Cannot find parameter values with index: " + counter);
}
StringTokenizer stHeader = new StringTokenizer(header, "|");
StringTokenizer stLine = new StringTokenizer(line, "|");
while (stHeader.hasMoreTokens()) {
String headerToken = stHeader.nextToken();
String lineToken = stLine.nextToken();
values.put(headerToken, lineToken);
}
if (stLine.hasMoreTokens()) {
throw new IllegalArgumentException(
"Parameter values line " + counter + " has more values than header");
}
} catch (IOException e) {
throw new RuntimeException("Cannot read parameter values file: " + file.getAbsolutePath(), e);
}
return values;
}
/**
* Reads the YAML file and replaces all environment variables (if present). Creates and returns an
* object of `objectType` class.
*/
public static <T> T createObject(String filePath, Class<T> objectType) throws IOException {
return yamlMapper. | readValue(StringUtils.replaceEnvVars(new File(filePath)), objectType); |
}
}
| src/main/java/com/microsoft/lst_bench/util/FileParser.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": " .map(\n s ->\n ImmutableStatementExec.of(\n s.getId(), pattern.matcher(s.getStatement()).replaceAll(replacement)))\n .collect(Collectors.toList()));\n }\n /**\n * Reads the contents of the `sourceFile` and replaces any environment variables if present. If\n * the environment variable is not set, the default value is used if specified. All other\n * parameters are ignored.",
"score": 37.56464178857628
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": " */\n public static String replaceEnvVars(File sourceFile) throws IOException {\n if (sourceFile == null || !sourceFile.isFile()) {\n // Nothing to do.\n LOGGER.debug(\"replaceEnvVars received a null or missing file.\");\n return null;\n }\n StringSubstitutor envSub = new StringSubstitutor(System.getenv());\n return envSub.replace(FileUtils.readFileToString(sourceFile, StandardCharsets.UTF_8));\n }",
"score": 29.405277889497288
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": "/** Utility class for string operations. */\npublic class StringUtils {\n private static final Logger LOGGER = LoggerFactory.getLogger(StringUtils.class);\n private StringUtils() {\n // Defeat instantiation\n }\n public static String format(String format, Map<String, Object> values) {\n return StringSubstitutor.replace(format, values);\n }\n public static String quote(String str) {",
"score": 22.578173303036138
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": " }\n return ImmutableStatementExec.of(\n statement.getId(), StringUtils.format(statement.getStatement(), parameterValues));\n }\n public static FileExec replaceParameters(FileExec file, Map<String, Object> parameterValues) {\n if (parameterValues == null || parameterValues.isEmpty()) {\n // Nothing to do\n return file;\n }\n return ImmutableFileExec.of(",
"score": 21.08209929449756
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": "import org.slf4j.LoggerFactory;\n/**\n * Default executor for tasks. Iterates over all files and all the statements contained in those\n * files and executes them sequentially.\n */\npublic class TaskExecutor {\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutor.class);\n protected final SQLTelemetryRegistry telemetryRegistry;\n protected final String experimentStartTime;\n public TaskExecutor(SQLTelemetryRegistry telemetryRegistry, String experimentStartTime) {",
"score": 18.819918908349127
}
] | java | readValue(StringUtils.replaceEnvVars(new File(filePath)), objectType); |
package com.minivv.pilot.model;
import java.util.*;
public class Prompts extends DomainObject {
private List<Prompt> prompts = new ArrayList<>();
public Prompts() {
}
public Prompts(List<Prompt> prompts) {
this.prompts = prompts;
}
public List<Prompt> getPrompts() {
return prompts;
}
public void setPrompts(List<Prompt> prompts) {
this.prompts = prompts;
}
// public boolean add(Prompt o) {
// if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()) || Objects.equals(prompt.getIndex(),o.getIndex()))) {
// return false;
// }
// return prompts.add(o);
// }
// public void add(String s, String to,int index) {
// prompts.add(new Prompt(s, to,index));
// }
public void add(String s, String to) {
prompts.add(new Prompt(s, to));
}
public boolean add(Prompt o) {
if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {
return false;
}
return prompts.add(o);
}
public int size() {
return prompts.size();
}
public Map<String, String> asMap() {
HashMap<String, String> stringStringHashMap = new HashMap<>();
for (Prompt prompt : prompts) {
stringStringHashMap | .put(prompt.getOption(), prompt.getSnippet()); |
}
return stringStringHashMap;
}
public void clear() {
this.prompts = new ArrayList<>();
}
} | src/main/java/com/minivv/pilot/model/Prompts.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 33.83575719944036
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " @Override\n public String addStatement(String code) {\n return prompt.getSnippet().replace(\"{query}\", code);\n }\n };\n actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);\n actionGroup.add(oldAction);\n }\n popupMenu.add(actionGroup);\n }",
"score": 28.37903454941659
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// actionManager.unregisterAction(idPrefix + prompt.getIndex());\n// }\n// }\n public void unregisterActions() {\n ActionManager actionManager = ActionManager.getInstance();\n for (Prompt prompt : this.settings.prompts.getPrompts()) {\n actionManager.unregisterAction(idPrefix + prompt.getOption());\n }\n }\n}",
"score": 26.41609416101708
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " public void registerActions() {\n ActionManager actionManager = ActionManager.getInstance();\n DefaultActionGroup popupMenu = (DefaultActionGroup) actionManager.getAction(\"EditorPopupMenu\");\n clear(popupMenu, actionGroup);\n for (Prompt prompt : this.settings.prompts.getPrompts()) {\n AnAction oldAction = actionManager.getAction(idPrefix + prompt.getOption());\n if (oldAction != null) {\n actionManager.unregisterAction(idPrefix + prompt.getOption());\n }\n oldAction = new BasePilotPluginAction(prompt.getOption()) {",
"score": 25.28142291397324
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// @Override\n// public String addStatement(String code) {\n// return prompt.getSnippet().replace(\"{query}\", code);\n// }\n// };\n// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);\n// actionGroup.add(newAction);\n// }\n// ((DefaultActionGroup) popupMenu).add(actionGroup);\n// }",
"score": 25.207886712648097
}
] | java | .put(prompt.getOption(), prompt.getSnippet()); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.util;
import com.microsoft.lst_bench.exec.FileExec;
import com.microsoft.lst_bench.exec.ImmutableFileExec;
import com.microsoft.lst_bench.exec.ImmutableStatementExec;
import com.microsoft.lst_bench.exec.StatementExec;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.text.StringSubstitutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Utility class for string operations. */
public class StringUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(StringUtils.class);
private StringUtils() {
// Defeat instantiation
}
public static String format(String format, Map<String, Object> values) {
return StringSubstitutor.replace(format, values);
}
public static String quote(String str) {
if (str == null) {
return null;
}
return "'" + str + "'";
}
public static StatementExec replaceParameters(
StatementExec statement, Map<String, Object> parameterValues) {
if (parameterValues == null || parameterValues.isEmpty()) {
// Nothing to do
return statement;
}
return ImmutableStatementExec.of(
statement. | getId(), StringUtils.format(statement.getStatement(), parameterValues)); |
}
public static FileExec replaceParameters(FileExec file, Map<String, Object> parameterValues) {
if (parameterValues == null || parameterValues.isEmpty()) {
// Nothing to do
return file;
}
return ImmutableFileExec.of(
file.getId(),
file.getStatements().stream()
.map(s -> replaceParameters(s, parameterValues))
.collect(Collectors.toList()));
}
public static FileExec replaceRegex(FileExec f, String regex, String replacement) {
Pattern pattern = Pattern.compile(regex);
return ImmutableFileExec.of(
f.getId(),
f.getStatements().stream()
.map(
s ->
ImmutableStatementExec.of(
s.getId(), pattern.matcher(s.getStatement()).replaceAll(replacement)))
.collect(Collectors.toList()));
}
/**
* Reads the contents of the `sourceFile` and replaces any environment variables if present. If
* the environment variable is not set, the default value is used if specified. All other
* parameters are ignored.
*/
public static String replaceEnvVars(File sourceFile) throws IOException {
if (sourceFile == null || !sourceFile.isFile()) {
// Nothing to do.
LOGGER.debug("replaceEnvVars received a null or missing file.");
return null;
}
StringSubstitutor envSub = new StringSubstitutor(System.getenv());
return envSub.replace(FileUtils.readFileToString(sourceFile, StandardCharsets.UTF_8));
}
}
| src/main/java/com/microsoft/lst_bench/util/StringUtils.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/telemetry/SQLTelemetryRegistry.java",
"retrieved_chunk": " // Create the tables if they don't exist.\n if (executeDdl) {\n executeDdl(ddlFile, parameterValues);\n }\n }\n private void executeDdl(String ddlFile, Map<String, Object> parameterValues)\n throws ClientException {\n LOGGER.info(\"Creating new logging tables...\");\n try (Connection connection = connectionManager.createConnection()) {\n List<StatementExec> ddlFileStatements = SQLParser.getStatements(ddlFile).getStatements();",
"score": 41.506052899134275
},
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " // the task template)\n parameterValues.putAll(experimentConfig.getParameterValues());\n }\n return files.stream()\n .map(f -> StringUtils.replaceParameters(f, parameterValues))\n .collect(Collectors.toList());\n }\n}",
"score": 40.59547464354363
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 40.416931646786004
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " StringUtils.replaceParameters(statement, localValues).getStatement());\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n // Reset query result.\n queryResult = null;\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeStatementEvent(",
"score": 39.993144411601136
},
{
"filename": "src/main/java/com/microsoft/lst_bench/telemetry/SQLTelemetryRegistry.java",
"retrieved_chunk": " for (StatementExec query : ddlFileStatements) {\n String currentQuery = StringUtils.replaceParameters(query, parameterValues).getStatement();\n connection.execute(currentQuery);\n }\n }\n LOGGER.info(\"Logging tables created.\");\n }\n /** Inserts an event into the stream. */\n public void writeEvent(EventInfo eventInfo) {\n eventsStream.add(eventInfo);",
"score": 38.158960575368646
}
] | java | getId(), StringUtils.format(statement.getStatement(), parameterValues)); |
package com.minivv.pilot.model;
import java.util.*;
public class Prompts extends DomainObject {
private List<Prompt> prompts = new ArrayList<>();
public Prompts() {
}
public Prompts(List<Prompt> prompts) {
this.prompts = prompts;
}
public List<Prompt> getPrompts() {
return prompts;
}
public void setPrompts(List<Prompt> prompts) {
this.prompts = prompts;
}
// public boolean add(Prompt o) {
// if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()) || Objects.equals(prompt.getIndex(),o.getIndex()))) {
// return false;
// }
// return prompts.add(o);
// }
// public void add(String s, String to,int index) {
// prompts.add(new Prompt(s, to,index));
// }
public void add(String s, String to) {
prompts.add(new Prompt(s, to));
}
public boolean add(Prompt o) {
if (prompts. | stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) { |
return false;
}
return prompts.add(o);
}
public int size() {
return prompts.size();
}
public Map<String, String> asMap() {
HashMap<String, String> stringStringHashMap = new HashMap<>();
for (Prompt prompt : prompts) {
stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());
}
return stringStringHashMap;
}
public void clear() {
this.prompts = new ArrayList<>();
}
} | src/main/java/com/minivv/pilot/model/Prompts.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " Prompts prompts = addDefaultPrompts(new Prompts());\n Map<String, String> stringStringMap = prompts.asMap();\n _prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));\n _prompts.addAll(prompts.getPrompts());\n }\n @Transient\n public static Prompts addDefaultPrompts(Prompts prompts) {\n prompts.add(Prompt.of(\"Readable\", \"help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}\"));\n prompts.add(Prompt.of(\"List Steps\", \"help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}\"));\n prompts.add(Prompt.of(\"Explain\", \"帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}\"));",
"score": 40.0429131519586
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " @Override\n public String addStatement(String code) {\n return prompt.getSnippet().replace(\"{query}\", code);\n }\n };\n actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);\n actionGroup.add(oldAction);\n }\n popupMenu.add(actionGroup);\n }",
"score": 39.87007693477423
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 37.9384100896752
},
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " prompts.add(Prompt.of(\"步骤注释\", \"帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}\"));\n prompts.add(Prompt.of(\"emptyForYou\", \"balabala{query}\"));\n return prompts;\n }\n}",
"score": 34.42754848189268
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// @Override\n// public String addStatement(String code) {\n// return prompt.getSnippet().replace(\"{query}\", code);\n// }\n// };\n// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);\n// actionGroup.add(newAction);\n// }\n// ((DefaultActionGroup) popupMenu).add(actionGroup);\n// }",
"score": 33.74097131015408
}
] | java | stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) { |
package com.minivv.pilot.ui;
import com.intellij.openapi.diagnostic.Logger;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.AppSettings;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PromptsTable extends JTable {
private static final Logger LOG = Logger.getInstance(PromptsTable.class);
private static final int NAME_COLUMN = 0;
private static final int VALUE_COLUMN = 1;
private final PromptTableModel promptTableModel = new PromptTableModel();
public final List<Prompt> prompts = new ArrayList<>();
public PromptsTable() {
setModel(promptTableModel);
DefaultCellEditor editor = new DefaultCellEditor(new JTextField());
this.setCellEditor(editor);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
public void reset(AppSettings settings) {
obtainPrompts(prompts, settings);
promptTableModel.fireTableDataChanged();
}
public boolean isModified(AppSettings settings) {
final ArrayList<Prompt> _prompts = new ArrayList<>();
obtainPrompts(_prompts, settings);
return !_prompts.equals(prompts);
}
private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {
prompts.clear();
prompts.addAll(settings.prompts.getPrompts());
}
public void addPrompt(Prompt prompt) {
prompts.add(prompt);
promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);
}
public void commit(AppSettings settings) {
settings.prompts.setPrompts(new ArrayList<>(this.prompts));
}
public void removeSelectedPrompts() {
int[] selectedRows = getSelectedRows();
if (selectedRows.length == 0) return;
Arrays.sort(selectedRows);
final int originalRow = selectedRows[0];
for (int i = selectedRows.length - 1; i >= 0; i--) {
final int selectedRow = selectedRows[i];
if (isValidRow(selectedRow)) {
prompts.remove(selectedRow);
promptTableModel.fireTableRowsDeleted(selectedRow, selectedRow);
}
}
promptTableModel.fireTableDataChanged();
if (originalRow < getRowCount()) {
setRowSelectionInterval(originalRow, originalRow);
} else if (getRowCount() > 0) {
final int index = getRowCount() - 1;
setRowSelectionInterval(index, index);
}
}
private boolean isValidRow(int selectedRow) {
return selectedRow >= 0 && selectedRow < prompts.size();
}
public void resetDefaultAliases() {
AppSettings.resetDefaultPrompts(prompts);
promptTableModel.fireTableDataChanged();
}
public boolean editPrompt() {
if (getSelectedRowCount() != 1) {
return false;
}
//进入行内编辑模式
return editCellAt(getSelectedRow(), getSelectedColumn());
}
private class PromptTableModel extends AbstractTableModel {
@Override
public int getColumnCount() {
return 2;
}
@Override
public int getRowCount() {
return prompts.size();
}
@Override
public Class getColumnClass(int columnIndex) {
return String.class;
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
String str = (String) value;
if (str.length() != 0) {
//修改prompts中的值
if (columnIndex == NAME_COLUMN) {
| prompts.get(rowIndex).setOption(str); |
} else if (columnIndex == VALUE_COLUMN) {
prompts.get(rowIndex).setSnippet(str);
}
promptTableModel.fireTableDataChanged();
}
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
final Prompt pair = prompts.get(rowIndex);
switch (columnIndex) {
case NAME_COLUMN:
return pair.getOption();
case VALUE_COLUMN:
return pair.getSnippet();
}
LOG.error("Wrong indices");
return null;
}
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case NAME_COLUMN:
return "Option";
case VALUE_COLUMN:
return "Snippet";
}
return null;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
}
}
| src/main/java/com/minivv/pilot/ui/PromptsTable.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "//\t\tthis.index = index;\n//\t}\n//\tpublic static Prompt of(String name, String value,int index) {\n//\t\treturn new Prompt(name, value,index);\n//\t}\n\tpublic Prompt(String option, String snippet) {\n\t\tthis.option = option;\n\t\tthis.snippet = snippet;\n\t}\n\tpublic static Prompt of(String name, String value) {",
"score": 24.011583124402947
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "\t\treturn new Prompt(name, value);\n\t}\n\tpublic String getOption() {\n\t\treturn option;\n\t}\n\tpublic void setOption(String option) {\n\t\tthis.option = option;\n\t}\n\tpublic String getSnippet() {\n\t\treturn snippet;",
"score": 21.68274421917618
},
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " public boolean enableProxy = false;\n public String proxyHost = \"127.0.0.1\";\n public int proxyPort = 1087;\n public String proxyType = SysConstants.httpProxyType;\n public String gptKey;\n public String gptModel = \"text-davinci-003\";\n public int gptMaxTokens = 2048;\n public int maxWaitSeconds = 60;\n public boolean isReplace = false;\n public String testConnMsg = SysConstants.testConnMsg;",
"score": 18.80978497655603
},
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": "public abstract class BasePilotPluginAction extends AnAction {\n// private final int index;\n// public BasePilotPluginAction(@Nullable @NlsActions.ActionText String text,int index) {\n// super(text);\n// this.index = index;\n// }\n public BasePilotPluginAction(@Nullable @NlsActions.ActionText String text) {\n super(text);\n }\n @Override",
"score": 16.51871562791712
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "// }\n// public void add(String s, String to,int index) {\n// prompts.add(new Prompt(s, to,index));\n// }\n public void add(String s, String to) {\n prompts.add(new Prompt(s, to));\n }\n public boolean add(Prompt o) {\n if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {\n return false;",
"score": 16.348978671660262
}
] | java | prompts.get(rowIndex).setOption(str); |
package com.minivv.pilot.state;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.minivv.pilot.action.BasePilotPluginAction;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.AppSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@State(
name = "chatGptPilot.idea.plugin",
storages = {@Storage("setting.xml")}
)
public class AppSettingsStorage implements PersistentStateComponent<AppSettings> {
private AppSettings settings = new AppSettings();
private final String idPrefix = "chatGptPilot_";
private final DefaultActionGroup actionGroup = new DefaultActionGroup("gpt pilot", true);
@Nullable
@Override
public AppSettings getState() {
if (settings == null) {
settings = new AppSettings();
}
return settings;
}
@Override
public void loadState(@NotNull AppSettings state) {
settings = state;
if(settings.prompts != null && settings.prompts.getPrompts().isEmpty()) {
AppSettings.addDefaultPrompts(settings.prompts);
}
}
public static AppSettingsStorage getInstance() {
return ApplicationManager.getApplication().getService(AppSettingsStorage.class);
}
public static @NotNull Project getProject() {
return ApplicationManager.getApplication().getService(ProjectManager.class).getOpenProjects()[0];
}
// public void registerActions() {
// ActionManager actionManager = ActionManager.getInstance();
// clear(actionGroup);
// AnAction popupMenu = actionManager.getAction("EditorPopupMenu");
// for (Prompt prompt : this.settings.prompts.getPrompts()) {
// BasePilotPluginAction newAction = new BasePilotPluginAction(prompt.getOption(), prompt.getIndex()) {
// @Override
// public String addStatement(String code) {
// return prompt.getSnippet().replace("{query}", code);
// }
// };
// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);
// actionGroup.add(newAction);
// }
// ((DefaultActionGroup) popupMenu).add(actionGroup);
// }
public void registerActions() {
ActionManager actionManager = ActionManager.getInstance();
DefaultActionGroup popupMenu = (DefaultActionGroup) actionManager.getAction("EditorPopupMenu");
clear(popupMenu, actionGroup);
for (Prompt prompt : this.settings.prompts.getPrompts()) {
AnAction oldAction = actionManager.getAction(idPrefix + prompt.getOption());
if (oldAction != null) {
| actionManager.unregisterAction(idPrefix + prompt.getOption()); |
}
oldAction = new BasePilotPluginAction(prompt.getOption()) {
@Override
public String addStatement(String code) {
return prompt.getSnippet().replace("{query}", code);
}
};
actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);
actionGroup.add(oldAction);
}
popupMenu.add(actionGroup);
}
private static void clear(DefaultActionGroup popupMenu, DefaultActionGroup actionGroup) {
popupMenu.remove(actionGroup);
AnAction[] childActionsOrStubs = actionGroup.getChildActionsOrStubs();
for (AnAction childActionsOrStub : childActionsOrStubs) {
actionGroup.remove(childActionsOrStub);
}
}
// public void unregisterActions() {
// ActionManager actionManager = ActionManager.getInstance();
// for (Prompt prompt : this.settings.prompts.getPrompts()) {
// actionManager.unregisterAction(idPrefix + prompt.getIndex());
// }
// }
public void unregisterActions() {
ActionManager actionManager = ActionManager.getInstance();
for (Prompt prompt : this.settings.prompts.getPrompts()) {
actionManager.unregisterAction(idPrefix + prompt.getOption());
}
}
} | src/main/java/com/minivv/pilot/state/AppSettingsStorage.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " return prompts;\n }\n public void setPrompts(List<Prompt> prompts) {\n this.prompts = prompts;\n }\n// public boolean add(Prompt o) {\n// if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()) || Objects.equals(prompt.getIndex(),o.getIndex()))) {\n// return false;\n// }\n// return prompts.add(o);",
"score": 31.43223685436122
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " }\n return prompts.add(o);\n }\n public int size() {\n return prompts.size();\n }\n public Map<String, String> asMap() {\n HashMap<String, String> stringStringHashMap = new HashMap<>();\n for (Prompt prompt : prompts) {\n stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());",
"score": 29.087578034482412
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 28.70783223253713
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "// }\n// public void add(String s, String to,int index) {\n// prompts.add(new Prompt(s, to,index));\n// }\n public void add(String s, String to) {\n prompts.add(new Prompt(s, to));\n }\n public boolean add(Prompt o) {\n if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {\n return false;",
"score": 27.868677318682987
},
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " Prompts prompts = addDefaultPrompts(new Prompts());\n Map<String, String> stringStringMap = prompts.asMap();\n _prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));\n _prompts.addAll(prompts.getPrompts());\n }\n @Transient\n public static Prompts addDefaultPrompts(Prompts prompts) {\n prompts.add(Prompt.of(\"Readable\", \"help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}\"));\n prompts.add(Prompt.of(\"List Steps\", \"help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}\"));\n prompts.add(Prompt.of(\"Explain\", \"帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}\"));",
"score": 13.37498750493454
}
] | java | actionManager.unregisterAction(idPrefix + prompt.getOption()); |
package com.minivv.pilot;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.minivv.pilot.model.AppSettings;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.ui.AppPluginSettingsPage;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class AppConfigurable implements Configurable {
private AppPluginSettingsPage form;
private AppSettings state;
private AppSettingsStorage appSettingsStorage;
public AppConfigurable() {
appSettingsStorage = AppSettingsStorage.getInstance();
state = appSettingsStorage.getState();
}
@Nls(capitalization = Nls.Capitalization.Title)
@Override
public String getDisplayName() {
return "gpt-copilot";
}
@Override
public @Nullable JComponent createComponent() {
form = new AppPluginSettingsPage(state);
return form.getRootPane();
}
@Override
public boolean isModified() {
return form != null && form.isSettingsModified(state);
}
@Override
public void apply() throws ConfigurationException {
| appSettingsStorage.unregisterActions(); |
state = form.getSettings().clone();
appSettingsStorage.loadState(state);
appSettingsStorage.registerActions();
}
@Override
public void reset() {
if (form != null) {
form.importForm(state);
}
}
@Override
public void disposeUIResources() {
form = null;
}
@Override
public @Nullable JComponent getPreferredFocusedComponent() {
return form.getGptKey();
}
public AppSettingsStorage getAppSettingsStorage() {
return appSettingsStorage;
}
}
| src/main/java/com/minivv/pilot/AppConfigurable.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java",
"retrieved_chunk": " return true;\n } else {\n return false;\n }\n }\n public boolean isSettingsModified(AppSettings state) {\n if (promptsTable.isModified(state)) return true;\n return !this.settings.equals(state) || isModified(state);\n }\n private boolean isModified(AppSettings state) {",
"score": 25.43980866059391
},
{
"filename": "src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java",
"retrieved_chunk": " !testConnMsg.getText().equals(state.testConnMsg);\n }\n public JPanel getRootPane() {\n return rootPane;\n }\n public JTextField getGptKey() {\n return gptKey;\n }\n}",
"score": 15.41257792803232
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " }\n @Override\n public void loadState(@NotNull AppSettings state) {\n settings = state;\n if(settings.prompts != null && settings.prompts.getPrompts().isEmpty()) {\n AppSettings.addDefaultPrompts(settings.prompts);\n }\n }\n public static AppSettingsStorage getInstance() {\n return ApplicationManager.getApplication().getService(AppSettingsStorage.class);",
"score": 14.971036606945242
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " return \"Snippet\";\n }\n return null;\n }\n @Override\n public boolean isCellEditable(int rowIndex, int columnIndex) {\n return true;\n }\n }\n}",
"score": 11.34475910169748
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n }\n public void reset(AppSettings settings) {\n obtainPrompts(prompts, settings);\n promptTableModel.fireTableDataChanged();\n }\n public boolean isModified(AppSettings settings) {\n final ArrayList<Prompt> _prompts = new ArrayList<>();\n obtainPrompts(_prompts, settings);\n return !_prompts.equals(prompts);",
"score": 10.06963474109231
}
] | java | appSettingsStorage.unregisterActions(); |
package com.minivv.pilot.state;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.minivv.pilot.action.BasePilotPluginAction;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.AppSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@State(
name = "chatGptPilot.idea.plugin",
storages = {@Storage("setting.xml")}
)
public class AppSettingsStorage implements PersistentStateComponent<AppSettings> {
private AppSettings settings = new AppSettings();
private final String idPrefix = "chatGptPilot_";
private final DefaultActionGroup actionGroup = new DefaultActionGroup("gpt pilot", true);
@Nullable
@Override
public AppSettings getState() {
if (settings == null) {
settings = new AppSettings();
}
return settings;
}
@Override
public void loadState(@NotNull AppSettings state) {
settings = state;
if(settings.prompts != null && settings.prompts.getPrompts().isEmpty()) {
AppSettings.addDefaultPrompts(settings.prompts);
}
}
public static AppSettingsStorage getInstance() {
return ApplicationManager.getApplication().getService(AppSettingsStorage.class);
}
public static @NotNull Project getProject() {
return ApplicationManager.getApplication().getService(ProjectManager.class).getOpenProjects()[0];
}
// public void registerActions() {
// ActionManager actionManager = ActionManager.getInstance();
// clear(actionGroup);
// AnAction popupMenu = actionManager.getAction("EditorPopupMenu");
// for (Prompt prompt : this.settings.prompts.getPrompts()) {
// BasePilotPluginAction newAction = new BasePilotPluginAction(prompt.getOption(), prompt.getIndex()) {
// @Override
// public String addStatement(String code) {
// return prompt.getSnippet().replace("{query}", code);
// }
// };
// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);
// actionGroup.add(newAction);
// }
// ((DefaultActionGroup) popupMenu).add(actionGroup);
// }
public void registerActions() {
ActionManager actionManager = ActionManager.getInstance();
DefaultActionGroup popupMenu = (DefaultActionGroup) actionManager.getAction("EditorPopupMenu");
clear(popupMenu, actionGroup);
for (Prompt prompt : this.settings.prompts.getPrompts()) {
AnAction oldAction = actionManager.getAction | (idPrefix + prompt.getOption()); |
if (oldAction != null) {
actionManager.unregisterAction(idPrefix + prompt.getOption());
}
oldAction = new BasePilotPluginAction(prompt.getOption()) {
@Override
public String addStatement(String code) {
return prompt.getSnippet().replace("{query}", code);
}
};
actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);
actionGroup.add(oldAction);
}
popupMenu.add(actionGroup);
}
private static void clear(DefaultActionGroup popupMenu, DefaultActionGroup actionGroup) {
popupMenu.remove(actionGroup);
AnAction[] childActionsOrStubs = actionGroup.getChildActionsOrStubs();
for (AnAction childActionsOrStub : childActionsOrStubs) {
actionGroup.remove(childActionsOrStub);
}
}
// public void unregisterActions() {
// ActionManager actionManager = ActionManager.getInstance();
// for (Prompt prompt : this.settings.prompts.getPrompts()) {
// actionManager.unregisterAction(idPrefix + prompt.getIndex());
// }
// }
public void unregisterActions() {
ActionManager actionManager = ActionManager.getInstance();
for (Prompt prompt : this.settings.prompts.getPrompts()) {
actionManager.unregisterAction(idPrefix + prompt.getOption());
}
}
} | src/main/java/com/minivv/pilot/state/AppSettingsStorage.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 25.10944511349915
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " return prompts;\n }\n public void setPrompts(List<Prompt> prompts) {\n this.prompts = prompts;\n }\n// public boolean add(Prompt o) {\n// if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()) || Objects.equals(prompt.getIndex(),o.getIndex()))) {\n// return false;\n// }\n// return prompts.add(o);",
"score": 22.695882065888775
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " }\n return prompts.add(o);\n }\n public int size() {\n return prompts.size();\n }\n public Map<String, String> asMap() {\n HashMap<String, String> stringStringHashMap = new HashMap<>();\n for (Prompt prompt : prompts) {\n stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());",
"score": 21.97613334604628
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "// }\n// public void add(String s, String to,int index) {\n// prompts.add(new Prompt(s, to,index));\n// }\n public void add(String s, String to) {\n prompts.add(new Prompt(s, to));\n }\n public boolean add(Prompt o) {\n if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {\n return false;",
"score": 20.332809000244463
},
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " Prompts prompts = addDefaultPrompts(new Prompts());\n Map<String, String> stringStringMap = prompts.asMap();\n _prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));\n _prompts.addAll(prompts.getPrompts());\n }\n @Transient\n public static Prompts addDefaultPrompts(Prompts prompts) {\n prompts.add(Prompt.of(\"Readable\", \"help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}\"));\n prompts.add(Prompt.of(\"List Steps\", \"help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}\"));\n prompts.add(Prompt.of(\"Explain\", \"帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}\"));",
"score": 12.09934073072138
}
] | java | (idPrefix + prompt.getOption()); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.telemetry;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.StatementExec;
import com.microsoft.lst_bench.sql.SQLParser;
import com.microsoft.lst_bench.util.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** A telemetry registry that writes events to a SQL-compatible database. */
public class SQLTelemetryRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(SQLTelemetryRegistry.class);
private final ConnectionManager connectionManager;
private final List<StatementExec> insertFileStatements;
// TODO: Make writing events thread-safe.
private List<EventInfo> eventsStream;
public SQLTelemetryRegistry(
ConnectionManager connectionManager,
boolean executeDdl,
String ddlFile,
String insertFile,
Map<String, Object> parameterValues)
throws ClientException {
this.connectionManager = connectionManager;
this.eventsStream = Collections.synchronizedList(new ArrayList<>());
this.insertFileStatements =
SQLParser.getStatements(insertFile).getStatements().stream()
.map(s -> StringUtils.replaceParameters(s, parameterValues))
.collect(Collectors.toUnmodifiableList());
// Create the tables if they don't exist.
if (executeDdl) {
executeDdl(ddlFile, parameterValues);
}
}
private void executeDdl(String ddlFile, Map<String, Object> parameterValues)
throws ClientException {
LOGGER.info("Creating new logging tables...");
try (Connection connection = connectionManager.createConnection()) {
List<StatementExec> | ddlFileStatements = SQLParser.getStatements(ddlFile).getStatements(); |
for (StatementExec query : ddlFileStatements) {
String currentQuery = StringUtils.replaceParameters(query, parameterValues).getStatement();
connection.execute(currentQuery);
}
}
LOGGER.info("Logging tables created.");
}
/** Inserts an event into the stream. */
public void writeEvent(EventInfo eventInfo) {
eventsStream.add(eventInfo);
}
/** Flushes the events to the database. */
public void flush() throws EventException {
if (eventsStream.isEmpty()) return;
LOGGER.info("Flushing events to database...");
try (Connection connection = connectionManager.createConnection()) {
Map<String, Object> values = new HashMap<>();
values.put(
"tuples",
eventsStream.stream()
.map(
o ->
String.join(
",",
StringUtils.quote(o.getExperimentId()),
StringUtils.quote(o.getStartTime().toString()),
StringUtils.quote(o.getEndTime().toString()),
StringUtils.quote(o.getEventId()),
StringUtils.quote(o.getEventType().toString()),
StringUtils.quote(o.getStatus().toString()),
StringUtils.quote(o.getPayload())))
.collect(Collectors.joining("),(", "(", ")")));
for (StatementExec query : insertFileStatements) {
String currentQuery = StringUtils.replaceParameters(query, values).getStatement();
connection.execute(currentQuery);
}
eventsStream = Collections.synchronizedList(new ArrayList<>());
LOGGER.info("Events flushed to database.");
} catch (ClientException e) {
throw new EventException(e);
}
}
}
| src/main/java/com/microsoft/lst_bench/telemetry/SQLTelemetryRegistry.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/sql/SQLParser.java",
"retrieved_chunk": " private SQLParser() {\n // Defeat instantiation\n }\n public static FileExec getStatements(String filepath) {\n return getStatements(new File(filepath));\n }\n public static FileExec getStatements(File file) {\n final List<StatementExec> statements = new ArrayList<>();\n try (BufferedReader br =\n new BufferedReader(",
"score": 34.67443525529344
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " this.experimentStartTime = experimentStartTime;\n this.telemetryRegistry = telemetryRegistry;\n }\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n try {\n for (StatementExec statement : file.getStatements()) {\n Instant statementStartTime = Instant.now();",
"score": 33.64146773078349
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": " if (str == null) {\n return null;\n }\n return \"'\" + str + \"'\";\n }\n public static StatementExec replaceParameters(\n StatementExec statement, Map<String, Object> parameterValues) {\n if (parameterValues == null || parameterValues.isEmpty()) {\n // Nothing to do\n return statement;",
"score": 30.655745242424025
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " this.phaseIdToEndTime = phaseIdToEndTime;\n this.experimentStartTime = experimentStartTime;\n }\n @Override\n public Boolean call() throws ClientException {\n Instant sessionStartTime = Instant.now();\n try (Connection connection = connectionManager.createConnection()) {\n for (TaskExec task : session.getTasks()) {\n Map<String, Object> values = updateRuntimeParameterValues(task);\n TaskExecutor taskExecutor = getTaskExecutor(task);",
"score": 29.010781202308706
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n if (file.getStatements().size() != 1) {\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw new ClientException(\n \"For dependent task execution, statements have to be in separate files.\");\n }\n StatementExec statement = file.getStatements().get(0);\n try {\n if (queryResult == null) {",
"score": 24.69194486021647
}
] | java | ddlFileStatements = SQLParser.getStatements(ddlFile).getStatements(); |
package com.minivv.pilot;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.minivv.pilot.model.AppSettings;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.ui.AppPluginSettingsPage;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class AppConfigurable implements Configurable {
private AppPluginSettingsPage form;
private AppSettings state;
private AppSettingsStorage appSettingsStorage;
public AppConfigurable() {
appSettingsStorage = AppSettingsStorage.getInstance();
state = appSettingsStorage.getState();
}
@Nls(capitalization = Nls.Capitalization.Title)
@Override
public String getDisplayName() {
return "gpt-copilot";
}
@Override
public @Nullable JComponent createComponent() {
form = new AppPluginSettingsPage(state);
return form.getRootPane();
}
@Override
public boolean isModified() {
return form != null && form.isSettingsModified(state);
}
@Override
public void apply() throws ConfigurationException {
appSettingsStorage.unregisterActions();
state = | form.getSettings().clone(); |
appSettingsStorage.loadState(state);
appSettingsStorage.registerActions();
}
@Override
public void reset() {
if (form != null) {
form.importForm(state);
}
}
@Override
public void disposeUIResources() {
form = null;
}
@Override
public @Nullable JComponent getPreferredFocusedComponent() {
return form.getGptKey();
}
public AppSettingsStorage getAppSettingsStorage() {
return appSettingsStorage;
}
}
| src/main/java/com/minivv/pilot/AppConfigurable.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java",
"retrieved_chunk": " return true;\n } else {\n return false;\n }\n }\n public boolean isSettingsModified(AppSettings state) {\n if (promptsTable.isModified(state)) return true;\n return !this.settings.equals(state) || isModified(state);\n }\n private boolean isModified(AppSettings state) {",
"score": 25.2051645235602
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " }\n @Override\n public void loadState(@NotNull AppSettings state) {\n settings = state;\n if(settings.prompts != null && settings.prompts.getPrompts().isEmpty()) {\n AppSettings.addDefaultPrompts(settings.prompts);\n }\n }\n public static AppSettingsStorage getInstance() {\n return ApplicationManager.getApplication().getService(AppSettingsStorage.class);",
"score": 14.840696898447387
},
{
"filename": "src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java",
"retrieved_chunk": " settings.maxWaitSeconds = (int) maxWaitSeconds.getValue();\n settings.proxyType = httpProxy.isSelected() ? SysConstants.httpProxyType : SysConstants.socketProxyType;\n settings.testConnMsg = testConnMsg.getText();\n settings.prompts = new Prompts(promptsTable.prompts);\n }\n public void importForm(AppSettings state) {\n this.settings = state.clone();\n setData(settings);\n promptsTable.reset(settings);\n }",
"score": 12.015661825625264
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " return \"Snippet\";\n }\n return null;\n }\n @Override\n public boolean isCellEditable(int rowIndex, int columnIndex) {\n return true;\n }\n }\n}",
"score": 11.102005833203314
},
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " AppSettingsStorage instance = AppSettingsStorage.getInstance();\n return instance.getState();\n }\n @Override\n public AppSettings clone() {\n Cloner cloner = new Cloner();\n cloner.nullInsteadOfClone();\n return cloner.deepClone(this);\n }\n public static void resetDefaultPrompts(List<Prompt> _prompts) {",
"score": 10.120478032280364
}
] | java | form.getSettings().clone(); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.telemetry;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.StatementExec;
import com.microsoft.lst_bench.sql.SQLParser;
import com.microsoft.lst_bench.util.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** A telemetry registry that writes events to a SQL-compatible database. */
public class SQLTelemetryRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(SQLTelemetryRegistry.class);
private final ConnectionManager connectionManager;
private final List<StatementExec> insertFileStatements;
// TODO: Make writing events thread-safe.
private List<EventInfo> eventsStream;
public SQLTelemetryRegistry(
ConnectionManager connectionManager,
boolean executeDdl,
String ddlFile,
String insertFile,
Map<String, Object> parameterValues)
throws ClientException {
this.connectionManager = connectionManager;
this.eventsStream = Collections.synchronizedList(new ArrayList<>());
this.insertFileStatements =
SQLParser.getStatements(insertFile).getStatements().stream()
.map(s -> StringUtils.replaceParameters(s, parameterValues))
.collect(Collectors.toUnmodifiableList());
// Create the tables if they don't exist.
if (executeDdl) {
executeDdl(ddlFile, parameterValues);
}
}
private void executeDdl(String ddlFile, Map<String, Object> parameterValues)
throws ClientException {
LOGGER.info("Creating new logging tables...");
try (Connection connection = connectionManager.createConnection()) {
List<StatementExec> ddlFileStatements = SQLParser.getStatements(ddlFile).getStatements();
for (StatementExec query : ddlFileStatements) {
String currentQuery = StringUtils.replaceParameters(query, parameterValues).getStatement();
| connection.execute(currentQuery); |
}
}
LOGGER.info("Logging tables created.");
}
/** Inserts an event into the stream. */
public void writeEvent(EventInfo eventInfo) {
eventsStream.add(eventInfo);
}
/** Flushes the events to the database. */
public void flush() throws EventException {
if (eventsStream.isEmpty()) return;
LOGGER.info("Flushing events to database...");
try (Connection connection = connectionManager.createConnection()) {
Map<String, Object> values = new HashMap<>();
values.put(
"tuples",
eventsStream.stream()
.map(
o ->
String.join(
",",
StringUtils.quote(o.getExperimentId()),
StringUtils.quote(o.getStartTime().toString()),
StringUtils.quote(o.getEndTime().toString()),
StringUtils.quote(o.getEventId()),
StringUtils.quote(o.getEventType().toString()),
StringUtils.quote(o.getStatus().toString()),
StringUtils.quote(o.getPayload())))
.collect(Collectors.joining("),(", "(", ")")));
for (StatementExec query : insertFileStatements) {
String currentQuery = StringUtils.replaceParameters(query, values).getStatement();
connection.execute(currentQuery);
}
eventsStream = Collections.synchronizedList(new ArrayList<>());
LOGGER.info("Events flushed to database.");
} catch (ClientException e) {
throw new EventException(e);
}
}
}
| src/main/java/com/microsoft/lst_bench/telemetry/SQLTelemetryRegistry.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " this.experimentStartTime = experimentStartTime;\n this.telemetryRegistry = telemetryRegistry;\n }\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n try {\n for (StatementExec statement : file.getStatements()) {\n Instant statementStartTime = Instant.now();",
"score": 42.05773571112826
},
{
"filename": "src/main/java/com/microsoft/lst_bench/sql/SQLParser.java",
"retrieved_chunk": " private SQLParser() {\n // Defeat instantiation\n }\n public static FileExec getStatements(String filepath) {\n return getStatements(new File(filepath));\n }\n public static FileExec getStatements(File file) {\n final List<StatementExec> statements = new ArrayList<>();\n try (BufferedReader br =\n new BufferedReader(",
"score": 39.659559342260174
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": " if (str == null) {\n return null;\n }\n return \"'\" + str + \"'\";\n }\n public static StatementExec replaceParameters(\n StatementExec statement, Map<String, Object> parameterValues) {\n if (parameterValues == null || parameterValues.isEmpty()) {\n // Nothing to do\n return statement;",
"score": 38.760137984677705
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": " }\n return ImmutableStatementExec.of(\n statement.getId(), StringUtils.format(statement.getStatement(), parameterValues));\n }\n public static FileExec replaceParameters(FileExec file, Map<String, Object> parameterValues) {\n if (parameterValues == null || parameterValues.isEmpty()) {\n // Nothing to do\n return file;\n }\n return ImmutableFileExec.of(",
"score": 34.79753309358206
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " this.phaseIdToEndTime = phaseIdToEndTime;\n this.experimentStartTime = experimentStartTime;\n }\n @Override\n public Boolean call() throws ClientException {\n Instant sessionStartTime = Instant.now();\n try (Connection connection = connectionManager.createConnection()) {\n for (TaskExec task : session.getTasks()) {\n Map<String, Object> values = updateRuntimeParameterValues(task);\n TaskExecutor taskExecutor = getTaskExecutor(task);",
"score": 33.35387705261245
}
] | java | connection.execute(currentQuery); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import com.microsoft.lst_bench.util.StringUtils;
import java.lang.reflect.Constructor;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default executor for sessions. Iterates over all tasks contained in the session and executes them
* sequentially.
*/
public class SessionExecutor implements Callable<Boolean> {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionExecutor.class);
private final ConnectionManager connectionManager;
private final SQLTelemetryRegistry telemetryRegistry;
private final SessionExec session;
private final Map<String, Object> runtimeParameterValues;
private final Map<String, Instant> phaseIdToEndTime;
private String experimentStartTime;
public SessionExecutor(
ConnectionManager connectionManager,
SQLTelemetryRegistry telemetryRegistry,
SessionExec session,
Map<String, Object> runtimeParameterValues,
Map<String, Instant> phaseIdToEndTime,
String experimentStartTime) {
this.connectionManager = connectionManager;
this.telemetryRegistry = telemetryRegistry;
this.session = session;
this.runtimeParameterValues = runtimeParameterValues;
this.phaseIdToEndTime = phaseIdToEndTime;
this.experimentStartTime = experimentStartTime;
}
@Override
public Boolean call() throws ClientException {
Instant sessionStartTime = Instant.now();
try (Connection connection = connectionManager.createConnection()) {
for (TaskExec task : session.getTasks()) {
Map<String, Object> values = updateRuntimeParameterValues(task);
TaskExecutor taskExecutor = getTaskExecutor(task);
Instant taskStartTime = Instant.now();
try {
taskExecutor.executeTask(connection, task, values);
} catch (Exception e) {
LOGGER.error("Exception executing task: " + task.getId());
writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);
throw e;
}
writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);
}
} catch (Exception e) {
LOGGER.error("Exception executing session: " + session.getId());
writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);
throw e;
}
writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);
return true;
}
private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {
Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);
if ( | task.getTimeTravelPhaseId() != null) { |
Instant ttPhaseEndTime = this.phaseIdToEndTime.get(task.getTimeTravelPhaseId());
if (ttPhaseEndTime == null) {
throw new RuntimeException(
"Time travel phase identifier not found: " + task.getTimeTravelPhaseId());
}
// We round to the next second to make sure we are capturing the changes in case
// are consecutive phases
String timeTravelValue =
DateTimeFormatter.AS_OF_FORMATTER.format(
ttPhaseEndTime.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));
values.put("asof", "TIMESTAMP AS OF " + StringUtils.quote(timeTravelValue));
} else {
values.put("asof", "");
}
return values;
}
private TaskExecutor getTaskExecutor(TaskExec task) {
if (task.getCustomTaskExecutor() == null) {
return new TaskExecutor(this.telemetryRegistry, this.experimentStartTime);
} else {
try {
Constructor<?> constructor =
Class.forName(task.getCustomTaskExecutor())
.getDeclaredConstructor(
SQLTelemetryRegistry.class, String.class, CustomTaskExecutorArguments.class);
return (TaskExecutor)
constructor.newInstance(
this.telemetryRegistry,
this.experimentStartTime,
task.getCustomTaskExecutorArguments());
} catch (Exception e) {
throw new IllegalArgumentException(
"Unable to load custom task class: " + task.getCustomTaskExecutor(), e);
}
}
}
private EventInfo writeSessionEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_SESSION, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writeTaskEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_TASK, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " }\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);",
"score": 37.36053299112815
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " fileStartTime,\n file.getId(),\n Status.FAILURE,\n /* payload= */ e.getMessage() + \"; \" + e.getStackTrace());\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);\n }\n }\n}",
"score": 35.732248710795524
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/FileParser.java",
"retrieved_chunk": " \"Cannot read permutation order file: \" + file.getAbsolutePath(), e);\n }\n return permutationOrder;\n }\n public static Map<String, Object> getParameterValues(String parameterValuesFile, int counter) {\n Map<String, Object> values = new HashMap<>();\n File file = new File(parameterValuesFile);\n if (!file.exists()) {\n throw new IllegalArgumentException(\n \"Cannot find parameter values file: \" + parameterValuesFile);",
"score": 34.12668744302961
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java",
"retrieved_chunk": " Status.SUCCESS,\n new ObjectMapper().writeValueAsString(experimentMetadata));\n } catch (Exception e) {\n LOGGER.error(\"Exception executing experiment: \" + config.getId());\n writeExperimentEvent(\n repetitionStartTime,\n config.getId(),\n Status.FAILURE,\n new ObjectMapper().writeValueAsString(experimentMetadata));\n throw e;",
"score": 33.89925173895682
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " @Override\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n int batch_size;\n if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {\n batch_size = DEFAULT_BATCH_SIZE;\n } else {\n batch_size = this.arguments.getDependentTaskBatchSize().intValue();\n }\n QueryResult queryResult = null;",
"score": 32.72705161840173
}
] | java | task.getTimeTravelPhaseId() != null) { |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import com.microsoft.lst_bench.util.StringUtils;
import java.lang.reflect.Constructor;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default executor for sessions. Iterates over all tasks contained in the session and executes them
* sequentially.
*/
public class SessionExecutor implements Callable<Boolean> {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionExecutor.class);
private final ConnectionManager connectionManager;
private final SQLTelemetryRegistry telemetryRegistry;
private final SessionExec session;
private final Map<String, Object> runtimeParameterValues;
private final Map<String, Instant> phaseIdToEndTime;
private String experimentStartTime;
public SessionExecutor(
ConnectionManager connectionManager,
SQLTelemetryRegistry telemetryRegistry,
SessionExec session,
Map<String, Object> runtimeParameterValues,
Map<String, Instant> phaseIdToEndTime,
String experimentStartTime) {
this.connectionManager = connectionManager;
this.telemetryRegistry = telemetryRegistry;
this.session = session;
this.runtimeParameterValues = runtimeParameterValues;
this.phaseIdToEndTime = phaseIdToEndTime;
this.experimentStartTime = experimentStartTime;
}
@Override
public Boolean call() throws ClientException {
Instant sessionStartTime = Instant.now();
try (Connection connection = connectionManager.createConnection()) {
for (TaskExec task : session.getTasks()) {
Map<String, Object> values = updateRuntimeParameterValues(task);
TaskExecutor taskExecutor = getTaskExecutor(task);
Instant taskStartTime = Instant.now();
try {
taskExecutor.executeTask(connection, task, values);
} catch (Exception e) {
LOGGER.error("Exception executing task: " + task.getId());
writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);
throw e;
}
writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);
}
} catch (Exception e) {
LOGGER.error("Exception executing session: " + session.getId());
writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);
throw e;
}
writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);
return true;
}
private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {
Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);
if (task.getTimeTravelPhaseId() != null) {
Instant ttPhaseEndTime = this.phaseIdToEndTime.get(task.getTimeTravelPhaseId());
if (ttPhaseEndTime == null) {
throw new RuntimeException(
"Time travel phase identifier not found: " + task.getTimeTravelPhaseId());
}
// We round to the next second to make sure we are capturing the changes in case
// are consecutive phases
String timeTravelValue =
DateTimeFormatter.AS_OF_FORMATTER.format(
ttPhaseEndTime.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));
values.put("asof", "TIMESTAMP AS OF " + StringUtils.quote(timeTravelValue));
} else {
values.put("asof", "");
}
return values;
}
private TaskExecutor getTaskExecutor(TaskExec task) {
if (task.getCustomTaskExecutor() == null) {
return new TaskExecutor(this.telemetryRegistry, this.experimentStartTime);
} else {
try {
Constructor<?> constructor =
Class | .forName(task.getCustomTaskExecutor())
.getDeclaredConstructor(
SQLTelemetryRegistry.class, String.class, CustomTaskExecutorArguments.class); |
return (TaskExecutor)
constructor.newInstance(
this.telemetryRegistry,
this.experimentStartTime,
task.getCustomTaskExecutorArguments());
} catch (Exception e) {
throw new IllegalArgumentException(
"Unable to load custom task class: " + task.getCustomTaskExecutor(), e);
}
}
}
private EventInfo writeSessionEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_SESSION, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writeTaskEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_TASK, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": "import org.slf4j.LoggerFactory;\n/**\n * Default executor for tasks. Iterates over all files and all the statements contained in those\n * files and executes them sequentially.\n */\npublic class TaskExecutor {\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutor.class);\n protected final SQLTelemetryRegistry telemetryRegistry;\n protected final String experimentStartTime;\n public TaskExecutor(SQLTelemetryRegistry telemetryRegistry, String experimentStartTime) {",
"score": 38.01923456374478
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " private static final Logger LOGGER = LoggerFactory.getLogger(DependentTaskExecutor.class);\n private final CustomTaskExecutorArguments arguments;\n private final int DEFAULT_BATCH_SIZE = 1;\n public DependentTaskExecutor(\n SQLTelemetryRegistry telemetryRegistry,\n String experimentStartTime,\n CustomTaskExecutorArguments arguments) {\n super(telemetryRegistry, experimentStartTime);\n this.arguments = arguments;\n }",
"score": 32.786171950457685
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " this.experimentStartTime = experimentStartTime;\n this.telemetryRegistry = telemetryRegistry;\n }\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n try {\n for (StatementExec statement : file.getStatements()) {\n Instant statementStartTime = Instant.now();",
"score": 30.561131238922194
},
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " }\n private static JDBCConnectionManager jdbcConnectionManager(\n JDBCConnectionConfig connectionConfig) {\n try {\n Class.forName(connectionConfig.getDriver());\n } catch (ClassNotFoundException e) {\n throw new IllegalArgumentException(\n \"Unable to load driver class: \" + connectionConfig.getDriver(), e);\n }\n return new JDBCConnectionManager(",
"score": 27.99580186812559
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " @Override\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n int batch_size;\n if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {\n batch_size = DEFAULT_BATCH_SIZE;\n } else {\n batch_size = this.arguments.getDependentTaskBatchSize().intValue();\n }\n QueryResult queryResult = null;",
"score": 27.413472182444046
}
] | java | .forName(task.getCustomTaskExecutor())
.getDeclaredConstructor(
SQLTelemetryRegistry.class, String.class, CustomTaskExecutorArguments.class); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import com.microsoft.lst_bench.util.StringUtils;
import java.lang.reflect.Constructor;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default executor for sessions. Iterates over all tasks contained in the session and executes them
* sequentially.
*/
public class SessionExecutor implements Callable<Boolean> {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionExecutor.class);
private final ConnectionManager connectionManager;
private final SQLTelemetryRegistry telemetryRegistry;
private final SessionExec session;
private final Map<String, Object> runtimeParameterValues;
private final Map<String, Instant> phaseIdToEndTime;
private String experimentStartTime;
public SessionExecutor(
ConnectionManager connectionManager,
SQLTelemetryRegistry telemetryRegistry,
SessionExec session,
Map<String, Object> runtimeParameterValues,
Map<String, Instant> phaseIdToEndTime,
String experimentStartTime) {
this.connectionManager = connectionManager;
this.telemetryRegistry = telemetryRegistry;
this.session = session;
this.runtimeParameterValues = runtimeParameterValues;
this.phaseIdToEndTime = phaseIdToEndTime;
this.experimentStartTime = experimentStartTime;
}
@Override
public Boolean call() throws ClientException {
Instant sessionStartTime = Instant.now();
try (Connection connection = connectionManager.createConnection()) {
for (TaskExec task : session.getTasks()) {
Map<String, Object> values = updateRuntimeParameterValues(task);
TaskExecutor taskExecutor = getTaskExecutor(task);
Instant taskStartTime = Instant.now();
try {
taskExecutor.executeTask(connection, task, values);
} catch (Exception e) {
LOGGER.error("Exception executing task: " | + task.getId()); |
writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);
throw e;
}
writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);
}
} catch (Exception e) {
LOGGER.error("Exception executing session: " + session.getId());
writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);
throw e;
}
writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);
return true;
}
private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {
Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);
if (task.getTimeTravelPhaseId() != null) {
Instant ttPhaseEndTime = this.phaseIdToEndTime.get(task.getTimeTravelPhaseId());
if (ttPhaseEndTime == null) {
throw new RuntimeException(
"Time travel phase identifier not found: " + task.getTimeTravelPhaseId());
}
// We round to the next second to make sure we are capturing the changes in case
// are consecutive phases
String timeTravelValue =
DateTimeFormatter.AS_OF_FORMATTER.format(
ttPhaseEndTime.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));
values.put("asof", "TIMESTAMP AS OF " + StringUtils.quote(timeTravelValue));
} else {
values.put("asof", "");
}
return values;
}
private TaskExecutor getTaskExecutor(TaskExec task) {
if (task.getCustomTaskExecutor() == null) {
return new TaskExecutor(this.telemetryRegistry, this.experimentStartTime);
} else {
try {
Constructor<?> constructor =
Class.forName(task.getCustomTaskExecutor())
.getDeclaredConstructor(
SQLTelemetryRegistry.class, String.class, CustomTaskExecutorArguments.class);
return (TaskExecutor)
constructor.newInstance(
this.telemetryRegistry,
this.experimentStartTime,
task.getCustomTaskExecutorArguments());
} catch (Exception e) {
throw new IllegalArgumentException(
"Unable to load custom task class: " + task.getCustomTaskExecutor(), e);
}
}
}
private EventInfo writeSessionEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_SESSION, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writeTaskEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_TASK, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " this.experimentStartTime = experimentStartTime;\n this.telemetryRegistry = telemetryRegistry;\n }\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n try {\n for (StatementExec statement : file.getStatements()) {\n Instant statementStartTime = Instant.now();",
"score": 70.13300942914879
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 48.973987667193455
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " @Override\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n int batch_size;\n if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {\n batch_size = DEFAULT_BATCH_SIZE;\n } else {\n batch_size = this.arguments.getDependentTaskBatchSize().intValue();\n }\n QueryResult queryResult = null;",
"score": 42.916883022102354
},
{
"filename": "src/main/java/com/microsoft/lst_bench/telemetry/SQLTelemetryRegistry.java",
"retrieved_chunk": " }\n /** Flushes the events to the database. */\n public void flush() throws EventException {\n if (eventsStream.isEmpty()) return;\n LOGGER.info(\"Flushing events to database...\");\n try (Connection connection = connectionManager.createConnection()) {\n Map<String, Object> values = new HashMap<>();\n values.put(\n \"tuples\",\n eventsStream.stream()",
"score": 39.882572648281794
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n if (file.getStatements().size() != 1) {\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw new ClientException(\n \"For dependent task execution, statements have to be in separate files.\");\n }\n StatementExec statement = file.getStatements().get(0);\n try {\n if (queryResult == null) {",
"score": 36.96968769672696
}
] | java | + task.getId()); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import com.microsoft.lst_bench.util.StringUtils;
import java.lang.reflect.Constructor;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default executor for sessions. Iterates over all tasks contained in the session and executes them
* sequentially.
*/
public class SessionExecutor implements Callable<Boolean> {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionExecutor.class);
private final ConnectionManager connectionManager;
private final SQLTelemetryRegistry telemetryRegistry;
private final SessionExec session;
private final Map<String, Object> runtimeParameterValues;
private final Map<String, Instant> phaseIdToEndTime;
private String experimentStartTime;
public SessionExecutor(
ConnectionManager connectionManager,
SQLTelemetryRegistry telemetryRegistry,
SessionExec session,
Map<String, Object> runtimeParameterValues,
Map<String, Instant> phaseIdToEndTime,
String experimentStartTime) {
this.connectionManager = connectionManager;
this.telemetryRegistry = telemetryRegistry;
this.session = session;
this.runtimeParameterValues = runtimeParameterValues;
this.phaseIdToEndTime = phaseIdToEndTime;
this.experimentStartTime = experimentStartTime;
}
@Override
public Boolean call() throws ClientException {
Instant sessionStartTime = Instant.now();
try (Connection connection = connectionManager.createConnection()) {
for (TaskExec task : session.getTasks()) {
Map<String, Object> values = updateRuntimeParameterValues(task);
TaskExecutor taskExecutor = getTaskExecutor(task);
Instant taskStartTime = Instant.now();
try {
taskExecutor.executeTask(connection, task, values);
} catch (Exception e) {
LOGGER.error("Exception executing task: " + task.getId());
writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);
throw e;
}
writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);
}
} catch (Exception e) {
LOGGER.error("Exception executing session: " + session.getId());
writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);
throw e;
}
writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);
return true;
}
private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {
Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);
if (task.getTimeTravelPhaseId() != null) {
Instant ttPhaseEndTime = this.phaseIdToEndTime.get(task.getTimeTravelPhaseId());
if (ttPhaseEndTime == null) {
throw new RuntimeException(
"Time travel phase identifier not found: " + task.getTimeTravelPhaseId());
}
// We round to the next second to make sure we are capturing the changes in case
// are consecutive phases
String timeTravelValue =
DateTimeFormatter.AS_OF_FORMATTER.format(
ttPhaseEndTime.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));
values.put("asof", "TIMESTAMP AS OF " + StringUtils.quote(timeTravelValue));
} else {
values.put("asof", "");
}
return values;
}
private TaskExecutor getTaskExecutor(TaskExec task) {
if (task.getCustomTaskExecutor() == null) {
return new TaskExecutor(this.telemetryRegistry, this.experimentStartTime);
} else {
try {
Constructor<?> constructor =
Class.forName(task.getCustomTaskExecutor())
.getDeclaredConstructor(
SQLTelemetryRegistry.class, String.class, CustomTaskExecutorArguments.class);
return (TaskExecutor)
constructor.newInstance(
this.telemetryRegistry,
this.experimentStartTime,
task.getCustomTaskExecutorArguments());
} catch (Exception e) {
throw new IllegalArgumentException(
| "Unable to load custom task class: " + task.getCustomTaskExecutor(), e); |
}
}
}
private EventInfo writeSessionEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_SESSION, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writeTaskEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_TASK, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " }\n private static JDBCConnectionManager jdbcConnectionManager(\n JDBCConnectionConfig connectionConfig) {\n try {\n Class.forName(connectionConfig.getDriver());\n } catch (ClassNotFoundException e) {\n throw new IllegalArgumentException(\n \"Unable to load driver class: \" + connectionConfig.getDriver(), e);\n }\n return new JDBCConnectionManager(",
"score": 45.41172588573267
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " private static final Logger LOGGER = LoggerFactory.getLogger(DependentTaskExecutor.class);\n private final CustomTaskExecutorArguments arguments;\n private final int DEFAULT_BATCH_SIZE = 1;\n public DependentTaskExecutor(\n SQLTelemetryRegistry telemetryRegistry,\n String experimentStartTime,\n CustomTaskExecutorArguments arguments) {\n super(telemetryRegistry, experimentStartTime);\n this.arguments = arguments;\n }",
"score": 31.1064463193007
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": "import org.slf4j.LoggerFactory;\n/**\n * Default executor for tasks. Iterates over all files and all the statements contained in those\n * files and executes them sequentially.\n */\npublic class TaskExecutor {\n private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutor.class);\n protected final SQLTelemetryRegistry telemetryRegistry;\n protected final String experimentStartTime;\n public TaskExecutor(SQLTelemetryRegistry telemetryRegistry, String experimentStartTime) {",
"score": 30.37432699674263
},
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " .withTimeTravelPhaseId(task.getTimeTravelPhaseId())\n .withCustomTaskExecutor(task.getCustomTaskExecutor())\n .withCustomTaskExecutorArguments(task.getCustomTaskExecutorArguments());\n }\n private static List<FileExec> createFileExecList(\n TaskTemplate taskTemplate,\n Task task,\n ExperimentConfig experimentConfig,\n Map<String, Integer> taskTemplateIdToPermuteOrderCounter,\n Map<String, Integer> taskTemplateIdToParameterValuesCounter) {",
"score": 24.324424816091074
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " this.experimentStartTime = experimentStartTime;\n this.telemetryRegistry = telemetryRegistry;\n }\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n try {\n for (StatementExec statement : file.getStatements()) {\n Instant statementStartTime = Instant.now();",
"score": 23.909863986534774
}
] | java | "Unable to load custom task class: " + task.getCustomTaskExecutor(), e); |
package com.minivv.pilot.model;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.annotations.Transient;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.constants.SysConstants;
import com.rits.cloning.Cloner;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public class AppSettings extends DomainObject implements Cloneable {
public boolean enableProxy = false;
public String proxyHost = "127.0.0.1";
public int proxyPort = 1087;
public String proxyType = SysConstants.httpProxyType;
public String gptKey;
public String gptModel = "text-davinci-003";
public int gptMaxTokens = 2048;
public int maxWaitSeconds = 60;
public boolean isReplace = false;
public String testConnMsg = SysConstants.testConnMsg;
public Prompts prompts = new Prompts();
public AppSettings() {
this.addDefaultPrompts(this.prompts);
}
@NotNull
public static Project getProject() {
return AppSettingsStorage.getProject();
}
@NotNull
public static AppSettings get() {
AppSettingsStorage instance = AppSettingsStorage.getInstance();
| return instance.getState(); |
}
@Override
public AppSettings clone() {
Cloner cloner = new Cloner();
cloner.nullInsteadOfClone();
return cloner.deepClone(this);
}
public static void resetDefaultPrompts(List<Prompt> _prompts) {
Prompts prompts = addDefaultPrompts(new Prompts());
Map<String, String> stringStringMap = prompts.asMap();
_prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));
_prompts.addAll(prompts.getPrompts());
}
@Transient
public static Prompts addDefaultPrompts(Prompts prompts) {
prompts.add(Prompt.of("Readable", "help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("List Steps", "help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("Explain", "帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("步骤注释", "帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("emptyForYou", "balabala{query}"));
return prompts;
}
} | src/main/java/com/minivv/pilot/model/AppSettings.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " }\n @Override\n public void loadState(@NotNull AppSettings state) {\n settings = state;\n if(settings.prompts != null && settings.prompts.getPrompts().isEmpty()) {\n AppSettings.addDefaultPrompts(settings.prompts);\n }\n }\n public static AppSettingsStorage getInstance() {\n return ApplicationManager.getApplication().getService(AppSettingsStorage.class);",
"score": 30.99162163351012
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " }\n public static @NotNull Project getProject() {\n return ApplicationManager.getApplication().getService(ProjectManager.class).getOpenProjects()[0];\n }\n// public void registerActions() {\n// ActionManager actionManager = ActionManager.getInstance();\n// clear(actionGroup);\n// AnAction popupMenu = actionManager.getAction(\"EditorPopupMenu\");\n// for (Prompt prompt : this.settings.prompts.getPrompts()) {\n// BasePilotPluginAction newAction = new BasePilotPluginAction(prompt.getOption(), prompt.getIndex()) {",
"score": 21.28935317127422
},
{
"filename": "src/main/java/com/minivv/pilot/AppConfigurable.java",
"retrieved_chunk": " private AppPluginSettingsPage form;\n private AppSettings state;\n private AppSettingsStorage appSettingsStorage;\n public AppConfigurable() {\n appSettingsStorage = AppSettingsStorage.getInstance();\n state = appSettingsStorage.getState();\n }\n @Nls(capitalization = Nls.Capitalization.Title)\n @Override\n public String getDisplayName() {",
"score": 21.231477069185573
},
{
"filename": "src/main/java/com/minivv/pilot/AppConfigurable.java",
"retrieved_chunk": " return form.getGptKey();\n }\n public AppSettingsStorage getAppSettingsStorage() {\n return appSettingsStorage;\n }\n}",
"score": 14.763981259998413
},
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": " doCommand(statement, editor, project);\n }\n private void doCommand(String statement, Editor editor, Project project) {\n AppSettings settings = AppSettingsStorage.getInstance().getState();\n if(settings == null){\n NotifyUtils.notifyMessage(project,\"gpt-copilot settings is null, please check!\", NotificationType.ERROR);\n return;\n }\n List<CompletionChoice> choices = GPTClient.callChatGPT(statement, settings);\n String optimizedCode;",
"score": 14.380992663904888
}
] | java | return instance.getState(); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.PhaseExec;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.WorkloadExec;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Benchmark executor implementation. */
public class LSTBenchmarkExecutor extends BenchmarkRunnable {
private static final Logger LOGGER = LoggerFactory.getLogger(LSTBenchmarkExecutor.class);
private final List<ConnectionManager> connectionManagers;
private final BenchmarkConfig config;
private final SQLTelemetryRegistry telemetryRegistry;
// timestamp of the start of the first iteration of an experiment.
private String experimentStartTime;
public LSTBenchmarkExecutor(
List<ConnectionManager> connectionManagers,
BenchmarkConfig config,
SQLTelemetryRegistry telemetryRegistry) {
super();
this.connectionManagers = Collections.unmodifiableList(connectionManagers);
this.config = config;
this.telemetryRegistry = telemetryRegistry;
}
/** This method runs the experiment. */
public void execute() throws Exception {
this.experimentStartTime = DateTimeFormatter.U_FORMATTER.format(Instant.now());
LOGGER.info("Running experiment: {}, start-time: {}", config.getId(), experimentStartTime);
final WorkloadExec workload = config.getWorkload();
// Thread pool size to max number of concurrent sessions
int maxConcurrentSessions = 1;
for (PhaseExec phase : workload.getPhases()) {
if (phase.getSessions().size() > maxConcurrentSessions) {
maxConcurrentSessions = phase.getSessions().size();
}
}
ExecutorService executor = null;
for (int i = 0; i < config.getRepetitions(); i++) {
LOGGER.info("Starting repetition: {}", i);
final Instant repetitionStartTime = Instant.now();
Map<String, Object> experimentMetadata = new HashMap<>(config.getMetadata());
try {
executor = Executors.newFixedThreadPool(maxConcurrentSessions);
// Fill in specific runtime parameter values
Map<String, Object> runtimeParameterValues = new HashMap<>();
runtimeParameterValues.put("repetition", i);
runtimeParameterValues.put("experiment_start_time", experimentStartTime);
experimentMetadata.putAll(runtimeParameterValues);
// Go over phases and execute
Map<String, Instant> phaseIdToEndTime = new HashMap<>();
for (PhaseExec phase : workload.getPhases()) {
LOGGER.info("Running " + phase.getId() + " phase...");
final Instant phaseStartTime = Instant.now();
EventInfo eventInfo;
try {
final List<SessionExecutor> threads = new ArrayList<>();
for (SessionExec session : phase.getSessions()) {
threads.add(
new SessionExecutor(
connectionManagers.get(session.getTargetEndpoint()),
this.telemetryRegistry,
session,
runtimeParameterValues,
phaseIdToEndTime,
this.experimentStartTime));
}
checkResults(executor.invokeAll(threads));
eventInfo = writePhaseEvent(phaseStartTime, phase.getId(), Status.SUCCESS);
} catch (Exception e) {
LOGGER.error("Exception executing phase: " + phase.getId());
writePhaseEvent(phaseStartTime, phase.getId(), Status.FAILURE);
throw e;
} finally {
telemetryRegistry.flush();
}
LOGGER.info(
"Phase {} finished in {} seconds.",
phase.getId(),
ChronoUnit.SECONDS.between(phaseStartTime | , eventInfo.getEndTime())); |
phaseIdToEndTime.put(phase.getId(), eventInfo.getEndTime());
}
// Log end-to-end execution of experiment.
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.SUCCESS,
new ObjectMapper().writeValueAsString(experimentMetadata));
} catch (Exception e) {
LOGGER.error("Exception executing experiment: " + config.getId());
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.FAILURE,
new ObjectMapper().writeValueAsString(experimentMetadata));
throw e;
} finally {
if (executor != null) {
executor.shutdown();
Validate.isTrue(executor.awaitTermination(1, TimeUnit.MINUTES));
}
telemetryRegistry.flush();
}
LOGGER.info("Finished repetition {}", i);
}
LOGGER.info("Finished experiment: {}", config.getId());
}
private void checkResults(List<Future<Boolean>> results) {
for (Future<Boolean> result : results) {
try {
Validate.isTrue(result.get());
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Thread did not finish correctly", e);
}
}
}
private EventInfo writeExperimentEvent(
Instant startTime, String id, Status status, String payload) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime,
startTime,
Instant.now(),
id,
EventType.EXEC_EXPERIMENT,
status)
.withPayload(payload);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writePhaseEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_PHASE, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " }\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);",
"score": 26.712955973216772
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " fileStartTime,\n file.getId(),\n Status.FAILURE,\n /* payload= */ e.getMessage() + \"; \" + e.getStackTrace());\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);\n }\n }\n}",
"score": 25.325499930967347
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " Instant taskStartTime = Instant.now();\n try {\n taskExecutor.executeTask(connection, task, values);\n } catch (Exception e) {\n LOGGER.error(\"Exception executing task: \" + task.getId());\n writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);\n throw e;\n }\n writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);\n }",
"score": 25.055141841154565
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 24.884183703822544
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " } catch (Exception e) {\n LOGGER.error(\"Exception executing session: \" + session.getId());\n writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);\n throw e;\n }\n writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);\n return true;\n }\n private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {\n Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);",
"score": 23.545933265214217
}
] | java | , eventInfo.getEndTime())); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.PhaseExec;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.WorkloadExec;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Benchmark executor implementation. */
public class LSTBenchmarkExecutor extends BenchmarkRunnable {
private static final Logger LOGGER = LoggerFactory.getLogger(LSTBenchmarkExecutor.class);
private final List<ConnectionManager> connectionManagers;
private final BenchmarkConfig config;
private final SQLTelemetryRegistry telemetryRegistry;
// timestamp of the start of the first iteration of an experiment.
private String experimentStartTime;
public LSTBenchmarkExecutor(
List<ConnectionManager> connectionManagers,
BenchmarkConfig config,
SQLTelemetryRegistry telemetryRegistry) {
super();
this.connectionManagers = Collections.unmodifiableList(connectionManagers);
this.config = config;
this.telemetryRegistry = telemetryRegistry;
}
/** This method runs the experiment. */
public void execute() throws Exception {
this.experimentStartTime = DateTimeFormatter.U_FORMATTER.format(Instant.now());
LOGGER.info("Running experiment: {}, start-time: {}", config.getId(), experimentStartTime);
final WorkloadExec workload = config.getWorkload();
// Thread pool size to max number of concurrent sessions
int maxConcurrentSessions = 1;
for (PhaseExec phase : workload.getPhases()) {
| if (phase.getSessions().size() > maxConcurrentSessions) { |
maxConcurrentSessions = phase.getSessions().size();
}
}
ExecutorService executor = null;
for (int i = 0; i < config.getRepetitions(); i++) {
LOGGER.info("Starting repetition: {}", i);
final Instant repetitionStartTime = Instant.now();
Map<String, Object> experimentMetadata = new HashMap<>(config.getMetadata());
try {
executor = Executors.newFixedThreadPool(maxConcurrentSessions);
// Fill in specific runtime parameter values
Map<String, Object> runtimeParameterValues = new HashMap<>();
runtimeParameterValues.put("repetition", i);
runtimeParameterValues.put("experiment_start_time", experimentStartTime);
experimentMetadata.putAll(runtimeParameterValues);
// Go over phases and execute
Map<String, Instant> phaseIdToEndTime = new HashMap<>();
for (PhaseExec phase : workload.getPhases()) {
LOGGER.info("Running " + phase.getId() + " phase...");
final Instant phaseStartTime = Instant.now();
EventInfo eventInfo;
try {
final List<SessionExecutor> threads = new ArrayList<>();
for (SessionExec session : phase.getSessions()) {
threads.add(
new SessionExecutor(
connectionManagers.get(session.getTargetEndpoint()),
this.telemetryRegistry,
session,
runtimeParameterValues,
phaseIdToEndTime,
this.experimentStartTime));
}
checkResults(executor.invokeAll(threads));
eventInfo = writePhaseEvent(phaseStartTime, phase.getId(), Status.SUCCESS);
} catch (Exception e) {
LOGGER.error("Exception executing phase: " + phase.getId());
writePhaseEvent(phaseStartTime, phase.getId(), Status.FAILURE);
throw e;
} finally {
telemetryRegistry.flush();
}
LOGGER.info(
"Phase {} finished in {} seconds.",
phase.getId(),
ChronoUnit.SECONDS.between(phaseStartTime, eventInfo.getEndTime()));
phaseIdToEndTime.put(phase.getId(), eventInfo.getEndTime());
}
// Log end-to-end execution of experiment.
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.SUCCESS,
new ObjectMapper().writeValueAsString(experimentMetadata));
} catch (Exception e) {
LOGGER.error("Exception executing experiment: " + config.getId());
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.FAILURE,
new ObjectMapper().writeValueAsString(experimentMetadata));
throw e;
} finally {
if (executor != null) {
executor.shutdown();
Validate.isTrue(executor.awaitTermination(1, TimeUnit.MINUTES));
}
telemetryRegistry.flush();
}
LOGGER.info("Finished repetition {}", i);
}
LOGGER.info("Finished experiment: {}", config.getId());
}
private void checkResults(List<Future<Boolean>> results) {
for (Future<Boolean> result : results) {
try {
Validate.isTrue(result.get());
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Thread did not finish correctly", e);
}
}
}
private EventInfo writeExperimentEvent(
Instant startTime, String id, Status status, String payload) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime,
startTime,
Instant.now(),
id,
EventType.EXEC_EXPERIMENT,
status)
.withPayload(payload);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writePhaseEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_PHASE, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/test/java/com/microsoft/lst_bench/input/ParserTest.java",
"retrieved_chunk": " FileParser.createObject(\n CONFIG_PATH + \"tpcds\" + File.separator + \"w0_tpcds-iceberg.yaml\", Workload.class);\n Assertions.assertEquals(1, workload.getVersion());\n Assertions.assertEquals(\"w0_tpcds_iceberg\", workload.getId());\n Assertions.assertEquals(9, workload.getPhases().size());\n for (Phase phase : workload.getPhases()) {\n switch (phase.getId()) {\n case \"setup\":\n {\n List<Session> sessions = phase.getSessions();",
"score": 35.9624623354438
},
{
"filename": "src/test/java/com/microsoft/lst_bench/input/ParserTest.java",
"retrieved_chunk": " @Test\n public void testParseW0Delta() throws IOException {\n Workload workload =\n FileParser.createObject(\n CONFIG_PATH + \"tpcds\" + File.separator + \"w0_tpcds-delta.yaml\", Workload.class);\n Assertions.assertEquals(1, workload.getVersion());\n Assertions.assertEquals(\"w0_tpcds_delta\", workload.getId());\n Assertions.assertEquals(9, workload.getPhases().size());\n for (Phase phase : workload.getPhases()) {\n switch (phase.getId()) {",
"score": 33.44266168715279
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/DateTimeFormatter.java",
"retrieved_chunk": " public static final java.time.format.DateTimeFormatter U_FORMATTER =\n java.time.format.DateTimeFormatter.ofPattern(\"yyyy_MM_dd_HH_mm_ss_SSS\")\n .withZone(ZoneOffset.UTC);\n /** Formatter for AS OF clause in SQL queries. */\n public static final java.time.format.DateTimeFormatter AS_OF_FORMATTER =\n java.time.format.DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss.000\")\n .withZone(ZoneOffset.UTC);\n}",
"score": 33.322437666750425
},
{
"filename": "src/test/java/com/microsoft/lst_bench/input/ParserTest.java",
"retrieved_chunk": " }\n @Test\n public void testParseWP4TimeTravel() throws IOException {\n Workload workload =\n FileParser.createObject(\n CONFIG_PATH + \"tpcds\" + File.separator + \"wp4_time_travel.yaml\", Workload.class);\n Assertions.assertEquals(1, workload.getVersion());\n Assertions.assertEquals(\"wp4_time_travel\", workload.getId());\n Assertions.assertEquals(18, workload.getPhases().size());\n for (Phase phase : workload.getPhases()) {",
"score": 31.838590858338932
},
{
"filename": "src/test/java/com/microsoft/lst_bench/input/ParserTest.java",
"retrieved_chunk": " }\n @Test\n public void testParseWP3RWConcurrency() throws IOException {\n Workload workload =\n FileParser.createObject(\n CONFIG_PATH + \"tpcds\" + File.separator + \"wp3_rw_concurrency.yaml\", Workload.class);\n Assertions.assertEquals(1, workload.getVersion());\n Assertions.assertEquals(\"wp3_rw_concurrency\", workload.getId());\n Assertions.assertEquals(10, workload.getPhases().size());\n for (Phase phase : workload.getPhases()) {",
"score": 31.838590858338932
}
] | java | if (phase.getSessions().size() > maxConcurrentSessions) { |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import com.microsoft.lst_bench.util.StringUtils;
import java.lang.reflect.Constructor;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default executor for sessions. Iterates over all tasks contained in the session and executes them
* sequentially.
*/
public class SessionExecutor implements Callable<Boolean> {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionExecutor.class);
private final ConnectionManager connectionManager;
private final SQLTelemetryRegistry telemetryRegistry;
private final SessionExec session;
private final Map<String, Object> runtimeParameterValues;
private final Map<String, Instant> phaseIdToEndTime;
private String experimentStartTime;
public SessionExecutor(
ConnectionManager connectionManager,
SQLTelemetryRegistry telemetryRegistry,
SessionExec session,
Map<String, Object> runtimeParameterValues,
Map<String, Instant> phaseIdToEndTime,
String experimentStartTime) {
this.connectionManager = connectionManager;
this.telemetryRegistry = telemetryRegistry;
this.session = session;
this.runtimeParameterValues = runtimeParameterValues;
this.phaseIdToEndTime = phaseIdToEndTime;
this.experimentStartTime = experimentStartTime;
}
@Override
public Boolean call() throws ClientException {
Instant sessionStartTime = Instant.now();
try (Connection connection = connectionManager.createConnection()) {
for (TaskExec task : session.getTasks()) {
Map<String, Object> values = updateRuntimeParameterValues(task);
TaskExecutor taskExecutor = getTaskExecutor(task);
Instant taskStartTime = Instant.now();
try {
taskExecutor.executeTask(connection, task, values);
} catch (Exception e) {
LOGGER.error("Exception executing task: " + task.getId());
| writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE); |
throw e;
}
writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);
}
} catch (Exception e) {
LOGGER.error("Exception executing session: " + session.getId());
writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);
throw e;
}
writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);
return true;
}
private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {
Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);
if (task.getTimeTravelPhaseId() != null) {
Instant ttPhaseEndTime = this.phaseIdToEndTime.get(task.getTimeTravelPhaseId());
if (ttPhaseEndTime == null) {
throw new RuntimeException(
"Time travel phase identifier not found: " + task.getTimeTravelPhaseId());
}
// We round to the next second to make sure we are capturing the changes in case
// are consecutive phases
String timeTravelValue =
DateTimeFormatter.AS_OF_FORMATTER.format(
ttPhaseEndTime.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));
values.put("asof", "TIMESTAMP AS OF " + StringUtils.quote(timeTravelValue));
} else {
values.put("asof", "");
}
return values;
}
private TaskExecutor getTaskExecutor(TaskExec task) {
if (task.getCustomTaskExecutor() == null) {
return new TaskExecutor(this.telemetryRegistry, this.experimentStartTime);
} else {
try {
Constructor<?> constructor =
Class.forName(task.getCustomTaskExecutor())
.getDeclaredConstructor(
SQLTelemetryRegistry.class, String.class, CustomTaskExecutorArguments.class);
return (TaskExecutor)
constructor.newInstance(
this.telemetryRegistry,
this.experimentStartTime,
task.getCustomTaskExecutorArguments());
} catch (Exception e) {
throw new IllegalArgumentException(
"Unable to load custom task class: " + task.getCustomTaskExecutor(), e);
}
}
}
private EventInfo writeSessionEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_SESSION, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writeTaskEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_TASK, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " this.experimentStartTime = experimentStartTime;\n this.telemetryRegistry = telemetryRegistry;\n }\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n try {\n for (StatementExec statement : file.getStatements()) {\n Instant statementStartTime = Instant.now();",
"score": 73.12254298194385
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 59.62524534255014
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " for (FileExec file : task.getFiles()) {\n Instant fileStartTime = Instant.now();\n if (file.getStatements().size() != 1) {\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw new ClientException(\n \"For dependent task execution, statements have to be in separate files.\");\n }\n StatementExec statement = file.getStatements().get(0);\n try {\n if (queryResult == null) {",
"score": 48.272085210007354
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " @Override\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n int batch_size;\n if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {\n batch_size = DEFAULT_BATCH_SIZE;\n } else {\n batch_size = this.arguments.getDependentTaskBatchSize().intValue();\n }\n QueryResult queryResult = null;",
"score": 45.106486474991726
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " }\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);",
"score": 42.73363124443279
}
] | java | writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.PhaseExec;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.WorkloadExec;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Benchmark executor implementation. */
public class LSTBenchmarkExecutor extends BenchmarkRunnable {
private static final Logger LOGGER = LoggerFactory.getLogger(LSTBenchmarkExecutor.class);
private final List<ConnectionManager> connectionManagers;
private final BenchmarkConfig config;
private final SQLTelemetryRegistry telemetryRegistry;
// timestamp of the start of the first iteration of an experiment.
private String experimentStartTime;
public LSTBenchmarkExecutor(
List<ConnectionManager> connectionManagers,
BenchmarkConfig config,
SQLTelemetryRegistry telemetryRegistry) {
super();
this.connectionManagers = Collections.unmodifiableList(connectionManagers);
this.config = config;
this.telemetryRegistry = telemetryRegistry;
}
/** This method runs the experiment. */
public void execute() throws Exception {
this.experimentStartTime = DateTimeFormatter.U_FORMATTER.format(Instant.now());
LOGGER.info("Running experiment: {}, start-time: {}", config.getId(), experimentStartTime);
final WorkloadExec workload = config.getWorkload();
// Thread pool size to max number of concurrent sessions
int maxConcurrentSessions = 1;
for (PhaseExec phase : workload.getPhases()) {
if (phase.getSessions().size() > maxConcurrentSessions) {
maxConcurrentSessions = phase.getSessions().size();
}
}
ExecutorService executor = null;
for (int i = 0; i < config.getRepetitions(); i++) {
LOGGER.info("Starting repetition: {}", i);
final Instant repetitionStartTime = Instant.now();
Map<String, Object> experimentMetadata = new HashMap<>(config.getMetadata());
try {
executor = Executors.newFixedThreadPool(maxConcurrentSessions);
// Fill in specific runtime parameter values
Map<String, Object> runtimeParameterValues = new HashMap<>();
runtimeParameterValues.put("repetition", i);
runtimeParameterValues.put("experiment_start_time", experimentStartTime);
experimentMetadata.putAll(runtimeParameterValues);
// Go over phases and execute
Map<String, Instant> phaseIdToEndTime = new HashMap<>();
for (PhaseExec phase : workload.getPhases()) {
LOGGER | .info("Running " + phase.getId() + " phase..."); |
final Instant phaseStartTime = Instant.now();
EventInfo eventInfo;
try {
final List<SessionExecutor> threads = new ArrayList<>();
for (SessionExec session : phase.getSessions()) {
threads.add(
new SessionExecutor(
connectionManagers.get(session.getTargetEndpoint()),
this.telemetryRegistry,
session,
runtimeParameterValues,
phaseIdToEndTime,
this.experimentStartTime));
}
checkResults(executor.invokeAll(threads));
eventInfo = writePhaseEvent(phaseStartTime, phase.getId(), Status.SUCCESS);
} catch (Exception e) {
LOGGER.error("Exception executing phase: " + phase.getId());
writePhaseEvent(phaseStartTime, phase.getId(), Status.FAILURE);
throw e;
} finally {
telemetryRegistry.flush();
}
LOGGER.info(
"Phase {} finished in {} seconds.",
phase.getId(),
ChronoUnit.SECONDS.between(phaseStartTime, eventInfo.getEndTime()));
phaseIdToEndTime.put(phase.getId(), eventInfo.getEndTime());
}
// Log end-to-end execution of experiment.
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.SUCCESS,
new ObjectMapper().writeValueAsString(experimentMetadata));
} catch (Exception e) {
LOGGER.error("Exception executing experiment: " + config.getId());
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.FAILURE,
new ObjectMapper().writeValueAsString(experimentMetadata));
throw e;
} finally {
if (executor != null) {
executor.shutdown();
Validate.isTrue(executor.awaitTermination(1, TimeUnit.MINUTES));
}
telemetryRegistry.flush();
}
LOGGER.info("Finished repetition {}", i);
}
LOGGER.info("Finished experiment: {}", config.getId());
}
private void checkResults(List<Future<Boolean>> results) {
for (Future<Boolean> result : results) {
try {
Validate.isTrue(result.get());
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Thread did not finish correctly", e);
}
}
}
private EventInfo writeExperimentEvent(
Instant startTime, String id, Status status, String payload) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime,
startTime,
Instant.now(),
id,
EventType.EXEC_EXPERIMENT,
status)
.withPayload(payload);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writePhaseEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_PHASE, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " ConnectionManager connectionManager,\n SQLTelemetryRegistry telemetryRegistry,\n SessionExec session,\n Map<String, Object> runtimeParameterValues,\n Map<String, Instant> phaseIdToEndTime,\n String experimentStartTime) {\n this.connectionManager = connectionManager;\n this.telemetryRegistry = telemetryRegistry;\n this.session = session;\n this.runtimeParameterValues = runtimeParameterValues;",
"score": 58.655735131776694
},
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " Map<String, Integer> taskTemplateIdToPermuteOrderCounter = new HashMap<>();\n Map<String, Integer> taskTemplateIdToParameterValuesCounter = new HashMap<>();\n List<PhaseExec> phases = new ArrayList<>();\n for (Phase phase : workload.getPhases()) {\n PhaseExec phaseExec =\n createPhaseExec(\n phase,\n idToTaskTemplate,\n experimentConfig,\n taskTemplateIdToPermuteOrderCounter,",
"score": 53.132624837381556
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " } catch (Exception e) {\n LOGGER.error(\"Exception executing session: \" + session.getId());\n writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);\n throw e;\n }\n writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);\n return true;\n }\n private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {\n Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);",
"score": 47.80015859350526
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " */\npublic class SessionExecutor implements Callable<Boolean> {\n private static final Logger LOGGER = LoggerFactory.getLogger(SessionExecutor.class);\n private final ConnectionManager connectionManager;\n private final SQLTelemetryRegistry telemetryRegistry;\n private final SessionExec session;\n private final Map<String, Object> runtimeParameterValues;\n private final Map<String, Instant> phaseIdToEndTime;\n private String experimentStartTime;\n public SessionExecutor(",
"score": 42.091104478172525
},
{
"filename": "src/main/java/com/microsoft/lst_bench/telemetry/SQLTelemetryRegistry.java",
"retrieved_chunk": " }\n /** Flushes the events to the database. */\n public void flush() throws EventException {\n if (eventsStream.isEmpty()) return;\n LOGGER.info(\"Flushing events to database...\");\n try (Connection connection = connectionManager.createConnection()) {\n Map<String, Object> values = new HashMap<>();\n values.put(\n \"tuples\",\n eventsStream.stream()",
"score": 37.66135578240919
}
] | java | .info("Running " + phase.getId() + " phase..."); |
package com.minivv.pilot.action;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsActions;
import com.minivv.pilot.model.AppSettings;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.utils.GPTClient;
import com.minivv.pilot.utils.NotifyUtils;
import com.theokanning.openai.completion.CompletionChoice;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public abstract class BasePilotPluginAction extends AnAction {
// private final int index;
// public BasePilotPluginAction(@Nullable @NlsActions.ActionText String text,int index) {
// super(text);
// this.index = index;
// }
public BasePilotPluginAction(@Nullable @NlsActions.ActionText String text) {
super(text);
}
@Override
public void update(@NotNull AnActionEvent e) {
super.update(e);
// 只有当编辑器中有选中的代码片段时才显示 GptCopilotAction 菜单选项
Editor editor = e.getData(CommonDataKeys.EDITOR);
if (editor == null) {
e.getPresentation().setEnabled(false);
return;
}
String code = editor.getSelectionModel().getSelectedText();
e.getPresentation().setEnabled(code != null && !code.isEmpty());
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
DataContext dataContext = e.getDataContext();
Project project = CommonDataKeys.PROJECT.getData(dataContext);
if (project == null) {
return;
}
// 获取编辑器对象
Editor editor = e.getData(CommonDataKeys.EDITOR);
if (editor == null) {
return;
}
// 获取用户选中的代码片段
String code = editor.getSelectionModel().getSelectedText();
if (code == null || code.isEmpty()) {
return;
}
String statement = addStatement(code);
NotifyUtils.notifyMessage(project,"sending code to gpt..", NotificationType.INFORMATION);
doCommand(statement, editor, project);
}
private void doCommand(String statement, Editor editor, Project project) {
AppSettings | settings = AppSettingsStorage.getInstance().getState(); |
if(settings == null){
NotifyUtils.notifyMessage(project,"gpt-copilot settings is null, please check!", NotificationType.ERROR);
return;
}
List<CompletionChoice> choices = GPTClient.callChatGPT(statement, settings);
String optimizedCode;
if(GPTClient.isSuccessful(choices)){
optimizedCode = GPTClient.toString(choices);
} else {
NotifyUtils.notifyMessage(project,"gpt-copilot connection failed, please check!", NotificationType.ERROR);
return;
}
//处理readable操作
ApplicationManager.getApplication().runWriteAction(() -> {
CommandProcessor.getInstance().executeCommand(
project,
() -> {
// 将优化后的代码作为注释添加到选中的代码块后面
insertCommentAfterSelectedText(editor, optimizedCode,settings.isReplace);
if(!settings.isReplace){
// 将选中的代码块注释掉
commentSelectedText(editor);
}
// 取消选中状态
clearSelection(editor);
},
"Insert Comment",
null
);
});
}
public abstract String addStatement(String code);
private void commentSelectedText(Editor editor) {
Document document = editor.getDocument();
int selectionStartOffset = editor.getSelectionModel().getSelectionStart();
int selectionEndOffset = editor.getSelectionModel().getSelectionEnd();
String selectedText = document.getText().substring(selectionStartOffset, selectionEndOffset);
document.replaceString(selectionStartOffset, selectionEndOffset, "/*" + selectedText + "*/");
}
private void insertCommentAfterSelectedText(Editor editor, String optimizedCode, boolean isReplace) {
Document document = editor.getDocument();
int selectionStartOffset = editor.getSelectionModel().getSelectionStart();
int selectionEndOffset = editor.getSelectionModel().getSelectionEnd();
if(isReplace){
document.replaceString(selectionStartOffset, selectionEndOffset, optimizedCode);
return;
}
document.insertString(selectionEndOffset, optimizedCode);
}
private void clearSelection(Editor editor) {
editor.getSelectionModel().removeSelection();
}
} | src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/utils/NotifyUtils.java",
"retrieved_chunk": " *\n * @param project\n * @param message\n */\n public static void notifyMessage(Project project, String message) {\n try {\n Notification currentNotify = NOTIFICATION.createNotification(message, NotificationType.INFORMATION);\n Notifications.Bus.notify(currentNotify, project);\n } catch (Exception e) {\n //",
"score": 25.698431571701754
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " @Override\n public String addStatement(String code) {\n return prompt.getSnippet().replace(\"{query}\", code);\n }\n };\n actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);\n actionGroup.add(oldAction);\n }\n popupMenu.add(actionGroup);\n }",
"score": 23.521450330645322
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// @Override\n// public String addStatement(String code) {\n// return prompt.getSnippet().replace(\"{query}\", code);\n// }\n// };\n// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);\n// actionGroup.add(newAction);\n// }\n// ((DefaultActionGroup) popupMenu).add(actionGroup);\n// }",
"score": 23.259393999631534
},
{
"filename": "src/main/java/com/minivv/pilot/utils/NotifyUtils.java",
"retrieved_chunk": " }\n }\n /**\n * 推送消息哦\n *\n * @param project\n * @param message\n * @param type\n */\n public static void notifyMessage(Project project, String message, @NotNull NotificationType type) {",
"score": 23.18585051837202
},
{
"filename": "src/main/java/com/minivv/pilot/utils/NotifyUtils.java",
"retrieved_chunk": " /**\n * 通知消息\n *\n * @param project\n */\n public static void notifyMessageDefault(Project project) {\n notifyMessage(project, COMMAND_COPIED);\n }\n /**\n * 消息",
"score": 19.984578849276154
}
] | java | settings = AppSettingsStorage.getInstance().getState(); |
package uk.gov.justice.laa.crime.dces.report.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.xml.bind.JAXBException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.gov.justice.laa.crime.dces.report.service.ContributionFilesService;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/internal/v1/dces/report")
@Tag(name = "DCES Contribution files report", description = "Rest API to retrieve and generate contribution files report")
public class ContributionsReportController {
private ContributionFilesService contributionFilesService;
@GetMapping(value = "/contributions/{start}/{finish}")
@Operation(description = "Retrieve information regarding contribution files sent during the given period and generate a report")
@ApiResponse(responseCode = "200")
@ApiResponse(responseCode = "400",
description = "Bad request.",
content = @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE,
schema = @Schema(implementation = ProblemDetail.class)
)
)
@ApiResponse(responseCode = "500",
description = "Server Error.",
content = @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE,
schema = @Schema(implementation = ProblemDetail.class)
)
)
public File getContributionFiles(@PathVariable("start") LocalDate start, @PathVariable("finish") LocalDate finish) throws JAXBException, IOException {
List<String> contributionFiles = contributionFilesService.getFiles(start, finish);
| String reportFileName = contributionFilesService.getFileName(start, finish); |
return contributionFilesService.processFiles(contributionFiles, start, finish, reportFileName);
}
}
| dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/controller/ContributionsReportController.java | ministryofjustice-laa-dces-report-service-ac8db88 | [
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/FdcFilesService.java",
"retrieved_chunk": " public File processFiles(List<String> files, LocalDate start, LocalDate finish) throws JAXBException, IOException {\n return fdcFileMapper.processRequest(files.toArray(new String[0]), getFileName(start, finish));\n }\n public String getFileName(LocalDate start, LocalDate finish) {\n return String.format(FILE_NAME_TEMPLATE, start, finish);\n }\n}",
"score": 71.18508066755328
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/ContributionFilesService.java",
"retrieved_chunk": " @Retry(name = SERVICE_NAME)\n public List<String> getFiles(LocalDate start, LocalDate finish) {\n log.info(\"Start - call MAAT API to collect contribution files date between {} and {}\", start.toString(), finish.toString());\n return contributionFilesClient.getContributions(start, finish);\n }\n public File processFiles(List<String> files, LocalDate start, LocalDate finish, String fileName) throws JAXBException, IOException {\n return contributionFilesMapper.processRequest(files.toArray(new String[0]), start, finish, fileName);\n }\n public String getFileName(LocalDate start, LocalDate finish) {\n return String.format(FILE_NAME_TEMPLATE, start, finish);",
"score": 69.49214493946417
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportServiceImpl.java",
"retrieved_chunk": " contributionFiles,\n start,\n end,\n contributionFilesService.getFileName(start, end)\n );\n }\n public File getFdcReport(LocalDate start, LocalDate end) throws JAXBException, IOException {\n List<String> contributionFiles = fdcFilesService.getFiles(start, end);\n // @TODO handle empty list\n return fdcFilesService.processFiles(contributionFiles, start, end);",
"score": 59.1639370157697
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportServiceImpl.java",
"retrieved_chunk": "@RequiredArgsConstructor\npublic class DcesReportServiceImpl implements DcesReportService {\n @Autowired\n private FdcFilesService fdcFilesService;\n @Autowired\n private ContributionFilesService contributionFilesService;\n public File getContributionsReport(LocalDate start, LocalDate end) throws JAXBException, IOException {\n List<String> contributionFiles = contributionFilesService.getFiles(start, end);\n // @TODO handle empty list\n return contributionFilesService.processFiles(",
"score": 52.74188714618822
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportFileService.java",
"retrieved_chunk": "/*\n This interface defines a contract for retrieving records and or files held within MAAT\n and accessible via its API and integrating the appropriate webclient.\n */\npackage uk.gov.justice.laa.crime.dces.report.service;\nimport java.time.LocalDate;\nimport java.util.List;\npublic interface DcesReportFileService {\n List<String> getFiles(LocalDate start, LocalDate end);\n String getFileName(LocalDate start, LocalDate finish);",
"score": 42.39504896297763
}
] | java | String reportFileName = contributionFilesService.getFileName(start, finish); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.PhaseExec;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.WorkloadExec;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Benchmark executor implementation. */
public class LSTBenchmarkExecutor extends BenchmarkRunnable {
private static final Logger LOGGER = LoggerFactory.getLogger(LSTBenchmarkExecutor.class);
private final List<ConnectionManager> connectionManagers;
private final BenchmarkConfig config;
private final SQLTelemetryRegistry telemetryRegistry;
// timestamp of the start of the first iteration of an experiment.
private String experimentStartTime;
public LSTBenchmarkExecutor(
List<ConnectionManager> connectionManagers,
BenchmarkConfig config,
SQLTelemetryRegistry telemetryRegistry) {
super();
this.connectionManagers = Collections.unmodifiableList(connectionManagers);
this.config = config;
this.telemetryRegistry = telemetryRegistry;
}
/** This method runs the experiment. */
public void execute() throws Exception {
this.experimentStartTime = DateTimeFormatter.U_FORMATTER.format(Instant.now());
LOGGER.info("Running experiment: {}, start-time: {}", config.getId(), experimentStartTime);
final WorkloadExec workload = config.getWorkload();
// Thread pool size to max number of concurrent sessions
int maxConcurrentSessions = 1;
for (PhaseExec phase : workload.getPhases()) {
if (phase.getSessions().size() > maxConcurrentSessions) {
maxConcurrentSessions = phase.getSessions().size();
}
}
ExecutorService executor = null;
for (int i = 0; i < config.getRepetitions(); i++) {
LOGGER.info("Starting repetition: {}", i);
final Instant repetitionStartTime = Instant.now();
Map<String, Object> experimentMetadata = new HashMap<>(config.getMetadata());
try {
executor = Executors.newFixedThreadPool(maxConcurrentSessions);
// Fill in specific runtime parameter values
Map<String, Object> runtimeParameterValues = new HashMap<>();
runtimeParameterValues.put("repetition", i);
runtimeParameterValues.put("experiment_start_time", experimentStartTime);
experimentMetadata.putAll(runtimeParameterValues);
// Go over phases and execute
Map<String, Instant> phaseIdToEndTime = new HashMap<>();
for (PhaseExec phase : workload.getPhases()) {
LOGGER.info("Running " + phase.getId() + " phase...");
final Instant phaseStartTime = Instant.now();
EventInfo eventInfo;
try {
final List<SessionExecutor> threads = new ArrayList<>();
for (SessionExec session : phase.getSessions()) {
threads.add(
new SessionExecutor(
connectionManagers.get(session.getTargetEndpoint()),
this.telemetryRegistry,
session,
runtimeParameterValues,
phaseIdToEndTime,
this.experimentStartTime));
}
checkResults(executor.invokeAll(threads));
eventInfo = writePhaseEvent(phaseStartTime, phase.getId(), Status.SUCCESS);
} catch (Exception e) {
LOGGER.error("Exception executing phase: " + phase.getId());
writePhaseEvent(phaseStartTime, phase.getId(), Status.FAILURE);
throw e;
} finally {
telemetryRegistry.flush();
}
LOGGER.info(
"Phase {} finished in {} seconds.",
| phase.getId(),
ChronoUnit.SECONDS.between(phaseStartTime, eventInfo.getEndTime())); |
phaseIdToEndTime.put(phase.getId(), eventInfo.getEndTime());
}
// Log end-to-end execution of experiment.
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.SUCCESS,
new ObjectMapper().writeValueAsString(experimentMetadata));
} catch (Exception e) {
LOGGER.error("Exception executing experiment: " + config.getId());
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.FAILURE,
new ObjectMapper().writeValueAsString(experimentMetadata));
throw e;
} finally {
if (executor != null) {
executor.shutdown();
Validate.isTrue(executor.awaitTermination(1, TimeUnit.MINUTES));
}
telemetryRegistry.flush();
}
LOGGER.info("Finished repetition {}", i);
}
LOGGER.info("Finished experiment: {}", config.getId());
}
private void checkResults(List<Future<Boolean>> results) {
for (Future<Boolean> result : results) {
try {
Validate.isTrue(result.get());
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Thread did not finish correctly", e);
}
}
}
private EventInfo writeExperimentEvent(
Instant startTime, String id, Status status, String payload) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime,
startTime,
Instant.now(),
id,
EventType.EXEC_EXPERIMENT,
status)
.withPayload(payload);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writePhaseEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_PHASE, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " }\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);",
"score": 45.759987391524625
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 43.68078207664001
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " Instant taskStartTime = Instant.now();\n try {\n taskExecutor.executeTask(connection, task, values);\n } catch (Exception e) {\n LOGGER.error(\"Exception executing task: \" + task.getId());\n writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);\n throw e;\n }\n writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);\n }",
"score": 43.46824458006353
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " } catch (Exception e) {\n LOGGER.error(\"Exception executing session: \" + session.getId());\n writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);\n throw e;\n }\n writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);\n return true;\n }\n private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {\n Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);",
"score": 40.73803188110408
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " StringUtils.replaceParameters(statement, localValues).getStatement());\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n // Reset query result.\n queryResult = null;\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeStatementEvent(",
"score": 34.69089096872986
}
] | java | phase.getId(),
ChronoUnit.SECONDS.between(phaseStartTime, eventInfo.getEndTime())); |
package com.minivv.pilot.model;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.annotations.Transient;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.constants.SysConstants;
import com.rits.cloning.Cloner;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public class AppSettings extends DomainObject implements Cloneable {
public boolean enableProxy = false;
public String proxyHost = "127.0.0.1";
public int proxyPort = 1087;
public String proxyType = SysConstants.httpProxyType;
public String gptKey;
public String gptModel = "text-davinci-003";
public int gptMaxTokens = 2048;
public int maxWaitSeconds = 60;
public boolean isReplace = false;
public String testConnMsg = SysConstants.testConnMsg;
public Prompts prompts = new Prompts();
public AppSettings() {
this.addDefaultPrompts(this.prompts);
}
@NotNull
public static Project getProject() {
return AppSettingsStorage.getProject();
}
@NotNull
public static AppSettings get() {
AppSettingsStorage instance = AppSettingsStorage.getInstance();
return instance.getState();
}
@Override
public AppSettings clone() {
Cloner cloner = new Cloner();
cloner.nullInsteadOfClone();
return cloner.deepClone(this);
}
public static void resetDefaultPrompts(List<Prompt> _prompts) {
Prompts prompts = addDefaultPrompts(new Prompts());
Map<String, String> stringStringMap = prompts.asMap();
_prompts.removeIf(next -> stringStringMap.containsKey | (next.getOption())); |
_prompts.addAll(prompts.getPrompts());
}
@Transient
public static Prompts addDefaultPrompts(Prompts prompts) {
prompts.add(Prompt.of("Readable", "help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("List Steps", "help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("Explain", "帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("步骤注释", "帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("emptyForYou", "balabala{query}"));
return prompts;
}
} | src/main/java/com/minivv/pilot/model/AppSettings.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "package com.minivv.pilot.model;\nimport java.util.*;\npublic class Prompts extends DomainObject {\n private List<Prompt> prompts = new ArrayList<>();\n public Prompts() {\n }\n public Prompts(List<Prompt> prompts) {\n this.prompts = prompts;\n }\n public List<Prompt> getPrompts() {",
"score": 26.03640907498563
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n }\n public void reset(AppSettings settings) {\n obtainPrompts(prompts, settings);\n promptTableModel.fireTableDataChanged();\n }\n public boolean isModified(AppSettings settings) {\n final ArrayList<Prompt> _prompts = new ArrayList<>();\n obtainPrompts(_prompts, settings);\n return !_prompts.equals(prompts);",
"score": 26.01345951736772
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " }\n return prompts.add(o);\n }\n public int size() {\n return prompts.size();\n }\n public Map<String, String> asMap() {\n HashMap<String, String> stringStringHashMap = new HashMap<>();\n for (Prompt prompt : prompts) {\n stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());",
"score": 24.419771928608707
},
{
"filename": "src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java",
"retrieved_chunk": " settings.maxWaitSeconds = (int) maxWaitSeconds.getValue();\n settings.proxyType = httpProxy.isSelected() ? SysConstants.httpProxyType : SysConstants.socketProxyType;\n settings.testConnMsg = testConnMsg.getText();\n settings.prompts = new Prompts(promptsTable.prompts);\n }\n public void importForm(AppSettings state) {\n this.settings = state.clone();\n setData(settings);\n promptsTable.reset(settings);\n }",
"score": 18.188932578670844
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "// }\n// public void add(String s, String to,int index) {\n// prompts.add(new Prompt(s, to,index));\n// }\n public void add(String s, String to) {\n prompts.add(new Prompt(s, to));\n }\n public boolean add(Prompt o) {\n if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {\n return false;",
"score": 17.415645653567672
}
] | java | (next.getOption())); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import com.microsoft.lst_bench.util.StringUtils;
import java.lang.reflect.Constructor;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default executor for sessions. Iterates over all tasks contained in the session and executes them
* sequentially.
*/
public class SessionExecutor implements Callable<Boolean> {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionExecutor.class);
private final ConnectionManager connectionManager;
private final SQLTelemetryRegistry telemetryRegistry;
private final SessionExec session;
private final Map<String, Object> runtimeParameterValues;
private final Map<String, Instant> phaseIdToEndTime;
private String experimentStartTime;
public SessionExecutor(
ConnectionManager connectionManager,
SQLTelemetryRegistry telemetryRegistry,
SessionExec session,
Map<String, Object> runtimeParameterValues,
Map<String, Instant> phaseIdToEndTime,
String experimentStartTime) {
this.connectionManager = connectionManager;
this.telemetryRegistry = telemetryRegistry;
this.session = session;
this.runtimeParameterValues = runtimeParameterValues;
this.phaseIdToEndTime = phaseIdToEndTime;
this.experimentStartTime = experimentStartTime;
}
@Override
public Boolean call() throws ClientException {
Instant sessionStartTime = Instant.now();
try (Connection connection = connectionManager.createConnection()) {
for (TaskExec task : session.getTasks()) {
Map<String, Object> values = updateRuntimeParameterValues(task);
TaskExecutor taskExecutor = getTaskExecutor(task);
Instant taskStartTime = Instant.now();
try {
taskExecutor.executeTask(connection, task, values);
} catch (Exception e) {
LOGGER.error("Exception executing task: " + task.getId());
writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);
throw e;
}
writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);
}
} catch (Exception e) {
LOGGER.error("Exception executing session: " + session.getId());
writeSessionEvent(sessionStartTime | , session.getId(), Status.FAILURE); |
throw e;
}
writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);
return true;
}
private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {
Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);
if (task.getTimeTravelPhaseId() != null) {
Instant ttPhaseEndTime = this.phaseIdToEndTime.get(task.getTimeTravelPhaseId());
if (ttPhaseEndTime == null) {
throw new RuntimeException(
"Time travel phase identifier not found: " + task.getTimeTravelPhaseId());
}
// We round to the next second to make sure we are capturing the changes in case
// are consecutive phases
String timeTravelValue =
DateTimeFormatter.AS_OF_FORMATTER.format(
ttPhaseEndTime.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));
values.put("asof", "TIMESTAMP AS OF " + StringUtils.quote(timeTravelValue));
} else {
values.put("asof", "");
}
return values;
}
private TaskExecutor getTaskExecutor(TaskExec task) {
if (task.getCustomTaskExecutor() == null) {
return new TaskExecutor(this.telemetryRegistry, this.experimentStartTime);
} else {
try {
Constructor<?> constructor =
Class.forName(task.getCustomTaskExecutor())
.getDeclaredConstructor(
SQLTelemetryRegistry.class, String.class, CustomTaskExecutorArguments.class);
return (TaskExecutor)
constructor.newInstance(
this.telemetryRegistry,
this.experimentStartTime,
task.getCustomTaskExecutorArguments());
} catch (Exception e) {
throw new IllegalArgumentException(
"Unable to load custom task class: " + task.getCustomTaskExecutor(), e);
}
}
}
private EventInfo writeSessionEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_SESSION, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writeTaskEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_TASK, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " }\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeFileEvent(fileStartTime, file.getId(), Status.FAILURE);\n throw e;\n }\n writeFileEvent(fileStartTime, file.getId(), Status.SUCCESS);",
"score": 96.05860819954471
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java",
"retrieved_chunk": " Status.SUCCESS,\n new ObjectMapper().writeValueAsString(experimentMetadata));\n } catch (Exception e) {\n LOGGER.error(\"Exception executing experiment: \" + config.getId());\n writeExperimentEvent(\n repetitionStartTime,\n config.getId(),\n Status.FAILURE,\n new ObjectMapper().writeValueAsString(experimentMetadata));\n throw e;",
"score": 92.95199678341285
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java",
"retrieved_chunk": " }\n checkResults(executor.invokeAll(threads));\n eventInfo = writePhaseEvent(phaseStartTime, phase.getId(), Status.SUCCESS);\n } catch (Exception e) {\n LOGGER.error(\"Exception executing phase: \" + phase.getId());\n writePhaseEvent(phaseStartTime, phase.getId(), Status.FAILURE);\n throw e;\n } finally {\n telemetryRegistry.flush();\n }",
"score": 91.11352816005484
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/TaskExecutor.java",
"retrieved_chunk": " try {\n connection.execute(StringUtils.replaceParameters(statement, values).getStatement());\n } catch (Exception e) {\n LOGGER.error(\"Exception executing statement: \" + statement.getId());\n writeStatementEvent(\n statementStartTime,\n statement.getId(),\n Status.FAILURE,\n e.getMessage() + \"; \" + e.getStackTrace());\n throw e;",
"score": 84.58620597474219
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " StringUtils.replaceParameters(statement, localValues).getStatement());\n writeStatementEvent(\n statementStartTime, statement.getId(), Status.SUCCESS, /* payload= */ null);\n }\n // Reset query result.\n queryResult = null;\n }\n } catch (Exception e) {\n LOGGER.error(\"Exception executing file: \" + file.getId());\n writeStatementEvent(",
"score": 73.86050442824234
}
] | java | , session.getId(), Status.FAILURE); |
package uk.gov.justice.laa.crime.dces.report.service;
import io.github.resilience4j.retry.annotation.Retry;
import jakarta.xml.bind.JAXBException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import uk.gov.justice.laa.crime.dces.report.client.FdcFilesClient;
import uk.gov.justice.laa.crime.dces.report.maatapi.exception.MaatApiClientException;
import uk.gov.justice.laa.crime.dces.report.mapper.FdcFileMapper;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
@Service
@RequiredArgsConstructor
@Slf4j
public class FdcFilesService implements DcesReportFileService {
private static final String SERVICE_NAME = "dcesReportFdc";
private static final String FILE_NAME_TEMPLATE = "FDC_%s_%s";
private final FdcFilesClient fdcFilesClient;
private final FdcFileMapper fdcFileMapper;
@Retry(name = SERVICE_NAME)
public List<String> getFiles(LocalDate start, LocalDate end) {
if (end.isBefore(start)) {
String message = String.format("invalid time range %s is before %s", end, start);
throw new MaatApiClientException(message);
}
log.info("Start - call MAAT API to collect FDC files, between {} and {}", start, end);
return fdcFilesClient.getContributions(start, end);
}
public File processFiles(List<String> files, LocalDate start, LocalDate finish) throws JAXBException, IOException {
return | fdcFileMapper.processRequest(files.toArray(new String[0]), getFileName(start, finish)); |
}
public String getFileName(LocalDate start, LocalDate finish) {
return String.format(FILE_NAME_TEMPLATE, start, finish);
}
}
| dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/FdcFilesService.java | ministryofjustice-laa-dces-report-service-ac8db88 | [
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/ContributionFilesService.java",
"retrieved_chunk": " @Retry(name = SERVICE_NAME)\n public List<String> getFiles(LocalDate start, LocalDate finish) {\n log.info(\"Start - call MAAT API to collect contribution files date between {} and {}\", start.toString(), finish.toString());\n return contributionFilesClient.getContributions(start, finish);\n }\n public File processFiles(List<String> files, LocalDate start, LocalDate finish, String fileName) throws JAXBException, IOException {\n return contributionFilesMapper.processRequest(files.toArray(new String[0]), start, finish, fileName);\n }\n public String getFileName(LocalDate start, LocalDate finish) {\n return String.format(FILE_NAME_TEMPLATE, start, finish);",
"score": 134.3921977124986
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportServiceImpl.java",
"retrieved_chunk": " contributionFiles,\n start,\n end,\n contributionFilesService.getFileName(start, end)\n );\n }\n public File getFdcReport(LocalDate start, LocalDate end) throws JAXBException, IOException {\n List<String> contributionFiles = fdcFilesService.getFiles(start, end);\n // @TODO handle empty list\n return fdcFilesService.processFiles(contributionFiles, start, end);",
"score": 88.10144027644026
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportFileService.java",
"retrieved_chunk": "/*\n This interface defines a contract for retrieving records and or files held within MAAT\n and accessible via its API and integrating the appropriate webclient.\n */\npackage uk.gov.justice.laa.crime.dces.report.service;\nimport java.time.LocalDate;\nimport java.util.List;\npublic interface DcesReportFileService {\n List<String> getFiles(LocalDate start, LocalDate end);\n String getFileName(LocalDate start, LocalDate finish);",
"score": 77.81554362637316
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/controller/ContributionsReportController.java",
"retrieved_chunk": " )\n )\n public File getContributionFiles(@PathVariable(\"start\") LocalDate start, @PathVariable(\"finish\") LocalDate finish) throws JAXBException, IOException {\n List<String> contributionFiles = contributionFilesService.getFiles(start, finish);\n String reportFileName = contributionFilesService.getFileName(start, finish);\n return contributionFilesService.processFiles(contributionFiles, start, finish, reportFileName);\n }\n}",
"score": 75.73777703171704
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportServiceImpl.java",
"retrieved_chunk": "@RequiredArgsConstructor\npublic class DcesReportServiceImpl implements DcesReportService {\n @Autowired\n private FdcFilesService fdcFilesService;\n @Autowired\n private ContributionFilesService contributionFilesService;\n public File getContributionsReport(LocalDate start, LocalDate end) throws JAXBException, IOException {\n List<String> contributionFiles = contributionFilesService.getFiles(start, end);\n // @TODO handle empty list\n return contributionFilesService.processFiles(",
"score": 68.07164847265469
}
] | java | fdcFileMapper.processRequest(files.toArray(new String[0]), getFileName(start, finish)); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.common.BenchmarkConfig;
import com.microsoft.lst_bench.common.BenchmarkRunnable;
import com.microsoft.lst_bench.common.LSTBenchmarkExecutor;
import com.microsoft.lst_bench.input.BenchmarkObjectFactory;
import com.microsoft.lst_bench.input.TaskLibrary;
import com.microsoft.lst_bench.input.Workload;
import com.microsoft.lst_bench.input.config.ConnectionConfig;
import com.microsoft.lst_bench.input.config.ConnectionsConfig;
import com.microsoft.lst_bench.input.config.ExperimentConfig;
import com.microsoft.lst_bench.input.config.TelemetryConfig;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.telemetry.TelemetryHook;
import com.microsoft.lst_bench.util.FileParser;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** This is the main class. */
public class Driver {
private static final Logger LOGGER = LoggerFactory.getLogger(Driver.class);
private static final String OPT_INPUT_TASK_LIBRARY_FILE = "task-library";
private static final String OPT_INPUT_WORKLOAD_FILE = "workload";
private static final String OPT_INPUT_CONNECTION_CONFIG_FILE = "connections-config";
private static final String OPT_INPUT_EXPERIMENT_CONFIG_FILE = "experiment-config";
private static final String OPT_INPUT_TELEMETRY_CONFIG_FILE = "input-log-config";
/** Defeat instantiation. */
private Driver() {}
/** Main method. */
public static void main(String[] args) throws Exception {
String inputTaskLibraryFile = null;
String inputWorkloadFile = null;
String inputConnectionsConfigFile = null;
String inputExperimentConfigFile = null;
String inputTelemetryConfigFile = null;
// Retrieve program input values
final Options options = createOptions();
final CommandLineParser parser = new DefaultParser();
try {
final CommandLine cmd = parser.parse(options, args);
if (cmd.getOptions().length == 0) {
usageAndHelp();
} else {
if (cmd.hasOption(OPT_INPUT_TASK_LIBRARY_FILE)) {
inputTaskLibraryFile = cmd.getOptionValue(OPT_INPUT_TASK_LIBRARY_FILE);
}
if (cmd.hasOption(OPT_INPUT_WORKLOAD_FILE)) {
inputWorkloadFile = cmd.getOptionValue(OPT_INPUT_WORKLOAD_FILE);
}
if (cmd.hasOption(OPT_INPUT_CONNECTION_CONFIG_FILE)) {
inputConnectionsConfigFile = cmd.getOptionValue(OPT_INPUT_CONNECTION_CONFIG_FILE);
}
if (cmd.hasOption(OPT_INPUT_EXPERIMENT_CONFIG_FILE)) {
inputExperimentConfigFile = cmd.getOptionValue(OPT_INPUT_EXPERIMENT_CONFIG_FILE);
}
if (cmd.hasOption(OPT_INPUT_TELEMETRY_CONFIG_FILE)) {
inputTelemetryConfigFile = cmd.getOptionValue(OPT_INPUT_TELEMETRY_CONFIG_FILE);
}
}
} catch (MissingOptionException | UnrecognizedOptionException e) {
usageAndHelp();
return;
}
// Validate input values
Validate.notNull(inputTaskLibraryFile, "TaskExec library file is required.");
Validate.notNull(inputWorkloadFile, "Workload file is required.");
Validate.notNull(inputConnectionsConfigFile, "Connections config file is required.");
Validate.notNull(inputExperimentConfigFile, "Experiment config file is required.");
Validate.notNull(inputTelemetryConfigFile, "Telemetry config file is required.");
// Create Java objects from input files
final TaskLibrary taskLibrary =
FileParser.createObject(inputTaskLibraryFile, TaskLibrary.class);
final Workload workload = FileParser.createObject(inputWorkloadFile, Workload.class);
final ConnectionsConfig connectionsConfig =
FileParser.createObject(inputConnectionsConfigFile, ConnectionsConfig.class);
final ExperimentConfig experimentConfig =
FileParser.createObject(inputExperimentConfigFile, ExperimentConfig.class);
final TelemetryConfig telemetryConfig =
FileParser.createObject(inputTelemetryConfigFile, TelemetryConfig.class);
run(taskLibrary, workload, connectionsConfig, experimentConfig, telemetryConfig);
}
/** Run benchmark. */
public static void run(
TaskLibrary taskLibrary,
Workload workload,
ConnectionsConfig connectionsConfig,
ExperimentConfig experimentConfig,
TelemetryConfig telemetryConfig)
throws Exception {
// Create connections managers
Set<String> connectionManagerIds = new HashSet<>();
List<ConnectionManager> connectionManagers = new ArrayList<>();
for (ConnectionConfig connectionConfig : connectionsConfig.getConnections()) {
ConnectionManager connectionManager =
BenchmarkObjectFactory.connectionManager(connectionConfig);
if (!connectionManagerIds.add(connectionConfig.getId())) {
throw new IllegalArgumentException("Duplicate connection id: " + connectionConfig.getId());
}
connectionManagers.add(connectionManager);
}
// Create log utility
final ConnectionManager telemetryConnectionManager =
BenchmarkObjectFactory.connectionManager(telemetryConfig.getConnection());
final SQLTelemetryRegistry telemetryRegistry =
new SQLTelemetryRegistry(
telemetryConnectionManager,
telemetryConfig.isExecuteDDL(),
telemetryConfig.getDDLFile(),
telemetryConfig.getInsertFile(),
telemetryConfig.getParameterValues());
Thread telemetryHook = new TelemetryHook(telemetryRegistry);
Runtime.getRuntime().addShutdownHook(telemetryHook);
// Create experiment configuration
final BenchmarkConfig benchmarkConfig =
BenchmarkObjectFactory.benchmarkConfig(experimentConfig, taskLibrary, workload);
// Run experiment
final BenchmarkRunnable experiment =
new LSTBenchmarkExecutor(connectionManagers, benchmarkConfig, telemetryRegistry);
| experiment.execute(); |
}
private static Options createOptions() {
final Options options = new Options();
final Option inputTaskLibraryFile =
Option.builder()
.required()
.option("l")
.longOpt(OPT_INPUT_TASK_LIBRARY_FILE)
.hasArg()
.argName("arg")
.desc("Path to input file containing the library with task templates")
.build();
options.addOption(inputTaskLibraryFile);
final Option inputWorkloadFile =
Option.builder()
.required()
.option("w")
.longOpt(OPT_INPUT_WORKLOAD_FILE)
.hasArg()
.argName("arg")
.desc("Path to input file containing the workload definition")
.build();
options.addOption(inputWorkloadFile);
final Option inputConnectionConfigFile =
Option.builder()
.required()
.option("c")
.longOpt(OPT_INPUT_CONNECTION_CONFIG_FILE)
.hasArg()
.argName("arg")
.desc("Path to input file containing connections config details")
.build();
options.addOption(inputConnectionConfigFile);
final Option inputExperimentConfigFile =
Option.builder()
.required()
.option("e")
.longOpt(OPT_INPUT_EXPERIMENT_CONFIG_FILE)
.hasArg()
.argName("arg")
.desc("Path to input file containing the experiment config details")
.build();
options.addOption(inputExperimentConfigFile);
final Option inputTelemetryConfigFile =
Option.builder()
.required()
.option("t")
.longOpt(OPT_INPUT_TELEMETRY_CONFIG_FILE)
.hasArg()
.argName("arg")
.desc("Path to input file containing the telemetry gathering config details")
.build();
options.addOption(inputTelemetryConfigFile);
return options;
}
private static void usageAndHelp() {
// Print usage and help
final HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(120);
formatter.printHelp("./launcher.sh", createOptions(), true);
}
}
| src/main/java/com/microsoft/lst_bench/Driver.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " * Creates a benchmark configuration from the experiment configuration, task library, and\n * workload.\n *\n * @param experimentConfig the experiment configuration\n * @param taskLibrary the task library\n * @param workload the workload\n * @return a benchmark configuration\n */\n public static BenchmarkConfig benchmarkConfig(\n ExperimentConfig experimentConfig, TaskLibrary taskLibrary, Workload workload) {",
"score": 57.23200875748432
},
{
"filename": "src/test/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutorTest.java",
"retrieved_chunk": " getClass().getClassLoader().getResource(\"./config/spark/w_all_tpcds-delta.yaml\");\n Assertions.assertNotNull(workloadFile);\n Workload workload = FileParser.createObject(workloadFile.getFile(), Workload.class);\n var config = BenchmarkObjectFactory.benchmarkConfig(experimentConfig, taskLibrary, workload);\n SQLTelemetryRegistry telemetryRegistry = getTelemetryRegistry();\n LSTBenchmarkExecutor benchmark =\n new LSTBenchmarkExecutor(connectionManagers, config, telemetryRegistry);\n benchmark.run();\n try (var validationConnection =\n DriverManager.getConnection(\"jdbc:duckdb:./\" + telemetryDbFileName)) {",
"score": 47.39006361905366
},
{
"filename": "src/test/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutorTest.java",
"retrieved_chunk": " ImmutableExperimentConfig.builder().id(\"nooptest\").version(1).repetitions(1).build();\n TaskLibrary taskLibrary = ImmutableTaskLibrary.builder().version(1).build();\n Workload workload = ImmutableWorkload.builder().id(\"nooptest\").version(1).build();\n var config = BenchmarkObjectFactory.benchmarkConfig(experimentConfig, taskLibrary, workload);\n SQLTelemetryRegistry telemetryRegistry = getTelemetryRegistry();\n LSTBenchmarkExecutor benchmark =\n new LSTBenchmarkExecutor(idToConnectionManager, config, telemetryRegistry);\n benchmark.run();\n }\n /**",
"score": 45.69762414570243
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java",
"retrieved_chunk": " public LSTBenchmarkExecutor(\n List<ConnectionManager> connectionManagers,\n BenchmarkConfig config,\n SQLTelemetryRegistry telemetryRegistry) {\n super();\n this.connectionManagers = Collections.unmodifiableList(connectionManagers);\n this.config = config;\n this.telemetryRegistry = telemetryRegistry;\n }\n /** This method runs the experiment. */",
"score": 44.345801070927585
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java",
"retrieved_chunk": "import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n/** Benchmark executor implementation. */\npublic class LSTBenchmarkExecutor extends BenchmarkRunnable {\n private static final Logger LOGGER = LoggerFactory.getLogger(LSTBenchmarkExecutor.class);\n private final List<ConnectionManager> connectionManagers;\n private final BenchmarkConfig config;\n private final SQLTelemetryRegistry telemetryRegistry;\n // timestamp of the start of the first iteration of an experiment.\n private String experimentStartTime;",
"score": 44.034395642259724
}
] | java | experiment.execute(); |
package uk.gov.justice.laa.crime.dces.report.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.xml.bind.JAXBException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.gov.justice.laa.crime.dces.report.service.ContributionFilesService;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/internal/v1/dces/report")
@Tag(name = "DCES Contribution files report", description = "Rest API to retrieve and generate contribution files report")
public class ContributionsReportController {
private ContributionFilesService contributionFilesService;
@GetMapping(value = "/contributions/{start}/{finish}")
@Operation(description = "Retrieve information regarding contribution files sent during the given period and generate a report")
@ApiResponse(responseCode = "200")
@ApiResponse(responseCode = "400",
description = "Bad request.",
content = @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE,
schema = @Schema(implementation = ProblemDetail.class)
)
)
@ApiResponse(responseCode = "500",
description = "Server Error.",
content = @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE,
schema = @Schema(implementation = ProblemDetail.class)
)
)
public File getContributionFiles(@PathVariable("start") LocalDate start, @PathVariable("finish") LocalDate finish) throws JAXBException, IOException {
List | <String> contributionFiles = contributionFilesService.getFiles(start, finish); |
String reportFileName = contributionFilesService.getFileName(start, finish);
return contributionFilesService.processFiles(contributionFiles, start, finish, reportFileName);
}
}
| dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/controller/ContributionsReportController.java | ministryofjustice-laa-dces-report-service-ac8db88 | [
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/ContributionFilesService.java",
"retrieved_chunk": " @Retry(name = SERVICE_NAME)\n public List<String> getFiles(LocalDate start, LocalDate finish) {\n log.info(\"Start - call MAAT API to collect contribution files date between {} and {}\", start.toString(), finish.toString());\n return contributionFilesClient.getContributions(start, finish);\n }\n public File processFiles(List<String> files, LocalDate start, LocalDate finish, String fileName) throws JAXBException, IOException {\n return contributionFilesMapper.processRequest(files.toArray(new String[0]), start, finish, fileName);\n }\n public String getFileName(LocalDate start, LocalDate finish) {\n return String.format(FILE_NAME_TEMPLATE, start, finish);",
"score": 52.86378518259879
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/FdcFilesService.java",
"retrieved_chunk": " public File processFiles(List<String> files, LocalDate start, LocalDate finish) throws JAXBException, IOException {\n return fdcFileMapper.processRequest(files.toArray(new String[0]), getFileName(start, finish));\n }\n public String getFileName(LocalDate start, LocalDate finish) {\n return String.format(FILE_NAME_TEMPLATE, start, finish);\n }\n}",
"score": 52.15394785922372
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportServiceImpl.java",
"retrieved_chunk": " contributionFiles,\n start,\n end,\n contributionFilesService.getFileName(start, end)\n );\n }\n public File getFdcReport(LocalDate start, LocalDate end) throws JAXBException, IOException {\n List<String> contributionFiles = fdcFilesService.getFiles(start, end);\n // @TODO handle empty list\n return fdcFilesService.processFiles(contributionFiles, start, end);",
"score": 44.07616270137693
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportServiceImpl.java",
"retrieved_chunk": "@RequiredArgsConstructor\npublic class DcesReportServiceImpl implements DcesReportService {\n @Autowired\n private FdcFilesService fdcFilesService;\n @Autowired\n private ContributionFilesService contributionFilesService;\n public File getContributionsReport(LocalDate start, LocalDate end) throws JAXBException, IOException {\n List<String> contributionFiles = contributionFilesService.getFiles(start, end);\n // @TODO handle empty list\n return contributionFilesService.processFiles(",
"score": 40.450340880177734
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportFileService.java",
"retrieved_chunk": "/*\n This interface defines a contract for retrieving records and or files held within MAAT\n and accessible via its API and integrating the appropriate webclient.\n */\npackage uk.gov.justice.laa.crime.dces.report.service;\nimport java.time.LocalDate;\nimport java.util.List;\npublic interface DcesReportFileService {\n List<String> getFiles(LocalDate start, LocalDate end);\n String getFileName(LocalDate start, LocalDate finish);",
"score": 31.320143725836502
}
] | java | <String> contributionFiles = contributionFilesService.getFiles(start, finish); |
package com.minivv.pilot.model;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.annotations.Transient;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.constants.SysConstants;
import com.rits.cloning.Cloner;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public class AppSettings extends DomainObject implements Cloneable {
public boolean enableProxy = false;
public String proxyHost = "127.0.0.1";
public int proxyPort = 1087;
public String proxyType = SysConstants.httpProxyType;
public String gptKey;
public String gptModel = "text-davinci-003";
public int gptMaxTokens = 2048;
public int maxWaitSeconds = 60;
public boolean isReplace = false;
public String testConnMsg = SysConstants.testConnMsg;
public Prompts prompts = new Prompts();
public AppSettings() {
this.addDefaultPrompts(this.prompts);
}
@NotNull
public static Project getProject() {
return AppSettingsStorage.getProject();
}
@NotNull
public static AppSettings get() {
AppSettingsStorage instance = AppSettingsStorage.getInstance();
return instance.getState();
}
@Override
public AppSettings clone() {
Cloner cloner = new Cloner();
cloner.nullInsteadOfClone();
return cloner.deepClone(this);
}
public static void resetDefaultPrompts(List<Prompt> _prompts) {
Prompts prompts = addDefaultPrompts(new Prompts());
Map<String, String> stringStringMap = prompts.asMap();
_prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));
_prompts.addAll(prompts.getPrompts());
}
@Transient
public static Prompts addDefaultPrompts(Prompts prompts) {
prompts.add(Prompt.of("Readable", "help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("List Steps", "help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("Explain", "帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add | (Prompt.of("步骤注释", "帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{ | query}"));
prompts.add(Prompt.of("emptyForYou", "balabala{query}"));
return prompts;
}
} | src/main/java/com/minivv/pilot/model/AppSettings.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "//\t\tthis.index = index;\n//\t}\n//\tpublic static Prompt of(String name, String value,int index) {\n//\t\treturn new Prompt(name, value,index);\n//\t}\n\tpublic Prompt(String option, String snippet) {\n\t\tthis.option = option;\n\t\tthis.snippet = snippet;\n\t}\n\tpublic static Prompt of(String name, String value) {",
"score": 62.45174856743752
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " @Override\n public String addStatement(String code) {\n return prompt.getSnippet().replace(\"{query}\", code);\n }\n };\n actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);\n actionGroup.add(oldAction);\n }\n popupMenu.add(actionGroup);\n }",
"score": 57.379801805705284
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// @Override\n// public String addStatement(String code) {\n// return prompt.getSnippet().replace(\"{query}\", code);\n// }\n// };\n// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);\n// actionGroup.add(newAction);\n// }\n// ((DefaultActionGroup) popupMenu).add(actionGroup);\n// }",
"score": 54.2080070720531
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "// }\n// public void add(String s, String to,int index) {\n// prompts.add(new Prompt(s, to,index));\n// }\n public void add(String s, String to) {\n prompts.add(new Prompt(s, to));\n }\n public boolean add(Prompt o) {\n if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {\n return false;",
"score": 49.8261052137487
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " return prompts;\n }\n public void setPrompts(List<Prompt> prompts) {\n this.prompts = prompts;\n }\n// public boolean add(Prompt o) {\n// if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()) || Objects.equals(prompt.getIndex(),o.getIndex()))) {\n// return false;\n// }\n// return prompts.add(o);",
"score": 43.97843399912661
}
] | java | (Prompt.of("步骤注释", "帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{ |
package uk.gov.justice.laa.crime.dces.report.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.xml.bind.JAXBException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.gov.justice.laa.crime.dces.report.service.ContributionFilesService;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/internal/v1/dces/report")
@Tag(name = "DCES Contribution files report", description = "Rest API to retrieve and generate contribution files report")
public class ContributionsReportController {
private ContributionFilesService contributionFilesService;
@GetMapping(value = "/contributions/{start}/{finish}")
@Operation(description = "Retrieve information regarding contribution files sent during the given period and generate a report")
@ApiResponse(responseCode = "200")
@ApiResponse(responseCode = "400",
description = "Bad request.",
content = @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE,
schema = @Schema(implementation = ProblemDetail.class)
)
)
@ApiResponse(responseCode = "500",
description = "Server Error.",
content = @Content(mediaType = MediaType.APPLICATION_PROBLEM_JSON_VALUE,
schema = @Schema(implementation = ProblemDetail.class)
)
)
public File getContributionFiles(@PathVariable("start") LocalDate start, @PathVariable("finish") LocalDate finish) throws JAXBException, IOException {
List<String> contributionFiles = contributionFilesService.getFiles(start, finish);
String reportFileName = contributionFilesService.getFileName(start, finish);
return | contributionFilesService.processFiles(contributionFiles, start, finish, reportFileName); |
}
}
| dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/controller/ContributionsReportController.java | ministryofjustice-laa-dces-report-service-ac8db88 | [
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/FdcFilesService.java",
"retrieved_chunk": " public File processFiles(List<String> files, LocalDate start, LocalDate finish) throws JAXBException, IOException {\n return fdcFileMapper.processRequest(files.toArray(new String[0]), getFileName(start, finish));\n }\n public String getFileName(LocalDate start, LocalDate finish) {\n return String.format(FILE_NAME_TEMPLATE, start, finish);\n }\n}",
"score": 90.02447131264768
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/ContributionFilesService.java",
"retrieved_chunk": " @Retry(name = SERVICE_NAME)\n public List<String> getFiles(LocalDate start, LocalDate finish) {\n log.info(\"Start - call MAAT API to collect contribution files date between {} and {}\", start.toString(), finish.toString());\n return contributionFilesClient.getContributions(start, finish);\n }\n public File processFiles(List<String> files, LocalDate start, LocalDate finish, String fileName) throws JAXBException, IOException {\n return contributionFilesMapper.processRequest(files.toArray(new String[0]), start, finish, fileName);\n }\n public String getFileName(LocalDate start, LocalDate finish) {\n return String.format(FILE_NAME_TEMPLATE, start, finish);",
"score": 87.29605350575702
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportServiceImpl.java",
"retrieved_chunk": " contributionFiles,\n start,\n end,\n contributionFilesService.getFileName(start, end)\n );\n }\n public File getFdcReport(LocalDate start, LocalDate end) throws JAXBException, IOException {\n List<String> contributionFiles = fdcFilesService.getFiles(start, end);\n // @TODO handle empty list\n return fdcFilesService.processFiles(contributionFiles, start, end);",
"score": 82.40720240021885
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportServiceImpl.java",
"retrieved_chunk": "@RequiredArgsConstructor\npublic class DcesReportServiceImpl implements DcesReportService {\n @Autowired\n private FdcFilesService fdcFilesService;\n @Autowired\n private ContributionFilesService contributionFilesService;\n public File getContributionsReport(LocalDate start, LocalDate end) throws JAXBException, IOException {\n List<String> contributionFiles = contributionFilesService.getFiles(start, end);\n // @TODO handle empty list\n return contributionFilesService.processFiles(",
"score": 74.1500569805662
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportFileService.java",
"retrieved_chunk": "/*\n This interface defines a contract for retrieving records and or files held within MAAT\n and accessible via its API and integrating the appropriate webclient.\n */\npackage uk.gov.justice.laa.crime.dces.report.service;\nimport java.time.LocalDate;\nimport java.util.List;\npublic interface DcesReportFileService {\n List<String> getFiles(LocalDate start, LocalDate end);\n String getFileName(LocalDate start, LocalDate finish);",
"score": 49.78468112242185
}
] | java | contributionFilesService.processFiles(contributionFiles, start, finish, reportFileName); |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.PhaseExec;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.WorkloadExec;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Benchmark executor implementation. */
public class LSTBenchmarkExecutor extends BenchmarkRunnable {
private static final Logger LOGGER = LoggerFactory.getLogger(LSTBenchmarkExecutor.class);
private final List<ConnectionManager> connectionManagers;
private final BenchmarkConfig config;
private final SQLTelemetryRegistry telemetryRegistry;
// timestamp of the start of the first iteration of an experiment.
private String experimentStartTime;
public LSTBenchmarkExecutor(
List<ConnectionManager> connectionManagers,
BenchmarkConfig config,
SQLTelemetryRegistry telemetryRegistry) {
super();
this.connectionManagers = Collections.unmodifiableList(connectionManagers);
this.config = config;
this.telemetryRegistry = telemetryRegistry;
}
/** This method runs the experiment. */
public void execute() throws Exception {
this.experimentStartTime = DateTimeFormatter.U_FORMATTER.format(Instant.now());
LOGGER.info("Running experiment: {}, start-time: {}", config.getId(), experimentStartTime);
final WorkloadExec workload = config.getWorkload();
// Thread pool size to max number of concurrent sessions
int maxConcurrentSessions = 1;
for (PhaseExec phase : workload.getPhases()) {
if (phase.getSessions().size() > maxConcurrentSessions) {
maxConcurrentSessions = phase.getSessions().size();
}
}
ExecutorService executor = null;
for (int i = 0; i < config.getRepetitions(); i++) {
LOGGER.info("Starting repetition: {}", i);
final Instant repetitionStartTime = Instant.now();
Map<String, Object> experimentMetadata = new HashMap<>(config.getMetadata());
try {
executor = Executors.newFixedThreadPool(maxConcurrentSessions);
// Fill in specific runtime parameter values
Map<String, Object> runtimeParameterValues = new HashMap<>();
runtimeParameterValues.put("repetition", i);
runtimeParameterValues.put("experiment_start_time", experimentStartTime);
experimentMetadata.putAll(runtimeParameterValues);
// Go over phases and execute
Map<String, Instant> phaseIdToEndTime = new HashMap<>();
for (PhaseExec phase : workload.getPhases()) {
LOGGER.info("Running " + phase.getId() + " phase...");
final Instant phaseStartTime = Instant.now();
EventInfo eventInfo;
try {
final List<SessionExecutor> threads = new ArrayList<>();
for (SessionExec session : phase.getSessions()) {
threads.add(
new SessionExecutor(
connectionManagers.get(session.getTargetEndpoint()),
this.telemetryRegistry,
session,
runtimeParameterValues,
phaseIdToEndTime,
this.experimentStartTime));
}
checkResults(executor.invokeAll(threads));
eventInfo = writePhaseEvent(phaseStartTime | , phase.getId(), Status.SUCCESS); |
} catch (Exception e) {
LOGGER.error("Exception executing phase: " + phase.getId());
writePhaseEvent(phaseStartTime, phase.getId(), Status.FAILURE);
throw e;
} finally {
telemetryRegistry.flush();
}
LOGGER.info(
"Phase {} finished in {} seconds.",
phase.getId(),
ChronoUnit.SECONDS.between(phaseStartTime, eventInfo.getEndTime()));
phaseIdToEndTime.put(phase.getId(), eventInfo.getEndTime());
}
// Log end-to-end execution of experiment.
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.SUCCESS,
new ObjectMapper().writeValueAsString(experimentMetadata));
} catch (Exception e) {
LOGGER.error("Exception executing experiment: " + config.getId());
writeExperimentEvent(
repetitionStartTime,
config.getId(),
Status.FAILURE,
new ObjectMapper().writeValueAsString(experimentMetadata));
throw e;
} finally {
if (executor != null) {
executor.shutdown();
Validate.isTrue(executor.awaitTermination(1, TimeUnit.MINUTES));
}
telemetryRegistry.flush();
}
LOGGER.info("Finished repetition {}", i);
}
LOGGER.info("Finished experiment: {}", config.getId());
}
private void checkResults(List<Future<Boolean>> results) {
for (Future<Boolean> result : results) {
try {
Validate.isTrue(result.get());
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Thread did not finish correctly", e);
}
}
}
private EventInfo writeExperimentEvent(
Instant startTime, String id, Status status, String payload) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime,
startTime,
Instant.now(),
id,
EventType.EXEC_EXPERIMENT,
status)
.withPayload(payload);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writePhaseEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_PHASE, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/LSTBenchmarkExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " ConnectionManager connectionManager,\n SQLTelemetryRegistry telemetryRegistry,\n SessionExec session,\n Map<String, Object> runtimeParameterValues,\n Map<String, Instant> phaseIdToEndTime,\n String experimentStartTime) {\n this.connectionManager = connectionManager;\n this.telemetryRegistry = telemetryRegistry;\n this.session = session;\n this.runtimeParameterValues = runtimeParameterValues;",
"score": 39.50946115120555
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " } catch (Exception e) {\n LOGGER.error(\"Exception executing session: \" + session.getId());\n writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);\n throw e;\n }\n writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);\n return true;\n }\n private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {\n Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);",
"score": 29.469923473078012
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " this.phaseIdToEndTime = phaseIdToEndTime;\n this.experimentStartTime = experimentStartTime;\n }\n @Override\n public Boolean call() throws ClientException {\n Instant sessionStartTime = Instant.now();\n try (Connection connection = connectionManager.createConnection()) {\n for (TaskExec task : session.getTasks()) {\n Map<String, Object> values = updateRuntimeParameterValues(task);\n TaskExecutor taskExecutor = getTaskExecutor(task);",
"score": 22.220760624244235
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " */\npublic class SessionExecutor implements Callable<Boolean> {\n private static final Logger LOGGER = LoggerFactory.getLogger(SessionExecutor.class);\n private final ConnectionManager connectionManager;\n private final SQLTelemetryRegistry telemetryRegistry;\n private final SessionExec session;\n private final Map<String, Object> runtimeParameterValues;\n private final Map<String, Instant> phaseIdToEndTime;\n private String experimentStartTime;\n public SessionExecutor(",
"score": 20.785962689460767
},
{
"filename": "src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java",
"retrieved_chunk": " experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_SESSION, status);\n telemetryRegistry.writeEvent(eventInfo);\n return eventInfo;\n }\n private EventInfo writeTaskEvent(Instant startTime, String id, Status status) {\n EventInfo eventInfo =\n ImmutableEventInfo.of(\n experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_TASK, status);\n telemetryRegistry.writeEvent(eventInfo);\n return eventInfo;",
"score": 20.46402747834896
}
] | java | , phase.getId(), Status.SUCCESS); |
package uk.gov.justice.laa.crime.dces.report.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import uk.gov.justice.laa.crime.dces.report.model.generated.FdcFile;
import uk.gov.justice.laa.crime.dces.report.model.generated.FdcFile.FdcList.Fdc;
import uk.gov.justice.laa.crime.dces.report.model.CSVDataLine;
import uk.gov.justice.laa.crime.dces.utils.DateUtils;
import javax.xml.datatype.XMLGregorianCalendar;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.List;
import java.util.Objects;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class CSVFileService {
public static final String FDC_FORMAT = "%s";
public static final String FDC_FORMAT_COMMA = "%s,";
public static final String EMPTY_CHARACTER = "";
public File writeContributionToCsv(List<CSVDataLine> contributionData, File targetFile) throws IOException {
// if file does not exist, we need to add the headers.
if(targetFile.length()==0) {
contributionData.add(0, getContributionsHeader());
}
// filewriter initialise
try (FileWriter fw = new FileWriter(targetFile, true)){
for (CSVDataLine csvDataLine : contributionData) {
writeContributionLine(fw, csvDataLine);
}
} catch (IOException e) {
throw new IOException(e);
}
return targetFile;
}
public File writeContributionToCsv(List<CSVDataLine> contributionData, String fileName) throws IOException {
File targetFile = createCsvFile(fileName);
return writeContributionToCsv(contributionData, targetFile);
}
public void writeFdcToCsv(FdcFile fdcFile, File targetFile) throws IOException {
List<Fdc> fdcList = fdcFile.getFdcList().getFdc();
// filewriter initialise
try (FileWriter fw = new FileWriter(targetFile, true)) {
if (targetFile.length() == 0) {
writeFdcHeader(fw);
}
for (Fdc fdcLine : fdcList) {
writeFdcLine(fw, fdcLine);
}
} catch (IOException e) {
throw new IOException(e);
}
}
public File writeFdcFileListToCsv(List<FdcFile> fdcFiles, String fileName) throws IOException {
File targetFile = createCsvFile(fileName);
for(FdcFile file: fdcFiles){
writeFdcToCsv(file, targetFile);
}
return targetFile;
}
private CSVDataLine getContributionsHeader(){
return CSVDataLine.builder()
.maatId("MAAT ID")
.dataFeedType("Data Feed Type")
.assessmentDate("Assessment Date")
.ccOutcomeDate("CC OutCome Date")
.correspondenceSentDate("Correspondence Sent Date")
.repOrderStatusDate("Rep Order Status Date")
.hardshipReviewDate("Hardship Review Date")
.passportedDate("Passported Date")
.build();
}
private void writeFdcHeader(FileWriter fw) throws IOException {
String headerLine = "MAAT ID, Sentence Date, Calculation Date, Final Cost, LGFS Cost, AGFS COST"+System.lineSeparator();
fw.append(headerLine);
}
private void writeContributionLine(FileWriter fw, CSVDataLine dataLine) throws IOException {
String lineOutput = dataLine.toString()+System.lineSeparator();
fw.append(lineOutput);
}
private void writeFdcLine(FileWriter fw, Fdc fdcLine) throws IOException {
fw.append(fdcLineBuilder(fdcLine));
}
private String fdcLineBuilder(Fdc fdcLine){
StringBuilder sb = new StringBuilder();
sb.append(getFdcValue(fdcLine.getMaatId(),true));
sb.append(getFdcValue(fdcLine.getSentenceDate()));
sb.append(getFdcValue(fdcLine.getCalculationDate()));
sb.append(getFdcValue(fdcLine.getFinalCost(),true));
sb.append(getFdcValue(fdcLine.getLgfsTotal(),true));
sb.append(getFdcValue(fdcLine.getAgfsTotal(),false));
sb.append(System.lineSeparator());
return sb.toString();
}
private String getFdcValue(Object o, boolean insertComma){
return String.format( (insertComma?FDC_FORMAT_COMMA:FDC_FORMAT),(Objects.nonNull(o)?o:EMPTY_CHARACTER));
}
private String getFdcValue(XMLGregorianCalendar o){
return | ( getFdcValue(DateUtils.convertXmlGregorianToString(o),true)); |
}
private File createCsvFile(String fileName) throws IOException {
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"));
return Files.createTempFile(fileName, ".csv", attr).toFile();
}
}
| dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/CSVFileService.java | ministryofjustice-laa-dces-report-service-ac8db88 | [
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/utils/DateUtils.java",
"retrieved_chunk": " public String convertXmlGregorianToString(XMLGregorianCalendar xmlGregorianCalendar){\n if(Objects.nonNull(xmlGregorianCalendar)){\n return df.format(xmlGregorianCalendar.toGregorianCalendar().getTime());\n }\n return \"\";\n }\n public boolean validateDate(XMLGregorianCalendar date, LocalDate startDate, LocalDate endDate){\n if(Objects.isNull(date)){ return false;}\n var convertedDate = LocalDate.parse(date.toString());\n return ( Objects.nonNull(startDate)",
"score": 40.36021629695848
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/mapper/ContributionsFileMapper.java",
"retrieved_chunk": " return EMPTY_CHARACTER;\n }\n return DateUtils.convertXmlGregorianToString(contribution.getAssessment().getEffectiveDate());\n }\n private String getOutcomeDate(CONTRIBUTIONS contribution, LocalDate startDate, LocalDate endDate){\n List<CcOutcome> filteredList = contribution.getCcOutcomes().getCcOutcome()\n .stream()\n .filter(Objects::nonNull)\n .filter(x->DateUtils.validateDate(x.getDate(),startDate,endDate))\n .toList();",
"score": 27.563946994971054
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/mapper/ContributionsFileMapper.java",
"retrieved_chunk": " }\n return DateUtils.convertXmlGregorianToString(contribution.getApplication().getRepStatusDate());\n }\n private String getHardshipReviewDate(CONTRIBUTIONS contribution, LocalDate startDate, LocalDate endDate){\n if(Objects.isNull(contribution.getApplication())\n || Objects.isNull(contribution.getApplication().getCcHardship()) || Objects.isNull(contribution.getApplication().getCcHardship().getReviewDate())\n || !DateUtils.validateDate(contribution.getApplication().getCcHardship().getReviewDate(), startDate, endDate)){\n return EMPTY_CHARACTER;\n }\n return DateUtils.convertXmlGregorianToString(contribution.getApplication().getCcHardship().getReviewDate());",
"score": 26.34228464225526
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/mapper/ContributionsFileMapper.java",
"retrieved_chunk": " }\n private String getPassportedDate(CONTRIBUTIONS contribution, LocalDate startDate, LocalDate endDate){\n if( Objects.isNull(contribution.getPassported()) || Objects.isNull(contribution.getPassported().getDateCompleted())\n || !DateUtils.validateDate(contribution.getPassported().getDateCompleted(), startDate, endDate)){\n return EMPTY_CHARACTER;\n }\n return DateUtils.convertXmlGregorianToString(contribution.getPassported().getDateCompleted());\n }\n}",
"score": 25.65852509806744
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/mapper/ContributionsFileMapper.java",
"retrieved_chunk": " .toList();\n if(!filteredList.isEmpty()){\n return DateUtils.convertXmlGregorianToString(filteredList.get(0).getCreated());\n }\n return \"\";\n }\n private String getRepOrderStatusDate(CONTRIBUTIONS contribution, LocalDate startDate, LocalDate endDate){\n if(Objects.isNull(contribution.getApplication()) || Objects.isNull(contribution.getApplication().getRepStatusDate())\n || !DateUtils.validateDate(contribution.getApplication().getRepStatusDate(), startDate, endDate)){\n return EMPTY_CHARACTER;",
"score": 25.23730891550246
}
] | java | ( getFdcValue(DateUtils.convertXmlGregorianToString(o),true)); |
package com.minivv.pilot.model;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.annotations.Transient;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.constants.SysConstants;
import com.rits.cloning.Cloner;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public class AppSettings extends DomainObject implements Cloneable {
public boolean enableProxy = false;
public String proxyHost = "127.0.0.1";
public int proxyPort = 1087;
public String proxyType = SysConstants.httpProxyType;
public String gptKey;
public String gptModel = "text-davinci-003";
public int gptMaxTokens = 2048;
public int maxWaitSeconds = 60;
public boolean isReplace = false;
public String testConnMsg = SysConstants.testConnMsg;
public Prompts prompts = new Prompts();
public AppSettings() {
this.addDefaultPrompts(this.prompts);
}
@NotNull
public static Project getProject() {
return AppSettingsStorage.getProject();
}
@NotNull
public static AppSettings get() {
AppSettingsStorage instance = AppSettingsStorage.getInstance();
return instance.getState();
}
@Override
public AppSettings clone() {
Cloner cloner = new Cloner();
cloner.nullInsteadOfClone();
return cloner.deepClone(this);
}
public static void resetDefaultPrompts(List<Prompt> _prompts) {
Prompts prompts = addDefaultPrompts(new Prompts());
Map<String, String> stringStringMap = prompts.asMap();
_prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));
_prompts.addAll(prompts.getPrompts());
}
@Transient
public static Prompts addDefaultPrompts(Prompts prompts) {
prompts.add(Prompt.of("Readable", "help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("List Steps", "help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("Explain", "帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("步骤注释", "帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add( | Prompt.of("emptyForYou", "balabala{ | query}"));
return prompts;
}
} | src/main/java/com/minivv/pilot/model/AppSettings.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "//\t\tthis.index = index;\n//\t}\n//\tpublic static Prompt of(String name, String value,int index) {\n//\t\treturn new Prompt(name, value,index);\n//\t}\n\tpublic Prompt(String option, String snippet) {\n\t\tthis.option = option;\n\t\tthis.snippet = snippet;\n\t}\n\tpublic static Prompt of(String name, String value) {",
"score": 69.8029440639065
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " @Override\n public String addStatement(String code) {\n return prompt.getSnippet().replace(\"{query}\", code);\n }\n };\n actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);\n actionGroup.add(oldAction);\n }\n popupMenu.add(actionGroup);\n }",
"score": 61.787394244102316
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// @Override\n// public String addStatement(String code) {\n// return prompt.getSnippet().replace(\"{query}\", code);\n// }\n// };\n// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);\n// actionGroup.add(newAction);\n// }\n// ((DefaultActionGroup) popupMenu).add(actionGroup);\n// }",
"score": 61.0696093364834
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "// }\n// public void add(String s, String to,int index) {\n// prompts.add(new Prompt(s, to,index));\n// }\n public void add(String s, String to) {\n prompts.add(new Prompt(s, to));\n }\n public boolean add(Prompt o) {\n if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {\n return false;",
"score": 55.02085934896965
},
{
"filename": "src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java",
"retrieved_chunk": " private final PromptsTable promptsTable;\n public AppPluginSettingsPage(AppSettings original) {\n this.settings = original.clone();\n this.promptsTable = new PromptsTable();\n promptsPane.add(ToolbarDecorator.createDecorator(promptsTable)\n .setRemoveAction(button -> promptsTable.removeSelectedPrompts())\n .setAddAction(button -> promptsTable.addPrompt(Prompt.of(\"Option\" + promptsTable.getRowCount(), \"Snippet:{query}\")))\n .addExtraAction(new AnActionButton(\"Reset Default Prompts\", AllIcons.Actions.Rollback) {\n @Override\n public void actionPerformed(@NotNull AnActionEvent e) {",
"score": 51.75451458298691
}
] | java | Prompt.of("emptyForYou", "balabala{ |
/*
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microsoft.lst_bench.common;
import com.microsoft.lst_bench.client.ClientException;
import com.microsoft.lst_bench.client.Connection;
import com.microsoft.lst_bench.client.ConnectionManager;
import com.microsoft.lst_bench.exec.SessionExec;
import com.microsoft.lst_bench.exec.TaskExec;
import com.microsoft.lst_bench.input.Task.CustomTaskExecutorArguments;
import com.microsoft.lst_bench.telemetry.EventInfo;
import com.microsoft.lst_bench.telemetry.EventInfo.EventType;
import com.microsoft.lst_bench.telemetry.EventInfo.Status;
import com.microsoft.lst_bench.telemetry.ImmutableEventInfo;
import com.microsoft.lst_bench.telemetry.SQLTelemetryRegistry;
import com.microsoft.lst_bench.util.DateTimeFormatter;
import com.microsoft.lst_bench.util.StringUtils;
import java.lang.reflect.Constructor;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default executor for sessions. Iterates over all tasks contained in the session and executes them
* sequentially.
*/
public class SessionExecutor implements Callable<Boolean> {
private static final Logger LOGGER = LoggerFactory.getLogger(SessionExecutor.class);
private final ConnectionManager connectionManager;
private final SQLTelemetryRegistry telemetryRegistry;
private final SessionExec session;
private final Map<String, Object> runtimeParameterValues;
private final Map<String, Instant> phaseIdToEndTime;
private String experimentStartTime;
public SessionExecutor(
ConnectionManager connectionManager,
SQLTelemetryRegistry telemetryRegistry,
SessionExec session,
Map<String, Object> runtimeParameterValues,
Map<String, Instant> phaseIdToEndTime,
String experimentStartTime) {
this.connectionManager = connectionManager;
this.telemetryRegistry = telemetryRegistry;
this.session = session;
this.runtimeParameterValues = runtimeParameterValues;
this.phaseIdToEndTime = phaseIdToEndTime;
this.experimentStartTime = experimentStartTime;
}
@Override
public Boolean call() throws ClientException {
Instant sessionStartTime = Instant.now();
try (Connection connection = connectionManager.createConnection()) {
for (TaskExec task : session.getTasks()) {
Map<String, Object> values = updateRuntimeParameterValues(task);
TaskExecutor taskExecutor = getTaskExecutor(task);
Instant taskStartTime = Instant.now();
try {
taskExecutor.executeTask(connection, task, values);
} catch (Exception e) {
LOGGER.error("Exception executing task: " + task.getId());
writeTaskEvent(taskStartTime, task.getId(), Status.FAILURE);
throw e;
}
writeTaskEvent(taskStartTime, task.getId(), Status.SUCCESS);
}
} catch (Exception e) {
LOGGER.error("Exception executing session: " + session.getId());
writeSessionEvent(sessionStartTime, session.getId(), Status.FAILURE);
throw e;
}
writeSessionEvent(sessionStartTime, session.getId(), Status.SUCCESS);
return true;
}
private Map<String, Object> updateRuntimeParameterValues(TaskExec task) {
Map<String, Object> values = new HashMap<>(this.runtimeParameterValues);
if (task.getTimeTravelPhaseId() != null) {
Instant ttPhaseEndTime = this.phaseIdToEndTime.get(task.getTimeTravelPhaseId());
if (ttPhaseEndTime == null) {
throw new RuntimeException(
"Time travel phase identifier not found: " + task.getTimeTravelPhaseId());
}
// We round to the next second to make sure we are capturing the changes in case
// are consecutive phases
String timeTravelValue =
DateTimeFormatter.AS_OF_FORMATTER.format(
ttPhaseEndTime.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));
values.put("asof", "TIMESTAMP AS OF " + StringUtils.quote(timeTravelValue));
} else {
values.put("asof", "");
}
return values;
}
private TaskExecutor getTaskExecutor(TaskExec task) {
if | (task.getCustomTaskExecutor() == null) { |
return new TaskExecutor(this.telemetryRegistry, this.experimentStartTime);
} else {
try {
Constructor<?> constructor =
Class.forName(task.getCustomTaskExecutor())
.getDeclaredConstructor(
SQLTelemetryRegistry.class, String.class, CustomTaskExecutorArguments.class);
return (TaskExecutor)
constructor.newInstance(
this.telemetryRegistry,
this.experimentStartTime,
task.getCustomTaskExecutorArguments());
} catch (Exception e) {
throw new IllegalArgumentException(
"Unable to load custom task class: " + task.getCustomTaskExecutor(), e);
}
}
}
private EventInfo writeSessionEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_SESSION, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
private EventInfo writeTaskEvent(Instant startTime, String id, Status status) {
EventInfo eventInfo =
ImmutableEventInfo.of(
experimentStartTime, startTime, Instant.now(), id, EventType.EXEC_TASK, status);
telemetryRegistry.writeEvent(eventInfo);
return eventInfo;
}
}
| src/main/java/com/microsoft/lst_bench/common/SessionExecutor.java | microsoft-lst-bench-96ac3ca | [
{
"filename": "src/main/java/com/microsoft/lst_bench/common/DependentTaskExecutor.java",
"retrieved_chunk": " @Override\n public void executeTask(Connection connection, TaskExec task, Map<String, Object> values)\n throws ClientException {\n int batch_size;\n if (this.arguments == null || this.arguments.getDependentTaskBatchSize() == null) {\n batch_size = DEFAULT_BATCH_SIZE;\n } else {\n batch_size = this.arguments.getDependentTaskBatchSize().intValue();\n }\n QueryResult queryResult = null;",
"score": 28.897958167658075
},
{
"filename": "src/main/java/com/microsoft/lst_bench/util/StringUtils.java",
"retrieved_chunk": "/** Utility class for string operations. */\npublic class StringUtils {\n private static final Logger LOGGER = LoggerFactory.getLogger(StringUtils.class);\n private StringUtils() {\n // Defeat instantiation\n }\n public static String format(String format, Map<String, Object> values) {\n return StringSubstitutor.replace(format, values);\n }\n public static String quote(String str) {",
"score": 27.522217863208134
},
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " if (taskTemplate.getParameterValuesFile() != null) {\n // Include parameter values defined in the task template\n parameterValues.putAll(\n FileParser.getParameterValues(\n taskTemplate.getParameterValuesFile(),\n taskTemplateIdToParameterValuesCounter.compute(\n taskTemplate.getId(), (k, v) -> v == null ? 1 : v + 1)));\n }\n if (experimentConfig.getParameterValues() != null) {\n // Include experiment-specific parameter values (they can override the ones defined in",
"score": 26.425862155931526
},
{
"filename": "src/main/java/com/microsoft/lst_bench/telemetry/SQLTelemetryRegistry.java",
"retrieved_chunk": " }\n /** Flushes the events to the database. */\n public void flush() throws EventException {\n if (eventsStream.isEmpty()) return;\n LOGGER.info(\"Flushing events to database...\");\n try (Connection connection = connectionManager.createConnection()) {\n Map<String, Object> values = new HashMap<>();\n values.put(\n \"tuples\",\n eventsStream.stream()",
"score": 25.93975516846637
},
{
"filename": "src/main/java/com/microsoft/lst_bench/input/BenchmarkObjectFactory.java",
"retrieved_chunk": " Map<String, FileExec> idToFile = new HashMap<>();\n for (FileExec file : files) {\n idToFile.put(file.getId(), file);\n }\n int counter;\n if (Boolean.TRUE.equals(task.isPermuteOrder())) {\n counter =\n taskTemplateIdToPermuteOrderCounter.compute(\n taskTemplate.getId(), (k, v) -> v == null ? 1 : v + 1);\n } else {",
"score": 24.23344453744896
}
] | java | (task.getCustomTaskExecutor() == null) { |
package uk.gov.justice.laa.crime.dces.report.service;
import jakarta.xml.bind.JAXBException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
@Service
@RequiredArgsConstructor
public class DcesReportServiceImpl implements DcesReportService {
@Autowired
private FdcFilesService fdcFilesService;
@Autowired
private ContributionFilesService contributionFilesService;
public File getContributionsReport(LocalDate start, LocalDate end) throws JAXBException, IOException {
List<String> contributionFiles = contributionFilesService.getFiles(start, end);
// @TODO handle empty list
return contributionFilesService.processFiles(
contributionFiles,
start,
end,
contributionFilesService.getFileName(start, end)
);
}
public File getFdcReport(LocalDate start, LocalDate end) throws JAXBException, IOException {
List<String> contributionFiles = fdcFilesService.getFiles(start, end);
// @TODO handle empty list
| return fdcFilesService.processFiles(contributionFiles, start, end); |
}
}
| dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportServiceImpl.java | ministryofjustice-laa-dces-report-service-ac8db88 | [
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/controller/ContributionsReportController.java",
"retrieved_chunk": " )\n )\n public File getContributionFiles(@PathVariable(\"start\") LocalDate start, @PathVariable(\"finish\") LocalDate finish) throws JAXBException, IOException {\n List<String> contributionFiles = contributionFilesService.getFiles(start, finish);\n String reportFileName = contributionFilesService.getFileName(start, finish);\n return contributionFilesService.processFiles(contributionFiles, start, finish, reportFileName);\n }\n}",
"score": 82.38651456038761
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/FdcFilesService.java",
"retrieved_chunk": " private final FdcFileMapper fdcFileMapper;\n @Retry(name = SERVICE_NAME)\n public List<String> getFiles(LocalDate start, LocalDate end) {\n if (end.isBefore(start)) {\n String message = String.format(\"invalid time range %s is before %s\", end, start);\n throw new MaatApiClientException(message);\n }\n log.info(\"Start - call MAAT API to collect FDC files, between {} and {}\", start, end);\n return fdcFilesClient.getContributions(start, end);\n }",
"score": 70.69355628860015
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/DcesReportService.java",
"retrieved_chunk": "package uk.gov.justice.laa.crime.dces.report.service;\nimport jakarta.xml.bind.JAXBException;\nimport java.io.File;\nimport java.io.IOException;\nimport java.time.LocalDate;\npublic interface DcesReportService {\n File getContributionsReport(LocalDate start, LocalDate end) throws JAXBException, IOException;\n File getFdcReport(LocalDate start, LocalDate end) throws JAXBException, IOException;\n}",
"score": 64.64418200392296
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/FdcFilesService.java",
"retrieved_chunk": " public File processFiles(List<String> files, LocalDate start, LocalDate finish) throws JAXBException, IOException {\n return fdcFileMapper.processRequest(files.toArray(new String[0]), getFileName(start, finish));\n }\n public String getFileName(LocalDate start, LocalDate finish) {\n return String.format(FILE_NAME_TEMPLATE, start, finish);\n }\n}",
"score": 53.03433595362914
},
{
"filename": "dces-report-service/src/main/java/uk/gov/justice/laa/crime/dces/report/service/ContributionFilesService.java",
"retrieved_chunk": " @Retry(name = SERVICE_NAME)\n public List<String> getFiles(LocalDate start, LocalDate finish) {\n log.info(\"Start - call MAAT API to collect contribution files date between {} and {}\", start.toString(), finish.toString());\n return contributionFilesClient.getContributions(start, finish);\n }\n public File processFiles(List<String> files, LocalDate start, LocalDate finish, String fileName) throws JAXBException, IOException {\n return contributionFilesMapper.processRequest(files.toArray(new String[0]), start, finish, fileName);\n }\n public String getFileName(LocalDate start, LocalDate finish) {\n return String.format(FILE_NAME_TEMPLATE, start, finish);",
"score": 49.83482091557874
}
] | java | return fdcFilesService.processFiles(contributionFiles, start, end); |
package com.minivv.pilot;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.minivv.pilot.model.AppSettings;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.ui.AppPluginSettingsPage;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class AppConfigurable implements Configurable {
private AppPluginSettingsPage form;
private AppSettings state;
private AppSettingsStorage appSettingsStorage;
public AppConfigurable() {
appSettingsStorage = AppSettingsStorage.getInstance();
state = appSettingsStorage.getState();
}
@Nls(capitalization = Nls.Capitalization.Title)
@Override
public String getDisplayName() {
return "gpt-copilot";
}
@Override
public @Nullable JComponent createComponent() {
form = new AppPluginSettingsPage(state);
return form.getRootPane();
}
@Override
public boolean isModified() {
return form != null && form.isSettingsModified(state);
}
@Override
public void apply() throws ConfigurationException {
appSettingsStorage.unregisterActions();
state = form.getSettings().clone();
appSettingsStorage.loadState(state);
appSettingsStorage.registerActions();
}
@Override
public void reset() {
if (form != null) {
form.importForm(state);
}
}
@Override
public void disposeUIResources() {
form = null;
}
@Override
public @Nullable JComponent getPreferredFocusedComponent() {
return | form.getGptKey(); |
}
public AppSettingsStorage getAppSettingsStorage() {
return appSettingsStorage;
}
}
| src/main/java/com/minivv/pilot/AppConfigurable.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": "public abstract class BasePilotPluginAction extends AnAction {\n// private final int index;\n// public BasePilotPluginAction(@Nullable @NlsActions.ActionText String text,int index) {\n// super(text);\n// this.index = index;\n// }\n public BasePilotPluginAction(@Nullable @NlsActions.ActionText String text) {\n super(text);\n }\n @Override",
"score": 10.109459617895958
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " private AppSettings settings = new AppSettings();\n private final String idPrefix = \"chatGptPilot_\";\n private final DefaultActionGroup actionGroup = new DefaultActionGroup(\"gpt pilot\", true);\n @Nullable\n @Override\n public AppSettings getState() {\n if (settings == null) {\n settings = new AppSettings();\n }\n return settings;",
"score": 9.613949788599784
},
{
"filename": "src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java",
"retrieved_chunk": " !testConnMsg.getText().equals(state.testConnMsg);\n }\n public JPanel getRootPane() {\n return rootPane;\n }\n public JTextField getGptKey() {\n return gptKey;\n }\n}",
"score": 8.895399676324104
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " return \"Snippet\";\n }\n return null;\n }\n @Override\n public boolean isCellEditable(int rowIndex, int columnIndex) {\n return true;\n }\n }\n}",
"score": 8.608657369989402
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n @Override\n public int getRowCount() {\n return prompts.size();\n }\n @Override\n public Class getColumnClass(int columnIndex) {\n return String.class;\n }\n @Override",
"score": 8.512193865724054
}
] | java | form.getGptKey(); |
package com.minivv.pilot.model;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.annotations.Transient;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.constants.SysConstants;
import com.rits.cloning.Cloner;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public class AppSettings extends DomainObject implements Cloneable {
public boolean enableProxy = false;
public String proxyHost = "127.0.0.1";
public int proxyPort = 1087;
public String proxyType = SysConstants.httpProxyType;
public String gptKey;
public String gptModel = "text-davinci-003";
public int gptMaxTokens = 2048;
public int maxWaitSeconds = 60;
public boolean isReplace = false;
public String testConnMsg = SysConstants.testConnMsg;
public Prompts prompts = new Prompts();
public AppSettings() {
this.addDefaultPrompts(this.prompts);
}
@NotNull
public static Project getProject() {
return AppSettingsStorage.getProject();
}
@NotNull
public static AppSettings get() {
AppSettingsStorage instance = AppSettingsStorage.getInstance();
return instance.getState();
}
@Override
public AppSettings clone() {
Cloner cloner = new Cloner();
cloner.nullInsteadOfClone();
return cloner.deepClone(this);
}
public static void resetDefaultPrompts(List<Prompt> _prompts) {
Prompts prompts = addDefaultPrompts(new Prompts());
Map<String, String> stringStringMap = prompts.asMap();
_prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));
_prompts.addAll(prompts.getPrompts());
}
@Transient
public static Prompts addDefaultPrompts(Prompts prompts) {
prompts. | add(Prompt.of("Readable", "help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{ | query}"));
prompts.add(Prompt.of("List Steps", "help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("Explain", "帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("步骤注释", "帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("emptyForYou", "balabala{query}"));
return prompts;
}
} | src/main/java/com/minivv/pilot/model/AppSettings.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "package com.minivv.pilot.model;\nimport java.util.*;\npublic class Prompts extends DomainObject {\n private List<Prompt> prompts = new ArrayList<>();\n public Prompts() {\n }\n public Prompts(List<Prompt> prompts) {\n this.prompts = prompts;\n }\n public List<Prompt> getPrompts() {",
"score": 44.85153769710917
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n }\n public void reset(AppSettings settings) {\n obtainPrompts(prompts, settings);\n promptTableModel.fireTableDataChanged();\n }\n public boolean isModified(AppSettings settings) {\n final ArrayList<Prompt> _prompts = new ArrayList<>();\n obtainPrompts(_prompts, settings);\n return !_prompts.equals(prompts);",
"score": 37.2432422506434
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " }\n return prompts.add(o);\n }\n public int size() {\n return prompts.size();\n }\n public Map<String, String> asMap() {\n HashMap<String, String> stringStringHashMap = new HashMap<>();\n for (Prompt prompt : prompts) {\n stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());",
"score": 35.840055677228165
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "//\t\tthis.index = index;\n//\t}\n//\tpublic static Prompt of(String name, String value,int index) {\n//\t\treturn new Prompt(name, value,index);\n//\t}\n\tpublic Prompt(String option, String snippet) {\n\t\tthis.option = option;\n\t\tthis.snippet = snippet;\n\t}\n\tpublic static Prompt of(String name, String value) {",
"score": 35.7819258293419
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 30.170220025813265
}
] | java | add(Prompt.of("Readable", "help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{ |
package com.minivv.pilot.model;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.annotations.Transient;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.constants.SysConstants;
import com.rits.cloning.Cloner;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public class AppSettings extends DomainObject implements Cloneable {
public boolean enableProxy = false;
public String proxyHost = "127.0.0.1";
public int proxyPort = 1087;
public String proxyType = SysConstants.httpProxyType;
public String gptKey;
public String gptModel = "text-davinci-003";
public int gptMaxTokens = 2048;
public int maxWaitSeconds = 60;
public boolean isReplace = false;
public String testConnMsg = SysConstants.testConnMsg;
public Prompts prompts = new Prompts();
public AppSettings() {
this.addDefaultPrompts(this.prompts);
}
@NotNull
public static Project getProject() {
return AppSettingsStorage.getProject();
}
@NotNull
public static AppSettings get() {
AppSettingsStorage instance = AppSettingsStorage.getInstance();
return instance.getState();
}
@Override
public AppSettings clone() {
Cloner cloner = new Cloner();
cloner.nullInsteadOfClone();
return cloner.deepClone(this);
}
public static void resetDefaultPrompts(List<Prompt> _prompts) {
Prompts prompts = addDefaultPrompts(new Prompts());
Map<String, String> stringStringMap = prompts.asMap();
_prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));
_prompts.addAll(prompts.getPrompts());
}
@Transient
public static Prompts addDefaultPrompts(Prompts prompts) {
prompts.add(Prompt.of("Readable", "help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts | .add(Prompt.of("List Steps", "help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{ | query}"));
prompts.add(Prompt.of("Explain", "帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("步骤注释", "帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("emptyForYou", "balabala{query}"));
return prompts;
}
} | src/main/java/com/minivv/pilot/model/AppSettings.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "//\t\tthis.index = index;\n//\t}\n//\tpublic static Prompt of(String name, String value,int index) {\n//\t\treturn new Prompt(name, value,index);\n//\t}\n\tpublic Prompt(String option, String snippet) {\n\t\tthis.option = option;\n\t\tthis.snippet = snippet;\n\t}\n\tpublic static Prompt of(String name, String value) {",
"score": 51.841965258836744
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " @Override\n public String addStatement(String code) {\n return prompt.getSnippet().replace(\"{query}\", code);\n }\n };\n actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);\n actionGroup.add(oldAction);\n }\n popupMenu.add(actionGroup);\n }",
"score": 46.07915960502377
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "package com.minivv.pilot.model;\nimport java.util.*;\npublic class Prompts extends DomainObject {\n private List<Prompt> prompts = new ArrayList<>();\n public Prompts() {\n }\n public Prompts(List<Prompt> prompts) {\n this.prompts = prompts;\n }\n public List<Prompt> getPrompts() {",
"score": 45.53934269072988
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " }\n return prompts.add(o);\n }\n public int size() {\n return prompts.size();\n }\n public Map<String, String> asMap() {\n HashMap<String, String> stringStringHashMap = new HashMap<>();\n for (Prompt prompt : prompts) {\n stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());",
"score": 44.143267146795395
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// @Override\n// public String addStatement(String code) {\n// return prompt.getSnippet().replace(\"{query}\", code);\n// }\n// };\n// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);\n// actionGroup.add(newAction);\n// }\n// ((DefaultActionGroup) popupMenu).add(actionGroup);\n// }",
"score": 43.05830569225495
}
] | java | .add(Prompt.of("List Steps", "help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{ |
package com.minivv.pilot.model;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.annotations.Transient;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.constants.SysConstants;
import com.rits.cloning.Cloner;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public class AppSettings extends DomainObject implements Cloneable {
public boolean enableProxy = false;
public String proxyHost = "127.0.0.1";
public int proxyPort = 1087;
public String proxyType = SysConstants.httpProxyType;
public String gptKey;
public String gptModel = "text-davinci-003";
public int gptMaxTokens = 2048;
public int maxWaitSeconds = 60;
public boolean isReplace = false;
public String testConnMsg = SysConstants.testConnMsg;
public Prompts prompts = new Prompts();
public AppSettings() {
this.addDefaultPrompts(this.prompts);
}
@NotNull
public static Project getProject() {
return AppSettingsStorage.getProject();
}
@NotNull
public static AppSettings get() {
AppSettingsStorage instance = AppSettingsStorage.getInstance();
return instance.getState();
}
@Override
public AppSettings clone() {
Cloner cloner = new Cloner();
cloner.nullInsteadOfClone();
return cloner.deepClone(this);
}
public static void resetDefaultPrompts(List<Prompt> _prompts) {
Prompts prompts = addDefaultPrompts(new Prompts());
Map<String, String> stringStringMap = prompts.asMap();
_prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));
_prompts.addAll(prompts.getPrompts());
}
@Transient
public static Prompts addDefaultPrompts(Prompts prompts) {
prompts.add(Prompt.of("Readable", "help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("List Steps", "help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts | .add(Prompt.of("Explain", "帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{ | query}"));
prompts.add(Prompt.of("步骤注释", "帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("emptyForYou", "balabala{query}"));
return prompts;
}
} | src/main/java/com/minivv/pilot/model/AppSettings.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "//\t\tthis.index = index;\n//\t}\n//\tpublic static Prompt of(String name, String value,int index) {\n//\t\treturn new Prompt(name, value,index);\n//\t}\n\tpublic Prompt(String option, String snippet) {\n\t\tthis.option = option;\n\t\tthis.snippet = snippet;\n\t}\n\tpublic static Prompt of(String name, String value) {",
"score": 58.33072299604625
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " @Override\n public String addStatement(String code) {\n return prompt.getSnippet().replace(\"{query}\", code);\n }\n };\n actionManager.registerAction(idPrefix + prompt.getOption(), oldAction);\n actionGroup.add(oldAction);\n }\n popupMenu.add(actionGroup);\n }",
"score": 53.02983886636198
},
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": "// @Override\n// public String addStatement(String code) {\n// return prompt.getSnippet().replace(\"{query}\", code);\n// }\n// };\n// actionManager.registerAction(idPrefix + prompt.getIndex(), newAction);\n// actionGroup.add(newAction);\n// }\n// ((DefaultActionGroup) popupMenu).add(actionGroup);\n// }",
"score": 49.91990795668526
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " }\n return prompts.add(o);\n }\n public int size() {\n return prompts.size();\n }\n public Map<String, String> asMap() {\n HashMap<String, String> stringStringHashMap = new HashMap<>();\n for (Prompt prompt : prompts) {\n stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());",
"score": 46.90662610945309
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "// }\n// public void add(String s, String to,int index) {\n// prompts.add(new Prompt(s, to,index));\n// }\n public void add(String s, String to) {\n prompts.add(new Prompt(s, to));\n }\n public boolean add(Prompt o) {\n if (prompts.stream().anyMatch(prompt -> prompt.getOption().equals(o.getOption()))) {\n return false;",
"score": 46.51000365368302
}
] | java | .add(Prompt.of("Explain", "帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{ |
package com.minivv.pilot.ui;
import com.intellij.icons.AllIcons;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.ui.AnActionButton;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.AnActionLink;
import com.minivv.pilot.constants.SysConstants;
import com.minivv.pilot.model.AppSettings;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.Prompts;
import com.minivv.pilot.utils.ActionLinkUtils;
import com.minivv.pilot.utils.Donate;
import com.minivv.pilot.utils.GPTClient;
import com.minivv.pilot.utils.NotifyUtils;
import com.theokanning.openai.completion.CompletionChoice;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Objects;
/**
* todo 超时时间配置
* todo 更换NotifyUtils
* todo 限制代码量
*/
public class AppPluginSettingsPage {
private JPanel rootPane;
private JTextField gptKey;
private JTextField gptModel;
private JSpinner gptMaxToken;
private JCheckBox isReplace;
private JRadioButton enableProxy;
private JRadioButton httpProxy;
private JRadioButton socketProxy;
private JTextField proxyHost;
private JSpinner proxyPort;
private AnActionLink gptKeyLink;
private AnActionLink gptModelsLink;
private AnActionLink gptUsageLink;
private JTextField testConnMsg;
private JButton testConnButton;
private JPanel promptsPane;
private JSpinner maxWaitSeconds;
private JButton donatePaypal;
private JButton donateWx;
// private JPanel locale;
private AppSettings settings;
private final PromptsTable promptsTable;
public AppPluginSettingsPage(AppSettings original) {
this.settings = original.clone();
this.promptsTable = new PromptsTable();
promptsPane.add(ToolbarDecorator.createDecorator(promptsTable)
.setRemoveAction(button -> promptsTable.removeSelectedPrompts())
.setAddAction(button -> promptsTable.addPrompt(Prompt.of("Option" + promptsTable.getRowCount(), "Snippet:{query}")))
.addExtraAction(new AnActionButton("Reset Default Prompts", AllIcons.Actions.Rollback) {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
promptsTable.resetDefaultAliases();
}
})
.createPanel());
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent e) {
return promptsTable.editPrompt();
}
}.installOn(promptsTable);
// ComboBox<Locale> comboBox = new ComboBox<>();
// Locale[] locales = Locale.getAvailableLocales();
// for (Locale locale : locales) {
// comboBox.addItem(locale);
// }
// locale.add(comboBox);
Donate.initUrl(donatePaypal, "https://www.paypal.me/kuweiguge");
// Donate.initImage(donateWx,"images/wechat_donate.png");
}
private void createUIComponents() {
gptMaxToken = new JSpinner(new SpinnerNumberModel(2048, 128, 2048, 128));
proxyPort = new JSpinner(new SpinnerNumberModel(1087, 1, 65535, 1));
maxWaitSeconds = new JSpinner(new SpinnerNumberModel(60, 5, 600, 5));
gptKeyLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/api-keys");
gptModelsLink = ActionLinkUtils.newActionLink("https://platform.openai.com/docs/models/overview");
gptUsageLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/usage");
}
public AppSettings getSettings() {
promptsTable.commit(settings);
getData(settings);
return settings;
}
private void getData(AppSettings settings) {
settings.gptKey = gptKey.getText();
settings.gptModel = gptModel.getText();
settings.gptMaxTokens = (int) gptMaxToken.getValue();
settings.isReplace = isReplace.isSelected();
settings.enableProxy = enableProxy.isSelected();
settings.proxyHost = proxyHost.getText();
settings.proxyPort = (int) proxyPort.getValue();
settings.maxWaitSeconds = (int) maxWaitSeconds.getValue();
settings.proxyType = httpProxy.isSelected() ? SysConstants.httpProxyType : SysConstants.socketProxyType;
settings.testConnMsg = testConnMsg.getText();
settings.prompts = new Prompts(promptsTable.prompts);
}
public void importForm(AppSettings state) {
this.settings = state.clone();
setData(settings);
promptsTable.reset(settings);
}
private void setData(AppSettings settings) {
gptKey.setText(settings.gptKey);
gptModel.setText(settings.gptModel);
gptMaxToken.setValue(settings.gptMaxTokens);
isReplace.setSelected(settings.isReplace);
testConnMsg.setText(settings.testConnMsg);
httpProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.httpProxyType));
socketProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.socketProxyType));
proxyHost.setText(settings.proxyHost);
proxyPort.setValue(settings.proxyPort);
maxWaitSeconds.setValue(settings.maxWaitSeconds);
enableProxy.addChangeListener(e -> {
if (enableProxy.isSelected()) {
httpProxy.setEnabled(true);
socketProxy.setEnabled(true);
proxyHost.setEnabled(true);
proxyPort.setEnabled(true);
} else {
httpProxy.setEnabled(false);
socketProxy.setEnabled(false);
proxyHost.setEnabled(false);
proxyPort.setEnabled(false);
}
});
httpProxy.addChangeListener(e -> {
socketProxy.setSelected(!httpProxy.isSelected());
});
socketProxy.addChangeListener(e -> {
httpProxy.setSelected(!socketProxy.isSelected());
});
enableProxy.setSelected(settings.enableProxy);
testConnButton.addActionListener(e -> {
String msg = StringUtils.isBlank(testConnMsg.getText()) ? SysConstants.testConnMsg : testConnMsg.getText();
boolean hasError = checkSettings();
if (hasError) {
return;
}
List<CompletionChoice> choices = GPTClient.callChatGPT(msg, settings);
if (GPTClient.isSuccessful(choices)) {
NotifyUtils.notifyMessage(AppSettings.getProject(), "Test connection successfully!ChatGPT answer:" + GPTClient.toString(choices), NotificationType.INFORMATION);
} else {
NotifyUtils.notifyMessage | (AppSettings.getProject(), "Test connection failed!", NotificationType.ERROR); |
}
});
}
/**
* 保存设置
*
* @return 是否有错误
*/
private boolean checkSettings() {
StringBuilder error = new StringBuilder();
if (StringUtils.isBlank(gptKey.getText())) {
error.append("GPT Key is required.").append("\n");
}
if (StringUtils.isBlank(gptModel.getText())) {
error.append("GPT Model is required.").append("\n");
}
if (gptMaxToken.getValue() == null || (int) gptMaxToken.getValue() <= 0 || (int) gptMaxToken.getValue() > 2048) {
error.append("GPT Max Token is required and should be between 1 and 2048.").append("\n");
}
if (enableProxy.isSelected()) {
if (StringUtils.isBlank(proxyHost.getText())) {
error.append("Proxy Host is required.").append("\n");
}
if (proxyPort.getValue() == null || (int) proxyPort.getValue() <= 0 || (int) proxyPort.getValue() > 65535) {
error.append("Proxy Port is required and should be between 1 and 65535.").append("\n");
}
if (maxWaitSeconds.getValue() == null || (int) maxWaitSeconds.getValue() <= 0 || (int) maxWaitSeconds.getValue() > 600) {
error.append("Max Wait Seconds is required and should be between 5 and 600.").append("\n");
}
}
if (promptsTable.getRowCount() <= 0) {
error.append("Prompts is required.").append("\n");
}
if (promptsTable.prompts.stream().anyMatch(p -> !StringUtils.contains(p.getSnippet(), "{query}"))) {
error.append("Prompts should contain {query}.").append("\n");
}
if (StringUtils.isNotBlank(error)) {
NotifyUtils.notifyMessage(AppSettings.getProject(), error.toString(), NotificationType.ERROR);
return true;
} else {
return false;
}
}
public boolean isSettingsModified(AppSettings state) {
if (promptsTable.isModified(state)) return true;
return !this.settings.equals(state) || isModified(state);
}
private boolean isModified(AppSettings state) {
return !gptKey.getText().equals(state.gptKey) ||
!gptModel.getText().equals(state.gptModel) ||
!gptMaxToken.getValue().equals(state.gptMaxTokens) ||
isReplace.isSelected() != state.isReplace ||
enableProxy.isSelected() != state.enableProxy ||
!proxyHost.getText().equals(state.proxyHost) ||
!proxyPort.getValue().equals(state.proxyPort) ||
!maxWaitSeconds.getValue().equals(state.maxWaitSeconds) ||
!httpProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.httpProxyType) ||
!socketProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.socketProxyType) ||
!testConnMsg.getText().equals(state.testConnMsg);
}
public JPanel getRootPane() {
return rootPane;
}
public JTextField getGptKey() {
return gptKey;
}
}
| src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": " if(GPTClient.isSuccessful(choices)){\n optimizedCode = GPTClient.toString(choices);\n } else {\n NotifyUtils.notifyMessage(project,\"gpt-copilot connection failed, please check!\", NotificationType.ERROR);\n return;\n }\n //处理readable操作\n ApplicationManager.getApplication().runWriteAction(() -> {\n CommandProcessor.getInstance().executeCommand(\n project,",
"score": 69.30676780724659
},
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": " doCommand(statement, editor, project);\n }\n private void doCommand(String statement, Editor editor, Project project) {\n AppSettings settings = AppSettingsStorage.getInstance().getState();\n if(settings == null){\n NotifyUtils.notifyMessage(project,\"gpt-copilot settings is null, please check!\", NotificationType.ERROR);\n return;\n }\n List<CompletionChoice> choices = GPTClient.callChatGPT(statement, settings);\n String optimizedCode;",
"score": 44.562460957891794
},
{
"filename": "src/main/java/com/minivv/pilot/utils/GPTClient.java",
"retrieved_chunk": " } catch (Exception e) {\n return new ArrayList<>();\n }\n }\n public static boolean isSuccessful(List<CompletionChoice> choices) {\n return CollectionUtils.isNotEmpty(choices) && !choices.get(0).getText().isBlank();\n }\n public static String toString(List<CompletionChoice> choices) {\n if (CollectionUtils.isEmpty(choices)) {\n return \"ChatGPT response is empty,please check your network or config!\";",
"score": 33.079777595306226
},
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": " if (editor == null) {\n return;\n }\n // 获取用户选中的代码片段\n String code = editor.getSelectionModel().getSelectedText();\n if (code == null || code.isEmpty()) {\n return;\n }\n String statement = addStatement(code);\n NotifyUtils.notifyMessage(project,\"sending code to gpt..\", NotificationType.INFORMATION);",
"score": 22.48362637060009
},
{
"filename": "src/main/java/com/minivv/pilot/utils/GPTClient.java",
"retrieved_chunk": "import java.net.Proxy;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport static com.theokanning.openai.service.OpenAiService.*;\npublic class GPTClient {\n public static List<CompletionChoice> callChatGPT(String code, AppSettings settings) {\n try {\n Locale.setDefault(Locale.getDefault());",
"score": 18.435400132784434
}
] | java | (AppSettings.getProject(), "Test connection failed!", NotificationType.ERROR); |
package com.minivv.pilot.model;
import com.intellij.openapi.project.Project;
import com.intellij.util.xmlb.annotations.Transient;
import com.minivv.pilot.state.AppSettingsStorage;
import com.minivv.pilot.constants.SysConstants;
import com.rits.cloning.Cloner;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
public class AppSettings extends DomainObject implements Cloneable {
public boolean enableProxy = false;
public String proxyHost = "127.0.0.1";
public int proxyPort = 1087;
public String proxyType = SysConstants.httpProxyType;
public String gptKey;
public String gptModel = "text-davinci-003";
public int gptMaxTokens = 2048;
public int maxWaitSeconds = 60;
public boolean isReplace = false;
public String testConnMsg = SysConstants.testConnMsg;
public Prompts prompts = new Prompts();
public AppSettings() {
this.addDefaultPrompts(this.prompts);
}
@NotNull
public static Project getProject() {
return AppSettingsStorage.getProject();
}
@NotNull
public static AppSettings get() {
AppSettingsStorage instance = AppSettingsStorage.getInstance();
return instance.getState();
}
@Override
public AppSettings clone() {
Cloner cloner = new Cloner();
cloner.nullInsteadOfClone();
return cloner.deepClone(this);
}
public static void resetDefaultPrompts(List<Prompt> _prompts) {
Prompts prompts = addDefaultPrompts(new Prompts());
Map< | String, String> stringStringMap = prompts.asMap(); |
_prompts.removeIf(next -> stringStringMap.containsKey(next.getOption()));
_prompts.addAll(prompts.getPrompts());
}
@Transient
public static Prompts addDefaultPrompts(Prompts prompts) {
prompts.add(Prompt.of("Readable", "help me enhance the readability of the following code snippet, without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("List Steps", "help me add comments to the key steps of the following code snippet and return the optimized code with comments. without adding any additional information except for the optimized code. Here is the code snippet:{query}"));
prompts.add(Prompt.of("Explain", "帮我增强下面一段代码的可读性吧,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("步骤注释", "帮我给下面一段代码的关键步骤添加注释,返回优化后的完整代码,除了优化后的代码,不要添加任何其他信息,这是代码片段:{query}"));
prompts.add(Prompt.of("emptyForYou", "balabala{query}"));
return prompts;
}
} | src/main/java/com/minivv/pilot/model/AppSettings.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": "package com.minivv.pilot.model;\nimport java.util.*;\npublic class Prompts extends DomainObject {\n private List<Prompt> prompts = new ArrayList<>();\n public Prompts() {\n }\n public Prompts(List<Prompt> prompts) {\n this.prompts = prompts;\n }\n public List<Prompt> getPrompts() {",
"score": 26.03640907498563
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompts.java",
"retrieved_chunk": " }\n return prompts.add(o);\n }\n public int size() {\n return prompts.size();\n }\n public Map<String, String> asMap() {\n HashMap<String, String> stringStringHashMap = new HashMap<>();\n for (Prompt prompt : prompts) {\n stringStringHashMap.put(prompt.getOption(), prompt.getSnippet());",
"score": 22.12442746839401
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n }\n public void reset(AppSettings settings) {\n obtainPrompts(prompts, settings);\n promptTableModel.fireTableDataChanged();\n }\n public boolean isModified(AppSettings settings) {\n final ArrayList<Prompt> _prompts = new ArrayList<>();\n obtainPrompts(_prompts, settings);\n return !_prompts.equals(prompts);",
"score": 18.962705148690596
},
{
"filename": "src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java",
"retrieved_chunk": " settings.maxWaitSeconds = (int) maxWaitSeconds.getValue();\n settings.proxyType = httpProxy.isSelected() ? SysConstants.httpProxyType : SysConstants.socketProxyType;\n settings.testConnMsg = testConnMsg.getText();\n settings.prompts = new Prompts(promptsTable.prompts);\n }\n public void importForm(AppSettings state) {\n this.settings = state.clone();\n setData(settings);\n promptsTable.reset(settings);\n }",
"score": 18.188932578670844
},
{
"filename": "src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java",
"retrieved_chunk": " private final PromptsTable promptsTable;\n public AppPluginSettingsPage(AppSettings original) {\n this.settings = original.clone();\n this.promptsTable = new PromptsTable();\n promptsPane.add(ToolbarDecorator.createDecorator(promptsTable)\n .setRemoveAction(button -> promptsTable.removeSelectedPrompts())\n .setAddAction(button -> promptsTable.addPrompt(Prompt.of(\"Option\" + promptsTable.getRowCount(), \"Snippet:{query}\")))\n .addExtraAction(new AnActionButton(\"Reset Default Prompts\", AllIcons.Actions.Rollback) {\n @Override\n public void actionPerformed(@NotNull AnActionEvent e) {",
"score": 16.434424110004862
}
] | java | String, String> stringStringMap = prompts.asMap(); |
package com.minivv.pilot.ui;
import com.intellij.icons.AllIcons;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.ui.AnActionButton;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.AnActionLink;
import com.minivv.pilot.constants.SysConstants;
import com.minivv.pilot.model.AppSettings;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.Prompts;
import com.minivv.pilot.utils.ActionLinkUtils;
import com.minivv.pilot.utils.Donate;
import com.minivv.pilot.utils.GPTClient;
import com.minivv.pilot.utils.NotifyUtils;
import com.theokanning.openai.completion.CompletionChoice;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Objects;
/**
* todo 超时时间配置
* todo 更换NotifyUtils
* todo 限制代码量
*/
public class AppPluginSettingsPage {
private JPanel rootPane;
private JTextField gptKey;
private JTextField gptModel;
private JSpinner gptMaxToken;
private JCheckBox isReplace;
private JRadioButton enableProxy;
private JRadioButton httpProxy;
private JRadioButton socketProxy;
private JTextField proxyHost;
private JSpinner proxyPort;
private AnActionLink gptKeyLink;
private AnActionLink gptModelsLink;
private AnActionLink gptUsageLink;
private JTextField testConnMsg;
private JButton testConnButton;
private JPanel promptsPane;
private JSpinner maxWaitSeconds;
private JButton donatePaypal;
private JButton donateWx;
// private JPanel locale;
private AppSettings settings;
private final PromptsTable promptsTable;
public AppPluginSettingsPage(AppSettings original) {
this.settings = original.clone();
this.promptsTable = new PromptsTable();
promptsPane.add(ToolbarDecorator.createDecorator(promptsTable)
.setRemoveAction(button -> promptsTable.removeSelectedPrompts())
.setAddAction(button -> promptsTable.addPrompt(Prompt.of("Option" + promptsTable.getRowCount(), "Snippet:{query}")))
.addExtraAction(new AnActionButton("Reset Default Prompts", AllIcons.Actions.Rollback) {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
promptsTable.resetDefaultAliases();
}
})
.createPanel());
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent e) {
return promptsTable.editPrompt();
}
}.installOn(promptsTable);
// ComboBox<Locale> comboBox = new ComboBox<>();
// Locale[] locales = Locale.getAvailableLocales();
// for (Locale locale : locales) {
// comboBox.addItem(locale);
// }
// locale.add(comboBox);
Donate.initUrl(donatePaypal, "https://www.paypal.me/kuweiguge");
// Donate.initImage(donateWx,"images/wechat_donate.png");
}
private void createUIComponents() {
gptMaxToken = new JSpinner(new SpinnerNumberModel(2048, 128, 2048, 128));
proxyPort = new JSpinner(new SpinnerNumberModel(1087, 1, 65535, 1));
maxWaitSeconds = new JSpinner(new SpinnerNumberModel(60, 5, 600, 5));
| gptKeyLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/api-keys"); |
gptModelsLink = ActionLinkUtils.newActionLink("https://platform.openai.com/docs/models/overview");
gptUsageLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/usage");
}
public AppSettings getSettings() {
promptsTable.commit(settings);
getData(settings);
return settings;
}
private void getData(AppSettings settings) {
settings.gptKey = gptKey.getText();
settings.gptModel = gptModel.getText();
settings.gptMaxTokens = (int) gptMaxToken.getValue();
settings.isReplace = isReplace.isSelected();
settings.enableProxy = enableProxy.isSelected();
settings.proxyHost = proxyHost.getText();
settings.proxyPort = (int) proxyPort.getValue();
settings.maxWaitSeconds = (int) maxWaitSeconds.getValue();
settings.proxyType = httpProxy.isSelected() ? SysConstants.httpProxyType : SysConstants.socketProxyType;
settings.testConnMsg = testConnMsg.getText();
settings.prompts = new Prompts(promptsTable.prompts);
}
public void importForm(AppSettings state) {
this.settings = state.clone();
setData(settings);
promptsTable.reset(settings);
}
private void setData(AppSettings settings) {
gptKey.setText(settings.gptKey);
gptModel.setText(settings.gptModel);
gptMaxToken.setValue(settings.gptMaxTokens);
isReplace.setSelected(settings.isReplace);
testConnMsg.setText(settings.testConnMsg);
httpProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.httpProxyType));
socketProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.socketProxyType));
proxyHost.setText(settings.proxyHost);
proxyPort.setValue(settings.proxyPort);
maxWaitSeconds.setValue(settings.maxWaitSeconds);
enableProxy.addChangeListener(e -> {
if (enableProxy.isSelected()) {
httpProxy.setEnabled(true);
socketProxy.setEnabled(true);
proxyHost.setEnabled(true);
proxyPort.setEnabled(true);
} else {
httpProxy.setEnabled(false);
socketProxy.setEnabled(false);
proxyHost.setEnabled(false);
proxyPort.setEnabled(false);
}
});
httpProxy.addChangeListener(e -> {
socketProxy.setSelected(!httpProxy.isSelected());
});
socketProxy.addChangeListener(e -> {
httpProxy.setSelected(!socketProxy.isSelected());
});
enableProxy.setSelected(settings.enableProxy);
testConnButton.addActionListener(e -> {
String msg = StringUtils.isBlank(testConnMsg.getText()) ? SysConstants.testConnMsg : testConnMsg.getText();
boolean hasError = checkSettings();
if (hasError) {
return;
}
List<CompletionChoice> choices = GPTClient.callChatGPT(msg, settings);
if (GPTClient.isSuccessful(choices)) {
NotifyUtils.notifyMessage(AppSettings.getProject(), "Test connection successfully!ChatGPT answer:" + GPTClient.toString(choices), NotificationType.INFORMATION);
} else {
NotifyUtils.notifyMessage(AppSettings.getProject(), "Test connection failed!", NotificationType.ERROR);
}
});
}
/**
* 保存设置
*
* @return 是否有错误
*/
private boolean checkSettings() {
StringBuilder error = new StringBuilder();
if (StringUtils.isBlank(gptKey.getText())) {
error.append("GPT Key is required.").append("\n");
}
if (StringUtils.isBlank(gptModel.getText())) {
error.append("GPT Model is required.").append("\n");
}
if (gptMaxToken.getValue() == null || (int) gptMaxToken.getValue() <= 0 || (int) gptMaxToken.getValue() > 2048) {
error.append("GPT Max Token is required and should be between 1 and 2048.").append("\n");
}
if (enableProxy.isSelected()) {
if (StringUtils.isBlank(proxyHost.getText())) {
error.append("Proxy Host is required.").append("\n");
}
if (proxyPort.getValue() == null || (int) proxyPort.getValue() <= 0 || (int) proxyPort.getValue() > 65535) {
error.append("Proxy Port is required and should be between 1 and 65535.").append("\n");
}
if (maxWaitSeconds.getValue() == null || (int) maxWaitSeconds.getValue() <= 0 || (int) maxWaitSeconds.getValue() > 600) {
error.append("Max Wait Seconds is required and should be between 5 and 600.").append("\n");
}
}
if (promptsTable.getRowCount() <= 0) {
error.append("Prompts is required.").append("\n");
}
if (promptsTable.prompts.stream().anyMatch(p -> !StringUtils.contains(p.getSnippet(), "{query}"))) {
error.append("Prompts should contain {query}.").append("\n");
}
if (StringUtils.isNotBlank(error)) {
NotifyUtils.notifyMessage(AppSettings.getProject(), error.toString(), NotificationType.ERROR);
return true;
} else {
return false;
}
}
public boolean isSettingsModified(AppSettings state) {
if (promptsTable.isModified(state)) return true;
return !this.settings.equals(state) || isModified(state);
}
private boolean isModified(AppSettings state) {
return !gptKey.getText().equals(state.gptKey) ||
!gptModel.getText().equals(state.gptModel) ||
!gptMaxToken.getValue().equals(state.gptMaxTokens) ||
isReplace.isSelected() != state.isReplace ||
enableProxy.isSelected() != state.enableProxy ||
!proxyHost.getText().equals(state.proxyHost) ||
!proxyPort.getValue().equals(state.proxyPort) ||
!maxWaitSeconds.getValue().equals(state.maxWaitSeconds) ||
!httpProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.httpProxyType) ||
!socketProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.socketProxyType) ||
!testConnMsg.getText().equals(state.testConnMsg);
}
public JPanel getRootPane() {
return rootPane;
}
public JTextField getGptKey() {
return gptKey;
}
}
| src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/model/AppSettings.java",
"retrieved_chunk": " public boolean enableProxy = false;\n public String proxyHost = \"127.0.0.1\";\n public int proxyPort = 1087;\n public String proxyType = SysConstants.httpProxyType;\n public String gptKey;\n public String gptModel = \"text-davinci-003\";\n public int gptMaxTokens = 2048;\n public int maxWaitSeconds = 60;\n public boolean isReplace = false;\n public String testConnMsg = SysConstants.testConnMsg;",
"score": 23.157002097574438
},
{
"filename": "src/main/java/com/minivv/pilot/utils/GPTClient.java",
"retrieved_chunk": " if (settings.enableProxy) {\n Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(settings.proxyHost, settings.proxyPort));\n OkHttpClient client = defaultClient(settings.gptKey, Duration.ofSeconds(settings.maxWaitSeconds))\n .newBuilder()\n .proxy(proxy)\n .build();\n Retrofit retrofit = defaultRetrofit(client, defaultObjectMapper());\n OpenAiApi api = retrofit.create(OpenAiApi.class);\n OpenAiService service = new OpenAiService(api);\n CompletionRequest completionRequest = CompletionRequest.builder()",
"score": 17.977989971776374
},
{
"filename": "src/main/java/com/minivv/pilot/utils/Donate.java",
"retrieved_chunk": "package com.minivv.pilot.utils;\nimport com.intellij.ide.BrowserUtil;\nimport com.intellij.openapi.diagnostic.Logger;\nimport com.intellij.openapi.util.IconLoader;\nimport javax.swing.*;\nimport java.awt.image.BufferedImage;\nimport java.net.URL;\npublic class Donate {\n\tprivate static final Logger LOG = Logger.getInstance(Donate.class);\n\tpublic static final Icon ICON = IconLoader.getIcon(\"com/minivv/pilot/ui/coins_in_hand.png\", Donate.class);",
"score": 15.464940319638105
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": "public class PromptsTable extends JTable {\n private static final Logger LOG = Logger.getInstance(PromptsTable.class);\n private static final int NAME_COLUMN = 0;\n private static final int VALUE_COLUMN = 1;\n private final PromptTableModel promptTableModel = new PromptTableModel();\n public final List<Prompt> prompts = new ArrayList<>();\n public PromptsTable() {\n setModel(promptTableModel);\n DefaultCellEditor editor = new DefaultCellEditor(new JTextField());\n this.setCellEditor(editor);",
"score": 13.97113828933934
},
{
"filename": "src/main/java/com/minivv/pilot/utils/Donate.java",
"retrieved_chunk": "\tpublic static void initUrl(JButton donate, String url) {\n\t\tdonate.setIcon(ICON);\n\t\tdonate.addActionListener(e -> BrowserUtil.browse(url));\n\t}\n\tpublic static void initImage(JButton donate, String imgPath) {\n\t\tdonate.setIcon(ICON);\n\t\tdonate.addActionListener(e -> {\n\t\t\t// 加载图像文件\n\t\t\tBufferedImage img = null;\n\t\t\tURL url = Donate.class.getResource(imgPath);",
"score": 13.868752413772821
}
] | java | gptKeyLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/api-keys"); |
package com.minivv.pilot.ui;
import com.intellij.icons.AllIcons;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.ui.AnActionButton;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.AnActionLink;
import com.minivv.pilot.constants.SysConstants;
import com.minivv.pilot.model.AppSettings;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.Prompts;
import com.minivv.pilot.utils.ActionLinkUtils;
import com.minivv.pilot.utils.Donate;
import com.minivv.pilot.utils.GPTClient;
import com.minivv.pilot.utils.NotifyUtils;
import com.theokanning.openai.completion.CompletionChoice;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Objects;
/**
* todo 超时时间配置
* todo 更换NotifyUtils
* todo 限制代码量
*/
public class AppPluginSettingsPage {
private JPanel rootPane;
private JTextField gptKey;
private JTextField gptModel;
private JSpinner gptMaxToken;
private JCheckBox isReplace;
private JRadioButton enableProxy;
private JRadioButton httpProxy;
private JRadioButton socketProxy;
private JTextField proxyHost;
private JSpinner proxyPort;
private AnActionLink gptKeyLink;
private AnActionLink gptModelsLink;
private AnActionLink gptUsageLink;
private JTextField testConnMsg;
private JButton testConnButton;
private JPanel promptsPane;
private JSpinner maxWaitSeconds;
private JButton donatePaypal;
private JButton donateWx;
// private JPanel locale;
private AppSettings settings;
private final PromptsTable promptsTable;
public AppPluginSettingsPage(AppSettings original) {
this.settings = original.clone();
this.promptsTable = new PromptsTable();
promptsPane.add(ToolbarDecorator.createDecorator(promptsTable)
.setRemoveAction(button -> promptsTable.removeSelectedPrompts())
.setAddAction(button -> promptsTable.addPrompt(Prompt.of("Option" + promptsTable.getRowCount(), "Snippet:{query}")))
.addExtraAction(new AnActionButton("Reset Default Prompts", AllIcons.Actions.Rollback) {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
promptsTable.resetDefaultAliases();
}
})
.createPanel());
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent e) {
return promptsTable.editPrompt();
}
}.installOn(promptsTable);
// ComboBox<Locale> comboBox = new ComboBox<>();
// Locale[] locales = Locale.getAvailableLocales();
// for (Locale locale : locales) {
// comboBox.addItem(locale);
// }
// locale.add(comboBox);
Donate.initUrl(donatePaypal, "https://www.paypal.me/kuweiguge");
// Donate.initImage(donateWx,"images/wechat_donate.png");
}
private void createUIComponents() {
gptMaxToken = new JSpinner(new SpinnerNumberModel(2048, 128, 2048, 128));
proxyPort = new JSpinner(new SpinnerNumberModel(1087, 1, 65535, 1));
maxWaitSeconds = new JSpinner(new SpinnerNumberModel(60, 5, 600, 5));
gptKeyLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/api-keys");
gptModelsLink = ActionLinkUtils.newActionLink("https://platform.openai.com/docs/models/overview");
gptUsageLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/usage");
}
public AppSettings getSettings() {
promptsTable.commit(settings);
getData(settings);
return settings;
}
private void getData(AppSettings settings) {
settings.gptKey = gptKey.getText();
settings.gptModel = gptModel.getText();
settings.gptMaxTokens = (int) gptMaxToken.getValue();
settings.isReplace = isReplace.isSelected();
settings.enableProxy = enableProxy.isSelected();
settings.proxyHost = proxyHost.getText();
settings.proxyPort = (int) proxyPort.getValue();
settings.maxWaitSeconds = (int) maxWaitSeconds.getValue();
settings.proxyType = httpProxy.isSelected() ? SysConstants.httpProxyType : SysConstants.socketProxyType;
settings.testConnMsg = testConnMsg.getText();
settings.prompts = new Prompts(promptsTable.prompts);
}
public void importForm(AppSettings state) {
this.settings = state.clone();
setData(settings);
promptsTable.reset(settings);
}
private void setData(AppSettings settings) {
gptKey.setText(settings.gptKey);
gptModel.setText(settings.gptModel);
gptMaxToken.setValue(settings.gptMaxTokens);
isReplace.setSelected(settings.isReplace);
testConnMsg.setText(settings.testConnMsg);
httpProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.httpProxyType));
socketProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.socketProxyType));
proxyHost.setText(settings.proxyHost);
proxyPort.setValue(settings.proxyPort);
maxWaitSeconds.setValue(settings.maxWaitSeconds);
enableProxy.addChangeListener(e -> {
if (enableProxy.isSelected()) {
httpProxy.setEnabled(true);
socketProxy.setEnabled(true);
proxyHost.setEnabled(true);
proxyPort.setEnabled(true);
} else {
httpProxy.setEnabled(false);
socketProxy.setEnabled(false);
proxyHost.setEnabled(false);
proxyPort.setEnabled(false);
}
});
httpProxy.addChangeListener(e -> {
socketProxy.setSelected(!httpProxy.isSelected());
});
socketProxy.addChangeListener(e -> {
httpProxy.setSelected(!socketProxy.isSelected());
});
enableProxy.setSelected(settings.enableProxy);
testConnButton.addActionListener(e -> {
String msg = StringUtils.isBlank(testConnMsg.getText()) ? SysConstants.testConnMsg : testConnMsg.getText();
boolean hasError = checkSettings();
if (hasError) {
return;
}
List<CompletionChoice> choices = GPTClient.callChatGPT(msg, settings);
if (GPTClient.isSuccessful(choices)) {
NotifyUtils. | notifyMessage(AppSettings.getProject(), "Test connection successfully!ChatGPT answer:" + GPTClient.toString(choices), NotificationType.INFORMATION); |
} else {
NotifyUtils.notifyMessage(AppSettings.getProject(), "Test connection failed!", NotificationType.ERROR);
}
});
}
/**
* 保存设置
*
* @return 是否有错误
*/
private boolean checkSettings() {
StringBuilder error = new StringBuilder();
if (StringUtils.isBlank(gptKey.getText())) {
error.append("GPT Key is required.").append("\n");
}
if (StringUtils.isBlank(gptModel.getText())) {
error.append("GPT Model is required.").append("\n");
}
if (gptMaxToken.getValue() == null || (int) gptMaxToken.getValue() <= 0 || (int) gptMaxToken.getValue() > 2048) {
error.append("GPT Max Token is required and should be between 1 and 2048.").append("\n");
}
if (enableProxy.isSelected()) {
if (StringUtils.isBlank(proxyHost.getText())) {
error.append("Proxy Host is required.").append("\n");
}
if (proxyPort.getValue() == null || (int) proxyPort.getValue() <= 0 || (int) proxyPort.getValue() > 65535) {
error.append("Proxy Port is required and should be between 1 and 65535.").append("\n");
}
if (maxWaitSeconds.getValue() == null || (int) maxWaitSeconds.getValue() <= 0 || (int) maxWaitSeconds.getValue() > 600) {
error.append("Max Wait Seconds is required and should be between 5 and 600.").append("\n");
}
}
if (promptsTable.getRowCount() <= 0) {
error.append("Prompts is required.").append("\n");
}
if (promptsTable.prompts.stream().anyMatch(p -> !StringUtils.contains(p.getSnippet(), "{query}"))) {
error.append("Prompts should contain {query}.").append("\n");
}
if (StringUtils.isNotBlank(error)) {
NotifyUtils.notifyMessage(AppSettings.getProject(), error.toString(), NotificationType.ERROR);
return true;
} else {
return false;
}
}
public boolean isSettingsModified(AppSettings state) {
if (promptsTable.isModified(state)) return true;
return !this.settings.equals(state) || isModified(state);
}
private boolean isModified(AppSettings state) {
return !gptKey.getText().equals(state.gptKey) ||
!gptModel.getText().equals(state.gptModel) ||
!gptMaxToken.getValue().equals(state.gptMaxTokens) ||
isReplace.isSelected() != state.isReplace ||
enableProxy.isSelected() != state.enableProxy ||
!proxyHost.getText().equals(state.proxyHost) ||
!proxyPort.getValue().equals(state.proxyPort) ||
!maxWaitSeconds.getValue().equals(state.maxWaitSeconds) ||
!httpProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.httpProxyType) ||
!socketProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.socketProxyType) ||
!testConnMsg.getText().equals(state.testConnMsg);
}
public JPanel getRootPane() {
return rootPane;
}
public JTextField getGptKey() {
return gptKey;
}
}
| src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": " if(GPTClient.isSuccessful(choices)){\n optimizedCode = GPTClient.toString(choices);\n } else {\n NotifyUtils.notifyMessage(project,\"gpt-copilot connection failed, please check!\", NotificationType.ERROR);\n return;\n }\n //处理readable操作\n ApplicationManager.getApplication().runWriteAction(() -> {\n CommandProcessor.getInstance().executeCommand(\n project,",
"score": 46.38693308602926
},
{
"filename": "src/main/java/com/minivv/pilot/utils/GPTClient.java",
"retrieved_chunk": " } catch (Exception e) {\n return new ArrayList<>();\n }\n }\n public static boolean isSuccessful(List<CompletionChoice> choices) {\n return CollectionUtils.isNotEmpty(choices) && !choices.get(0).getText().isBlank();\n }\n public static String toString(List<CompletionChoice> choices) {\n if (CollectionUtils.isEmpty(choices)) {\n return \"ChatGPT response is empty,please check your network or config!\";",
"score": 44.446911919129505
},
{
"filename": "src/main/java/com/minivv/pilot/action/BasePilotPluginAction.java",
"retrieved_chunk": " doCommand(statement, editor, project);\n }\n private void doCommand(String statement, Editor editor, Project project) {\n AppSettings settings = AppSettingsStorage.getInstance().getState();\n if(settings == null){\n NotifyUtils.notifyMessage(project,\"gpt-copilot settings is null, please check!\", NotificationType.ERROR);\n return;\n }\n List<CompletionChoice> choices = GPTClient.callChatGPT(statement, settings);\n String optimizedCode;",
"score": 34.416664251691884
},
{
"filename": "src/main/java/com/minivv/pilot/utils/GPTClient.java",
"retrieved_chunk": " }\n return choices.get(0).getText();\n }\n}",
"score": 23.75682037535938
},
{
"filename": "src/main/java/com/minivv/pilot/constants/SysConstants.java",
"retrieved_chunk": "package com.minivv.pilot.constants;\npublic interface SysConstants {\n String httpProxyType = \"HTTP\";\n String socketProxyType = \"SOCKET\";\n String testConnMsg = \"Hello ChatGPT!\";\n}",
"score": 22.13905540154014
}
] | java | notifyMessage(AppSettings.getProject(), "Test connection successfully!ChatGPT answer:" + GPTClient.toString(choices), NotificationType.INFORMATION); |
package com.minivv.pilot.ui;
import com.intellij.icons.AllIcons;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.ui.AnActionButton;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.AnActionLink;
import com.minivv.pilot.constants.SysConstants;
import com.minivv.pilot.model.AppSettings;
import com.minivv.pilot.model.Prompt;
import com.minivv.pilot.model.Prompts;
import com.minivv.pilot.utils.ActionLinkUtils;
import com.minivv.pilot.utils.Donate;
import com.minivv.pilot.utils.GPTClient;
import com.minivv.pilot.utils.NotifyUtils;
import com.theokanning.openai.completion.CompletionChoice;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Objects;
/**
* todo 超时时间配置
* todo 更换NotifyUtils
* todo 限制代码量
*/
public class AppPluginSettingsPage {
private JPanel rootPane;
private JTextField gptKey;
private JTextField gptModel;
private JSpinner gptMaxToken;
private JCheckBox isReplace;
private JRadioButton enableProxy;
private JRadioButton httpProxy;
private JRadioButton socketProxy;
private JTextField proxyHost;
private JSpinner proxyPort;
private AnActionLink gptKeyLink;
private AnActionLink gptModelsLink;
private AnActionLink gptUsageLink;
private JTextField testConnMsg;
private JButton testConnButton;
private JPanel promptsPane;
private JSpinner maxWaitSeconds;
private JButton donatePaypal;
private JButton donateWx;
// private JPanel locale;
private AppSettings settings;
private final PromptsTable promptsTable;
public AppPluginSettingsPage(AppSettings original) {
this.settings | = original.clone(); |
this.promptsTable = new PromptsTable();
promptsPane.add(ToolbarDecorator.createDecorator(promptsTable)
.setRemoveAction(button -> promptsTable.removeSelectedPrompts())
.setAddAction(button -> promptsTable.addPrompt(Prompt.of("Option" + promptsTable.getRowCount(), "Snippet:{query}")))
.addExtraAction(new AnActionButton("Reset Default Prompts", AllIcons.Actions.Rollback) {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
promptsTable.resetDefaultAliases();
}
})
.createPanel());
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent e) {
return promptsTable.editPrompt();
}
}.installOn(promptsTable);
// ComboBox<Locale> comboBox = new ComboBox<>();
// Locale[] locales = Locale.getAvailableLocales();
// for (Locale locale : locales) {
// comboBox.addItem(locale);
// }
// locale.add(comboBox);
Donate.initUrl(donatePaypal, "https://www.paypal.me/kuweiguge");
// Donate.initImage(donateWx,"images/wechat_donate.png");
}
private void createUIComponents() {
gptMaxToken = new JSpinner(new SpinnerNumberModel(2048, 128, 2048, 128));
proxyPort = new JSpinner(new SpinnerNumberModel(1087, 1, 65535, 1));
maxWaitSeconds = new JSpinner(new SpinnerNumberModel(60, 5, 600, 5));
gptKeyLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/api-keys");
gptModelsLink = ActionLinkUtils.newActionLink("https://platform.openai.com/docs/models/overview");
gptUsageLink = ActionLinkUtils.newActionLink("https://platform.openai.com/account/usage");
}
public AppSettings getSettings() {
promptsTable.commit(settings);
getData(settings);
return settings;
}
private void getData(AppSettings settings) {
settings.gptKey = gptKey.getText();
settings.gptModel = gptModel.getText();
settings.gptMaxTokens = (int) gptMaxToken.getValue();
settings.isReplace = isReplace.isSelected();
settings.enableProxy = enableProxy.isSelected();
settings.proxyHost = proxyHost.getText();
settings.proxyPort = (int) proxyPort.getValue();
settings.maxWaitSeconds = (int) maxWaitSeconds.getValue();
settings.proxyType = httpProxy.isSelected() ? SysConstants.httpProxyType : SysConstants.socketProxyType;
settings.testConnMsg = testConnMsg.getText();
settings.prompts = new Prompts(promptsTable.prompts);
}
public void importForm(AppSettings state) {
this.settings = state.clone();
setData(settings);
promptsTable.reset(settings);
}
private void setData(AppSettings settings) {
gptKey.setText(settings.gptKey);
gptModel.setText(settings.gptModel);
gptMaxToken.setValue(settings.gptMaxTokens);
isReplace.setSelected(settings.isReplace);
testConnMsg.setText(settings.testConnMsg);
httpProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.httpProxyType));
socketProxy.setSelected(Objects.equals(settings.proxyType, SysConstants.socketProxyType));
proxyHost.setText(settings.proxyHost);
proxyPort.setValue(settings.proxyPort);
maxWaitSeconds.setValue(settings.maxWaitSeconds);
enableProxy.addChangeListener(e -> {
if (enableProxy.isSelected()) {
httpProxy.setEnabled(true);
socketProxy.setEnabled(true);
proxyHost.setEnabled(true);
proxyPort.setEnabled(true);
} else {
httpProxy.setEnabled(false);
socketProxy.setEnabled(false);
proxyHost.setEnabled(false);
proxyPort.setEnabled(false);
}
});
httpProxy.addChangeListener(e -> {
socketProxy.setSelected(!httpProxy.isSelected());
});
socketProxy.addChangeListener(e -> {
httpProxy.setSelected(!socketProxy.isSelected());
});
enableProxy.setSelected(settings.enableProxy);
testConnButton.addActionListener(e -> {
String msg = StringUtils.isBlank(testConnMsg.getText()) ? SysConstants.testConnMsg : testConnMsg.getText();
boolean hasError = checkSettings();
if (hasError) {
return;
}
List<CompletionChoice> choices = GPTClient.callChatGPT(msg, settings);
if (GPTClient.isSuccessful(choices)) {
NotifyUtils.notifyMessage(AppSettings.getProject(), "Test connection successfully!ChatGPT answer:" + GPTClient.toString(choices), NotificationType.INFORMATION);
} else {
NotifyUtils.notifyMessage(AppSettings.getProject(), "Test connection failed!", NotificationType.ERROR);
}
});
}
/**
* 保存设置
*
* @return 是否有错误
*/
private boolean checkSettings() {
StringBuilder error = new StringBuilder();
if (StringUtils.isBlank(gptKey.getText())) {
error.append("GPT Key is required.").append("\n");
}
if (StringUtils.isBlank(gptModel.getText())) {
error.append("GPT Model is required.").append("\n");
}
if (gptMaxToken.getValue() == null || (int) gptMaxToken.getValue() <= 0 || (int) gptMaxToken.getValue() > 2048) {
error.append("GPT Max Token is required and should be between 1 and 2048.").append("\n");
}
if (enableProxy.isSelected()) {
if (StringUtils.isBlank(proxyHost.getText())) {
error.append("Proxy Host is required.").append("\n");
}
if (proxyPort.getValue() == null || (int) proxyPort.getValue() <= 0 || (int) proxyPort.getValue() > 65535) {
error.append("Proxy Port is required and should be between 1 and 65535.").append("\n");
}
if (maxWaitSeconds.getValue() == null || (int) maxWaitSeconds.getValue() <= 0 || (int) maxWaitSeconds.getValue() > 600) {
error.append("Max Wait Seconds is required and should be between 5 and 600.").append("\n");
}
}
if (promptsTable.getRowCount() <= 0) {
error.append("Prompts is required.").append("\n");
}
if (promptsTable.prompts.stream().anyMatch(p -> !StringUtils.contains(p.getSnippet(), "{query}"))) {
error.append("Prompts should contain {query}.").append("\n");
}
if (StringUtils.isNotBlank(error)) {
NotifyUtils.notifyMessage(AppSettings.getProject(), error.toString(), NotificationType.ERROR);
return true;
} else {
return false;
}
}
public boolean isSettingsModified(AppSettings state) {
if (promptsTable.isModified(state)) return true;
return !this.settings.equals(state) || isModified(state);
}
private boolean isModified(AppSettings state) {
return !gptKey.getText().equals(state.gptKey) ||
!gptModel.getText().equals(state.gptModel) ||
!gptMaxToken.getValue().equals(state.gptMaxTokens) ||
isReplace.isSelected() != state.isReplace ||
enableProxy.isSelected() != state.enableProxy ||
!proxyHost.getText().equals(state.proxyHost) ||
!proxyPort.getValue().equals(state.proxyPort) ||
!maxWaitSeconds.getValue().equals(state.maxWaitSeconds) ||
!httpProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.httpProxyType) ||
!socketProxy.isSelected() == Objects.equals(state.proxyType, SysConstants.socketProxyType) ||
!testConnMsg.getText().equals(state.testConnMsg);
}
public JPanel getRootPane() {
return rootPane;
}
public JTextField getGptKey() {
return gptKey;
}
}
| src/main/java/com/minivv/pilot/ui/AppPluginSettingsPage.java | minivv-gpt-copilot-b16ad12 | [
{
"filename": "src/main/java/com/minivv/pilot/state/AppSettingsStorage.java",
"retrieved_chunk": " private AppSettings settings = new AppSettings();\n private final String idPrefix = \"chatGptPilot_\";\n private final DefaultActionGroup actionGroup = new DefaultActionGroup(\"gpt pilot\", true);\n @Nullable\n @Override\n public AppSettings getState() {\n if (settings == null) {\n settings = new AppSettings();\n }\n return settings;",
"score": 29.859664067013
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": "public class PromptsTable extends JTable {\n private static final Logger LOG = Logger.getInstance(PromptsTable.class);\n private static final int NAME_COLUMN = 0;\n private static final int VALUE_COLUMN = 1;\n private final PromptTableModel promptTableModel = new PromptTableModel();\n public final List<Prompt> prompts = new ArrayList<>();\n public PromptsTable() {\n setModel(promptTableModel);\n DefaultCellEditor editor = new DefaultCellEditor(new JTextField());\n this.setCellEditor(editor);",
"score": 26.745584861406652
},
{
"filename": "src/main/java/com/minivv/pilot/AppConfigurable.java",
"retrieved_chunk": " private AppPluginSettingsPage form;\n private AppSettings state;\n private AppSettingsStorage appSettingsStorage;\n public AppConfigurable() {\n appSettingsStorage = AppSettingsStorage.getInstance();\n state = appSettingsStorage.getState();\n }\n @Nls(capitalization = Nls.Capitalization.Title)\n @Override\n public String getDisplayName() {",
"score": 24.504952530611
},
{
"filename": "src/main/java/com/minivv/pilot/model/Prompt.java",
"retrieved_chunk": "package com.minivv.pilot.model;\npublic class Prompt extends DomainObject {\n\tprivate String option;\n\tprivate String snippet;\n//\tprivate Integer index;\n\tpublic Prompt() {\n\t}\n//\tpublic Prompt(String option, String snippet,int index) {\n//\t\tthis.option = option;\n//\t\tthis.snippet = snippet;",
"score": 18.647461065308097
},
{
"filename": "src/main/java/com/minivv/pilot/ui/PromptsTable.java",
"retrieved_chunk": " }\n private void obtainPrompts(@NotNull List<Prompt> prompts, AppSettings settings) {\n prompts.clear();\n prompts.addAll(settings.prompts.getPrompts());\n }\n public void addPrompt(Prompt prompt) {\n prompts.add(prompt);\n promptTableModel.fireTableRowsInserted(prompts.size() - 1, prompts.size() - 1);\n }\n public void commit(AppSettings settings) {",
"score": 18.592219548367986
}
] | java | = original.clone(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.