repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
slezier/SimpleFunctionalTest | sft-md-report/src/main/java/sft/reports/markdown/decorators/MdNullDecorator.java | // Path: sft-core/src/main/java/sft/FixtureCall.java
// public class FixtureCall {
//
// public final UseCase useCase;
// public final String name;
// public final int line;
// public final Fixture fixture;
// public final int emptyLine;
// public ArrayList<String> parametersValues = new ArrayList<String>();
//
// public FixtureCall(UseCase useCase, String name, int line, Fixture fixture, ArrayList<String> parametersValues, int emptyLine) {
// this.useCase = useCase;
// this.name = name;
// this.line = line;
// this.fixture= fixture;
// this.emptyLine = emptyLine;
// this.parametersValues.addAll(parametersValues);
// }
//
// public Map<String, String> getParameters() {
// final HashMap<String, String> parameters = new HashMap<String, String>();
// for (int index = 0; index < fixture.parametersName.size(); index++) {
// String name = fixture.parametersName.get(index);
// String value = parametersValues.get(index);
// parameters.put(name,value);
// }
// return parameters;
// }
// }
//
// Path: sft-md-report/src/main/java/sft/reports/markdown/MarkdownReport.java
// public class MarkdownReport extends Report {
// private Map<Class<? extends Decorator>, DecoratorReportImplementation> decorators= new HashMap<Class<? extends Decorator>, DecoratorReportImplementation>();
//
// private TargetFolder folder;
// private static final String TARGET_SFT_RESULT = "target/sft-result/";
// public static final String MD_DEPENDENCIES_FOLDER = "sft-md-default";
//
//
// public MarkdownReport(DefaultConfiguration configuration){
// super(configuration);
// decorators.put(NullDecorator.class,new MdNullDecorator(configuration));
// folder=configuration.getProjectFolder().getTargetFolder(TARGET_SFT_RESULT);
// }
//
// @Override
// public DecoratorReportImplementation getDecoratorImplementation(Decorator decorator) {
// DecoratorReportImplementation result = decorators.get(decorator.getClass());
// if( result == null ){
// result = new MdNullDecorator(configuration);
// }
// return result;
// }
//
// @Override
// public void addDecorator(Class<? extends Decorator> decoratorClass, DecoratorReportImplementation decoratorImplementation) {
// decorators.put(decoratorClass,decoratorImplementation);
//
// }
//
// @Override
// public void report(UseCaseResult useCaseResult) throws Exception {
// folder.copyFromResources(MD_DEPENDENCIES_FOLDER);
// final Decorator decorator = useCaseResult.useCase.useCaseDecorator;
// DecoratorReportImplementation decoratorImplementation = getDecoratorImplementation(decorator);
// String useCaseReport = decoratorImplementation.applyOnUseCase(useCaseResult, decorator.parameters);
//
// File mdFile = folder.createFileFromClass(useCaseResult.useCase.classUnderTest, ".md");
// Writer html = new OutputStreamWriter(new FileOutputStream(mdFile));
// html.write(useCaseReport);
// html.close();
// System.out.println("Report wrote: " + mdFile.getCanonicalPath());
// }
// }
| import sft.ContextHandler;
import sft.DefaultConfiguration;
import sft.FixtureCall;
import sft.UseCase;
import sft.decorators.DecoratorReportImplementation;
import sft.report.RelativePathResolver;
import sft.reports.markdown.MarkdownReport;
import sft.result.*;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher; | result += writeContext(useCaseResult.useCase.beforeUseCase);
result += applyOnScenarios(useCaseResult.scenarioResults);
result += writeContext(useCaseResult.useCase.afterUseCase);
result += applyOnSubUseCases(useCaseResult.subUseCaseResults);
return result;
}
private String writeContext(ContextHandler beforeUseCase) {
String result = "";
if(beforeUseCase != null && beforeUseCase.fixtureCalls !=null){
for (FixtureCall fixtureCall : beforeUseCase.fixtureCalls) {
result += applyOnFixtureCall(Issue.SUCCEEDED, fixtureCall);
}
}
return result;
}
private String writeComment(String comment) {
if( comment == null ){
return "";
}
return ">" + comment.replaceAll("\\n","\n>\n>") +"\n\n";
}
private String writeUseCaseName(UseCase useCase, Issue issue) {
return "# " + useCase.getName()+ getIssueMarkdownImage(issue, useCase.classUnderTest, Size.BIG) +"\n";
}
private String getIssueMarkdownImage(Issue issue, Class<?> classUnderTest, Size size) {
String pathOf = pathResolver.getPathOf(classUnderTest, "md"); | // Path: sft-core/src/main/java/sft/FixtureCall.java
// public class FixtureCall {
//
// public final UseCase useCase;
// public final String name;
// public final int line;
// public final Fixture fixture;
// public final int emptyLine;
// public ArrayList<String> parametersValues = new ArrayList<String>();
//
// public FixtureCall(UseCase useCase, String name, int line, Fixture fixture, ArrayList<String> parametersValues, int emptyLine) {
// this.useCase = useCase;
// this.name = name;
// this.line = line;
// this.fixture= fixture;
// this.emptyLine = emptyLine;
// this.parametersValues.addAll(parametersValues);
// }
//
// public Map<String, String> getParameters() {
// final HashMap<String, String> parameters = new HashMap<String, String>();
// for (int index = 0; index < fixture.parametersName.size(); index++) {
// String name = fixture.parametersName.get(index);
// String value = parametersValues.get(index);
// parameters.put(name,value);
// }
// return parameters;
// }
// }
//
// Path: sft-md-report/src/main/java/sft/reports/markdown/MarkdownReport.java
// public class MarkdownReport extends Report {
// private Map<Class<? extends Decorator>, DecoratorReportImplementation> decorators= new HashMap<Class<? extends Decorator>, DecoratorReportImplementation>();
//
// private TargetFolder folder;
// private static final String TARGET_SFT_RESULT = "target/sft-result/";
// public static final String MD_DEPENDENCIES_FOLDER = "sft-md-default";
//
//
// public MarkdownReport(DefaultConfiguration configuration){
// super(configuration);
// decorators.put(NullDecorator.class,new MdNullDecorator(configuration));
// folder=configuration.getProjectFolder().getTargetFolder(TARGET_SFT_RESULT);
// }
//
// @Override
// public DecoratorReportImplementation getDecoratorImplementation(Decorator decorator) {
// DecoratorReportImplementation result = decorators.get(decorator.getClass());
// if( result == null ){
// result = new MdNullDecorator(configuration);
// }
// return result;
// }
//
// @Override
// public void addDecorator(Class<? extends Decorator> decoratorClass, DecoratorReportImplementation decoratorImplementation) {
// decorators.put(decoratorClass,decoratorImplementation);
//
// }
//
// @Override
// public void report(UseCaseResult useCaseResult) throws Exception {
// folder.copyFromResources(MD_DEPENDENCIES_FOLDER);
// final Decorator decorator = useCaseResult.useCase.useCaseDecorator;
// DecoratorReportImplementation decoratorImplementation = getDecoratorImplementation(decorator);
// String useCaseReport = decoratorImplementation.applyOnUseCase(useCaseResult, decorator.parameters);
//
// File mdFile = folder.createFileFromClass(useCaseResult.useCase.classUnderTest, ".md");
// Writer html = new OutputStreamWriter(new FileOutputStream(mdFile));
// html.write(useCaseReport);
// html.close();
// System.out.println("Report wrote: " + mdFile.getCanonicalPath());
// }
// }
// Path: sft-md-report/src/main/java/sft/reports/markdown/decorators/MdNullDecorator.java
import sft.ContextHandler;
import sft.DefaultConfiguration;
import sft.FixtureCall;
import sft.UseCase;
import sft.decorators.DecoratorReportImplementation;
import sft.report.RelativePathResolver;
import sft.reports.markdown.MarkdownReport;
import sft.result.*;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
result += writeContext(useCaseResult.useCase.beforeUseCase);
result += applyOnScenarios(useCaseResult.scenarioResults);
result += writeContext(useCaseResult.useCase.afterUseCase);
result += applyOnSubUseCases(useCaseResult.subUseCaseResults);
return result;
}
private String writeContext(ContextHandler beforeUseCase) {
String result = "";
if(beforeUseCase != null && beforeUseCase.fixtureCalls !=null){
for (FixtureCall fixtureCall : beforeUseCase.fixtureCalls) {
result += applyOnFixtureCall(Issue.SUCCEEDED, fixtureCall);
}
}
return result;
}
private String writeComment(String comment) {
if( comment == null ){
return "";
}
return ">" + comment.replaceAll("\\n","\n>\n>") +"\n\n";
}
private String writeUseCaseName(UseCase useCase, Issue issue) {
return "# " + useCase.getName()+ getIssueMarkdownImage(issue, useCase.classUnderTest, Size.BIG) +"\n";
}
private String getIssueMarkdownImage(Issue issue, Class<?> classUnderTest, Size size) {
String pathOf = pathResolver.getPathOf(classUnderTest, "md"); | String relativePathToFile = pathResolver.getRelativePathToFile(pathOf, MarkdownReport.MD_DEPENDENCIES_FOLDER); |
kbastani/oreilly-building-microservices-training | day-1/part-4/account-service/src/main/java/com/example/user/User.java | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
| import com.example.account.Account;
import javax.persistence.*;
import java.util.List; | package com.example.user;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Transient
private UserStatus status;
private Long userId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user") | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
// Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
import com.example.account.Account;
import javax.persistence.*;
import java.util.List;
package com.example.user;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Transient
private UserStatus status;
private Long userId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user") | private List<Account> accounts; |
kbastani/oreilly-building-microservices-training | day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
| import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.Set; | package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository; | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.Set;
package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository; | private UserService userService; |
kbastani/oreilly-building-microservices-training | day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
| import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.Set; | package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService; | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.Set;
package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService; | private UserRepository userRepository; |
kbastani/oreilly-building-microservices-training | day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
| import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.Set; | package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService;
private UserRepository userRepository;
public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
this.accountRepository = accountRepository;
this.userService = userService;
this.userRepository = userRepository;
}
public Account createAccount(Long userId, Account account) {
// Call the user microservice | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.Set;
package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService;
private UserRepository userRepository;
public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
this.accountRepository = accountRepository;
this.userService = userService;
this.userRepository = userRepository;
}
public Account createAccount(Long userId, Account account) {
// Call the user microservice | User user = userService.getUser(userId); |
kbastani/oreilly-building-microservices-training | day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
| import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.Set; | package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService;
private UserRepository userRepository;
public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
this.accountRepository = accountRepository;
this.userService = userService;
this.userRepository = userRepository;
}
public Account createAccount(Long userId, Account account) {
// Call the user microservice
User user = userService.getUser(userId);
Assert.notNull(user, "The user with the ID could not be found");
// The user must not be inactive | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.Set;
package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService;
private UserRepository userRepository;
public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
this.accountRepository = accountRepository;
this.userService = userService;
this.userRepository = userRepository;
}
public Account createAccount(Long userId, Account account) {
// Call the user microservice
User user = userService.getUser(userId);
Assert.notNull(user, "The user with the ID could not be found");
// The user must not be inactive | if (user.getStatus() != UserStatus.ACTIVE) { |
kbastani/oreilly-building-microservices-training | day-1/part-4/account-service/src/main/java/com/example/account/AccountService.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
| import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.List; | package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository; | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
// Path: day-1/part-4/account-service/src/main/java/com/example/account/AccountService.java
import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.List;
package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository; | private UserService userService; |
kbastani/oreilly-building-microservices-training | day-1/part-4/account-service/src/main/java/com/example/account/AccountService.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
| import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.List; | package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService; | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
// Path: day-1/part-4/account-service/src/main/java/com/example/account/AccountService.java
import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.List;
package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService; | private UserRepository userRepository; |
kbastani/oreilly-building-microservices-training | day-1/part-4/account-service/src/main/java/com/example/account/AccountService.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
| import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.List; | package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService;
private UserRepository userRepository;
public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
this.accountRepository = accountRepository;
this.userService = userService;
this.userRepository = userRepository;
}
public Account createAccount(Long userId, Account account) {
// Call the user microservice | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
// Path: day-1/part-4/account-service/src/main/java/com/example/account/AccountService.java
import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.List;
package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService;
private UserRepository userRepository;
public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
this.accountRepository = accountRepository;
this.userService = userService;
this.userRepository = userRepository;
}
public Account createAccount(Long userId, Account account) {
// Call the user microservice | User user = userService.getUser(userId); |
kbastani/oreilly-building-microservices-training | day-1/part-4/account-service/src/main/java/com/example/account/AccountService.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
| import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.List; | package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService;
private UserRepository userRepository;
public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
this.accountRepository = accountRepository;
this.userService = userService;
this.userRepository = userRepository;
}
public Account createAccount(Long userId, Account account) {
// Call the user microservice
User user = userService.getUser(userId);
Assert.notNull(user, "The user with the ID could not be found");
// The user must not be inactive | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserRepository.java
// public interface UserRepository extends GraphRepository<User> {
// User getUserByUserId(Long userId);
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserService.java
// @Service
// @Transactional
// public class UserService {
//
// private RestTemplate restTemplate;
//
// public UserService(RestTemplate restTemplate) {
// this.restTemplate = restTemplate;
// }
//
// public User getUser(Long userId) {
// User user = null;
//
// ResponseEntity<User> response =
// restTemplate.getForEntity(URI.create("http://user-service/users/" + userId), User.class);
//
// if (response.getStatusCode().is2xxSuccessful())
// user = response.getBody();
//
// return user;
// }
// }
//
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserStatus.java
// public enum UserStatus {
// ACTIVE,
// INACTIVE
// }
// Path: day-1/part-4/account-service/src/main/java/com/example/account/AccountService.java
import com.example.user.User;
import com.example.user.UserRepository;
import com.example.user.UserService;
import com.example.user.UserStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.List;
package com.example.account;
@Service
@Transactional
public class AccountService {
private AccountRepository accountRepository;
private UserService userService;
private UserRepository userRepository;
public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
this.accountRepository = accountRepository;
this.userService = userService;
this.userRepository = userRepository;
}
public Account createAccount(Long userId, Account account) {
// Call the user microservice
User user = userService.getUser(userId);
Assert.notNull(user, "The user with the ID could not be found");
// The user must not be inactive | if (user.getStatus() != UserStatus.ACTIVE) { |
kbastani/oreilly-building-microservices-training | day-1/part-4/account-service/src/main/java/com/example/user/UserController.java | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
// @Service
// @Transactional
// public class AccountService {
//
// private AccountRepository accountRepository;
// private UserService userService;
// private UserRepository userRepository;
//
// public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
// this.accountRepository = accountRepository;
// this.userService = userService;
// this.userRepository = userRepository;
// }
//
// public Account createAccount(Long userId, Account account) {
// // Call the user microservice
// User user = userService.getUser(userId);
//
// Assert.notNull(user, "The user with the ID could not be found");
//
// // The user must not be inactive
// if (user.getStatus() != UserStatus.ACTIVE) {
// throw new RuntimeException("Cannot create a new account for an inactive user");
// }
//
// // Set the user relationship on the new account object
// account.setUser(new User(userId));
//
// return accountRepository.save(account);
// }
//
// public Account getAccount(String accountNumber) {
// return accountRepository.getAccountByAccountNumber(accountNumber);
// }
//
// public Set<Account> getAccounts(Long userId) {
// User user = userRepository.getUserByUserId(userId);
//
// if(user == null) {
// return Collections.emptySet();
// }
//
// return user.getAccounts();
// }
// }
| import com.example.account.Account;
import com.example.account.AccountService;
import org.springframework.web.bind.annotation.*;
import java.util.List; | package com.example.user;
@RestController
@RequestMapping("/v1/users")
public class UserController {
| // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
// @Service
// @Transactional
// public class AccountService {
//
// private AccountRepository accountRepository;
// private UserService userService;
// private UserRepository userRepository;
//
// public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
// this.accountRepository = accountRepository;
// this.userService = userService;
// this.userRepository = userRepository;
// }
//
// public Account createAccount(Long userId, Account account) {
// // Call the user microservice
// User user = userService.getUser(userId);
//
// Assert.notNull(user, "The user with the ID could not be found");
//
// // The user must not be inactive
// if (user.getStatus() != UserStatus.ACTIVE) {
// throw new RuntimeException("Cannot create a new account for an inactive user");
// }
//
// // Set the user relationship on the new account object
// account.setUser(new User(userId));
//
// return accountRepository.save(account);
// }
//
// public Account getAccount(String accountNumber) {
// return accountRepository.getAccountByAccountNumber(accountNumber);
// }
//
// public Set<Account> getAccounts(Long userId) {
// User user = userRepository.getUserByUserId(userId);
//
// if(user == null) {
// return Collections.emptySet();
// }
//
// return user.getAccounts();
// }
// }
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserController.java
import com.example.account.Account;
import com.example.account.AccountService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
package com.example.user;
@RestController
@RequestMapping("/v1/users")
public class UserController {
| private AccountService accountService; |
kbastani/oreilly-building-microservices-training | day-1/part-4/account-service/src/main/java/com/example/user/UserController.java | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
// @Service
// @Transactional
// public class AccountService {
//
// private AccountRepository accountRepository;
// private UserService userService;
// private UserRepository userRepository;
//
// public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
// this.accountRepository = accountRepository;
// this.userService = userService;
// this.userRepository = userRepository;
// }
//
// public Account createAccount(Long userId, Account account) {
// // Call the user microservice
// User user = userService.getUser(userId);
//
// Assert.notNull(user, "The user with the ID could not be found");
//
// // The user must not be inactive
// if (user.getStatus() != UserStatus.ACTIVE) {
// throw new RuntimeException("Cannot create a new account for an inactive user");
// }
//
// // Set the user relationship on the new account object
// account.setUser(new User(userId));
//
// return accountRepository.save(account);
// }
//
// public Account getAccount(String accountNumber) {
// return accountRepository.getAccountByAccountNumber(accountNumber);
// }
//
// public Set<Account> getAccounts(Long userId) {
// User user = userRepository.getUserByUserId(userId);
//
// if(user == null) {
// return Collections.emptySet();
// }
//
// return user.getAccounts();
// }
// }
| import com.example.account.Account;
import com.example.account.AccountService;
import org.springframework.web.bind.annotation.*;
import java.util.List; | package com.example.user;
@RestController
@RequestMapping("/v1/users")
public class UserController {
private AccountService accountService;
public UserController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/{userId}/accounts") | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
// @Service
// @Transactional
// public class AccountService {
//
// private AccountRepository accountRepository;
// private UserService userService;
// private UserRepository userRepository;
//
// public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
// this.accountRepository = accountRepository;
// this.userService = userService;
// this.userRepository = userRepository;
// }
//
// public Account createAccount(Long userId, Account account) {
// // Call the user microservice
// User user = userService.getUser(userId);
//
// Assert.notNull(user, "The user with the ID could not be found");
//
// // The user must not be inactive
// if (user.getStatus() != UserStatus.ACTIVE) {
// throw new RuntimeException("Cannot create a new account for an inactive user");
// }
//
// // Set the user relationship on the new account object
// account.setUser(new User(userId));
//
// return accountRepository.save(account);
// }
//
// public Account getAccount(String accountNumber) {
// return accountRepository.getAccountByAccountNumber(accountNumber);
// }
//
// public Set<Account> getAccounts(Long userId) {
// User user = userRepository.getUserByUserId(userId);
//
// if(user == null) {
// return Collections.emptySet();
// }
//
// return user.getAccounts();
// }
// }
// Path: day-1/part-4/account-service/src/main/java/com/example/user/UserController.java
import com.example.account.Account;
import com.example.account.AccountService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
package com.example.user;
@RestController
@RequestMapping("/v1/users")
public class UserController {
private AccountService accountService;
public UserController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/{userId}/accounts") | public List<Account> getUserAccounts(@PathVariable Long userId) { |
kbastani/oreilly-building-microservices-training | day-1/part-2/account-service/src/main/java/com/example/account/Account.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
| import com.example.user.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.UUID; | package com.example.account;
@NodeEntity
public class Account {
@GraphId
private Long id;
@JsonIgnore
@Relationship(type = "HAS_ACCOUNT", direction = "INCOMING") | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
// Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
import com.example.user.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.neo4j.ogm.annotation.GraphId;
import org.neo4j.ogm.annotation.NodeEntity;
import org.neo4j.ogm.annotation.Relationship;
import java.util.UUID;
package com.example.account;
@NodeEntity
public class Account {
@GraphId
private Long id;
@JsonIgnore
@Relationship(type = "HAS_ACCOUNT", direction = "INCOMING") | private User user; |
kbastani/oreilly-building-microservices-training | day-1/part-2/account-service/src/main/java/com/example/user/UserController.java | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
// @Service
// @Transactional
// public class AccountService {
//
// private AccountRepository accountRepository;
// private UserService userService;
// private UserRepository userRepository;
//
// public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
// this.accountRepository = accountRepository;
// this.userService = userService;
// this.userRepository = userRepository;
// }
//
// public Account createAccount(Long userId, Account account) {
// // Call the user microservice
// User user = userService.getUser(userId);
//
// Assert.notNull(user, "The user with the ID could not be found");
//
// // The user must not be inactive
// if (user.getStatus() != UserStatus.ACTIVE) {
// throw new RuntimeException("Cannot create a new account for an inactive user");
// }
//
// // Set the user relationship on the new account object
// account.setUser(new User(userId));
//
// return accountRepository.save(account);
// }
//
// public Account getAccount(String accountNumber) {
// return accountRepository.getAccountByAccountNumber(accountNumber);
// }
//
// public Set<Account> getAccounts(Long userId) {
// User user = userRepository.getUserByUserId(userId);
//
// if(user == null) {
// return Collections.emptySet();
// }
//
// return user.getAccounts();
// }
// }
| import com.example.account.Account;
import com.example.account.AccountService;
import org.springframework.web.bind.annotation.*;
import java.util.Set; | package com.example.user;
@RestController
@RequestMapping("/v1/users")
public class UserController {
| // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
// @Service
// @Transactional
// public class AccountService {
//
// private AccountRepository accountRepository;
// private UserService userService;
// private UserRepository userRepository;
//
// public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
// this.accountRepository = accountRepository;
// this.userService = userService;
// this.userRepository = userRepository;
// }
//
// public Account createAccount(Long userId, Account account) {
// // Call the user microservice
// User user = userService.getUser(userId);
//
// Assert.notNull(user, "The user with the ID could not be found");
//
// // The user must not be inactive
// if (user.getStatus() != UserStatus.ACTIVE) {
// throw new RuntimeException("Cannot create a new account for an inactive user");
// }
//
// // Set the user relationship on the new account object
// account.setUser(new User(userId));
//
// return accountRepository.save(account);
// }
//
// public Account getAccount(String accountNumber) {
// return accountRepository.getAccountByAccountNumber(accountNumber);
// }
//
// public Set<Account> getAccounts(Long userId) {
// User user = userRepository.getUserByUserId(userId);
//
// if(user == null) {
// return Collections.emptySet();
// }
//
// return user.getAccounts();
// }
// }
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserController.java
import com.example.account.Account;
import com.example.account.AccountService;
import org.springframework.web.bind.annotation.*;
import java.util.Set;
package com.example.user;
@RestController
@RequestMapping("/v1/users")
public class UserController {
| private AccountService accountService; |
kbastani/oreilly-building-microservices-training | day-1/part-2/account-service/src/main/java/com/example/user/UserController.java | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
// @Service
// @Transactional
// public class AccountService {
//
// private AccountRepository accountRepository;
// private UserService userService;
// private UserRepository userRepository;
//
// public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
// this.accountRepository = accountRepository;
// this.userService = userService;
// this.userRepository = userRepository;
// }
//
// public Account createAccount(Long userId, Account account) {
// // Call the user microservice
// User user = userService.getUser(userId);
//
// Assert.notNull(user, "The user with the ID could not be found");
//
// // The user must not be inactive
// if (user.getStatus() != UserStatus.ACTIVE) {
// throw new RuntimeException("Cannot create a new account for an inactive user");
// }
//
// // Set the user relationship on the new account object
// account.setUser(new User(userId));
//
// return accountRepository.save(account);
// }
//
// public Account getAccount(String accountNumber) {
// return accountRepository.getAccountByAccountNumber(accountNumber);
// }
//
// public Set<Account> getAccounts(Long userId) {
// User user = userRepository.getUserByUserId(userId);
//
// if(user == null) {
// return Collections.emptySet();
// }
//
// return user.getAccounts();
// }
// }
| import com.example.account.Account;
import com.example.account.AccountService;
import org.springframework.web.bind.annotation.*;
import java.util.Set; | package com.example.user;
@RestController
@RequestMapping("/v1/users")
public class UserController {
private AccountService accountService;
public UserController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/{userId}/accounts") | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
//
// Path: day-1/part-2/account-service/src/main/java/com/example/account/AccountService.java
// @Service
// @Transactional
// public class AccountService {
//
// private AccountRepository accountRepository;
// private UserService userService;
// private UserRepository userRepository;
//
// public AccountService(AccountRepository accountRepository, UserService userService, UserRepository userRepository) {
// this.accountRepository = accountRepository;
// this.userService = userService;
// this.userRepository = userRepository;
// }
//
// public Account createAccount(Long userId, Account account) {
// // Call the user microservice
// User user = userService.getUser(userId);
//
// Assert.notNull(user, "The user with the ID could not be found");
//
// // The user must not be inactive
// if (user.getStatus() != UserStatus.ACTIVE) {
// throw new RuntimeException("Cannot create a new account for an inactive user");
// }
//
// // Set the user relationship on the new account object
// account.setUser(new User(userId));
//
// return accountRepository.save(account);
// }
//
// public Account getAccount(String accountNumber) {
// return accountRepository.getAccountByAccountNumber(accountNumber);
// }
//
// public Set<Account> getAccounts(Long userId) {
// User user = userRepository.getUserByUserId(userId);
//
// if(user == null) {
// return Collections.emptySet();
// }
//
// return user.getAccounts();
// }
// }
// Path: day-1/part-2/account-service/src/main/java/com/example/user/UserController.java
import com.example.account.Account;
import com.example.account.AccountService;
import org.springframework.web.bind.annotation.*;
import java.util.Set;
package com.example.user;
@RestController
@RequestMapping("/v1/users")
public class UserController {
private AccountService accountService;
public UserController(AccountService accountService) {
this.accountService = accountService;
}
@GetMapping("/{userId}/accounts") | public Set<Account> getUserAccounts(@PathVariable Long userId) { |
kbastani/oreilly-building-microservices-training | day-1/part-4/account-service/src/main/java/com/example/account/Account.java | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
| import com.example.user.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.UUID; | package com.example.account;
@Entity
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) | // Path: day-1/part-4/account-service/src/main/java/com/example/user/User.java
// @Entity
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Transient
// private UserStatus status;
//
// private Long userId;
//
// @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
// private List<Account> accounts;
//
// public User() {
// }
//
// public User(Long userId) {
// this.userId = userId;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public List<Account> getAccounts() {
// return accounts;
// }
//
// public void setAccounts(List<Account> accounts) {
// this.accounts = accounts;
// }
//
// public UserStatus getStatus() {
// return status;
// }
//
// public void setStatus(UserStatus status) {
// this.status = status;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "id=" + id +
// ", status=" + status +
// ", userId=" + userId +
// ", accounts=" + accounts +
// '}';
// }
// }
// Path: day-1/part-4/account-service/src/main/java/com/example/account/Account.java
import com.example.user.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.UUID;
package com.example.account;
@Entity
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) | private User user; |
kbastani/oreilly-building-microservices-training | day-1/part-2/account-service/src/main/java/com/example/user/User.java | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
| import com.example.account.Account;
import org.neo4j.ogm.annotation.*;
import java.util.Set; | package com.example.user;
@NodeEntity
public class User {
@GraphId
private Long id;
@Transient
private UserStatus status;
@Index(unique = true, primary = true)
private Long userId;
@Relationship(type = "HAS_ACCOUNT") | // Path: day-1/part-2/account-service/src/main/java/com/example/account/Account.java
// @NodeEntity
// public class Account {
//
// @GraphId
// private Long id;
//
// @JsonIgnore
// @Relationship(type = "HAS_ACCOUNT", direction = "INCOMING")
// private User user;
// private String accountNumber;
// private AccountStatus status;
//
// public Account() {
// accountNumber = UUID.randomUUID().toString();
// }
//
// public Account(User user) {
// this();
// this.user = user;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public AccountStatus getStatus() {
// return status;
// }
//
// public void setStatus(AccountStatus status) {
// this.status = status;
// }
//
// public Long getUserId() {
// return user != null ? user.getUserId() : null;
// }
//
// @Override
// public String toString() {
// return "Account{" +
// "id=" + id +
// ", user=" + user +
// ", accountNumber='" + accountNumber + '\'' +
// '}';
// }
// }
// Path: day-1/part-2/account-service/src/main/java/com/example/user/User.java
import com.example.account.Account;
import org.neo4j.ogm.annotation.*;
import java.util.Set;
package com.example.user;
@NodeEntity
public class User {
@GraphId
private Long id;
@Transient
private UserStatus status;
@Index(unique = true, primary = true)
private Long userId;
@Relationship(type = "HAS_ACCOUNT") | private Set<Account> accounts; |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/PartStreamImplTest.java | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/PartStream.java
// public interface PartStream {
//
// /**
// * Returns the content type of this part, as it was submitted by
// * the client.
// *
// * @return The content type of this part
// */
// String getContentType();
//
// /**
// * Returns the name of this part, which equals the name of the form
// * field the part was selected for.
// *
// * @return The name of this part as a String
// */
// String getName();
//
// /**
// * Returns the known size of this part. This means that the
// * returned value depends on how many bytes have been processed. When called
// * during the start of the part processing the returned value will be equal
// * to the specified buffer threshold or the actual part size if it's smaller
// * than that. When called during the end the returned value is always the
// * actual size, because by that time it has been fully processed.
// *
// * @return A long specifying the known size of this part, in bytes.
// */
// long getKnownSize();
//
// /**
// * Returns the file name specified by the client or null if the
// * part is a normal form field.
// *
// * @return The submitted file name
// */
// String getSubmittedFileName();
//
// /**
// * Determines whether or not this PartStream instance represents
// * a file item. If it's a normal form field then it will return false.
// * Consequently, if this returns true then the {@link PartStream#getSubmittedFileName}
// * will return with a non-null value and vice-versa.
// *
// * @return True if the instance represents an uploaded file; false if it represents a simple form field.
// */
// boolean isFile();
//
// /**
// * Returns whether the part has been completely uploaded. The
// * part begin callback is called only after the given size threshold
// * is reached or if the part is completely uploaded. Therefore, the
// * parts that are smaller than the threshold are passed to the part begin
// * callback after their upload is finished and their actual size is known.
// * This method can be used to determine that. In the part end callback
// * this will always return true.
// *
// * @return True if the part is completely uploaded, false otherwise.
// */
// boolean isFinished();
//
// /**
// * Returns the value of the specified mime header as a String. If
// * the Part did not include a header of the specified name, this
// * method returns null. If there are multiple headers with the same name,
// * this method returns the first header in the part. The header name
// * is case insensitive. You can use this method with any request header.
// *
// * @param name a String specifying the header name
// * @return a String containing the value of the requested header, or null if the part does not have a header of that name
// */
// String getHeader(String name);
//
// /**
// * Returns the values of the part header with the given name.
// *
// * @param name the header name whose values to return
// * @return a (possibly empty) Collection of the values of the header with the given name
// */
// Collection<String> getHeaders(String name);
//
// /**
// * Returns the header names of this part.
// *
// * @return a (possibly empty) Collection of the header names of this Part
// */
// Collection<String> getHeaderNames();
//
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.github.elopteryx.upload.PartStream;
import org.junit.jupiter.api.Test; | package com.github.elopteryx.upload.internal;
class PartStreamImplTest {
@Test
void it_should_return_the_correct_data() {
final var fileName = "r-" + System.currentTimeMillis();
final var fieldName = "r-" + System.currentTimeMillis();
final var contentType = "r-" + System.currentTimeMillis();
final var headers = new Headers();
headers.addHeader(Headers.CONTENT_TYPE, contentType); | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/PartStream.java
// public interface PartStream {
//
// /**
// * Returns the content type of this part, as it was submitted by
// * the client.
// *
// * @return The content type of this part
// */
// String getContentType();
//
// /**
// * Returns the name of this part, which equals the name of the form
// * field the part was selected for.
// *
// * @return The name of this part as a String
// */
// String getName();
//
// /**
// * Returns the known size of this part. This means that the
// * returned value depends on how many bytes have been processed. When called
// * during the start of the part processing the returned value will be equal
// * to the specified buffer threshold or the actual part size if it's smaller
// * than that. When called during the end the returned value is always the
// * actual size, because by that time it has been fully processed.
// *
// * @return A long specifying the known size of this part, in bytes.
// */
// long getKnownSize();
//
// /**
// * Returns the file name specified by the client or null if the
// * part is a normal form field.
// *
// * @return The submitted file name
// */
// String getSubmittedFileName();
//
// /**
// * Determines whether or not this PartStream instance represents
// * a file item. If it's a normal form field then it will return false.
// * Consequently, if this returns true then the {@link PartStream#getSubmittedFileName}
// * will return with a non-null value and vice-versa.
// *
// * @return True if the instance represents an uploaded file; false if it represents a simple form field.
// */
// boolean isFile();
//
// /**
// * Returns whether the part has been completely uploaded. The
// * part begin callback is called only after the given size threshold
// * is reached or if the part is completely uploaded. Therefore, the
// * parts that are smaller than the threshold are passed to the part begin
// * callback after their upload is finished and their actual size is known.
// * This method can be used to determine that. In the part end callback
// * this will always return true.
// *
// * @return True if the part is completely uploaded, false otherwise.
// */
// boolean isFinished();
//
// /**
// * Returns the value of the specified mime header as a String. If
// * the Part did not include a header of the specified name, this
// * method returns null. If there are multiple headers with the same name,
// * this method returns the first header in the part. The header name
// * is case insensitive. You can use this method with any request header.
// *
// * @param name a String specifying the header name
// * @return a String containing the value of the requested header, or null if the part does not have a header of that name
// */
// String getHeader(String name);
//
// /**
// * Returns the values of the part header with the given name.
// *
// * @param name the header name whose values to return
// * @return a (possibly empty) Collection of the values of the header with the given name
// */
// Collection<String> getHeaders(String name);
//
// /**
// * Returns the header names of this part.
// *
// * @return a (possibly empty) Collection of the header names of this Part
// */
// Collection<String> getHeaderNames();
//
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/PartStreamImplTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.github.elopteryx.upload.PartStream;
import org.junit.jupiter.api.Test;
package com.github.elopteryx.upload.internal;
class PartStreamImplTest {
@Test
void it_should_return_the_correct_data() {
final var fileName = "r-" + System.currentTimeMillis();
final var fieldName = "r-" + System.currentTimeMillis();
final var contentType = "r-" + System.currentTimeMillis();
final var headers = new Headers();
headers.addHeader(Headers.CONTENT_TYPE, contentType); | final PartStream partStream = new PartStreamImpl(fileName, fieldName, headers); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/JettyIntegrationTest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
| import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import static org.junit.jupiter.api.Assertions.fail;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import jakarta.servlet.http.HttpServletResponse; | package com.github.elopteryx.upload.internal.integration;
class JettyIntegrationTest {
private static Server server;
/**
* Sets up the test environment, generates data to upload, starts a
* Jetty instance which will receive the client requests.
* @throws Exception If an error occurred with the servlets
*/
@BeforeAll
static void setUpClass() throws Exception {
server = new Server(8090);
final var handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(AsyncUploadServlet.class, "/async");
handler.addServletWithMapping(BlockingUploadServlet.class, "/blocking");
server.start();
}
@Test
void test_with_a_real_request_simple_async() {
performRequest("http://localhost:8090/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() {
performRequest("http://localhost:8090/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/JettyIntegrationTest.java
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import static org.junit.jupiter.api.Assertions.fail;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import jakarta.servlet.http.HttpServletResponse;
package com.github.elopteryx.upload.internal.integration;
class JettyIntegrationTest {
private static Server server;
/**
* Sets up the test environment, generates data to upload, starts a
* Jetty instance which will receive the client requests.
* @throws Exception If an error occurred with the servlets
*/
@BeforeAll
static void setUpClass() throws Exception {
server = new Server(8090);
final var handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(AsyncUploadServlet.class, "/async");
handler.addServletWithMapping(BlockingUploadServlet.class, "/blocking");
server.start();
}
@Test
void test_with_a_real_request_simple_async() {
performRequest("http://localhost:8090/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() {
performRequest("http://localhost:8090/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() { | performRequest("http://localhost:8090/async?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture()); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/JettyIntegrationTest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
| import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import static org.junit.jupiter.api.Assertions.fail;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import jakarta.servlet.http.HttpServletResponse; | package com.github.elopteryx.upload.internal.integration;
class JettyIntegrationTest {
private static Server server;
/**
* Sets up the test environment, generates data to upload, starts a
* Jetty instance which will receive the client requests.
* @throws Exception If an error occurred with the servlets
*/
@BeforeAll
static void setUpClass() throws Exception {
server = new Server(8090);
final var handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(AsyncUploadServlet.class, "/async");
handler.addServletWithMapping(BlockingUploadServlet.class, "/blocking");
server.start();
}
@Test
void test_with_a_real_request_simple_async() {
performRequest("http://localhost:8090/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() {
performRequest("http://localhost:8090/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() {
performRequest("http://localhost:8090/async?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_lesser_blocking() {
performRequest("http://localhost:8090/blocking?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_greater_async() { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/JettyIntegrationTest.java
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import static org.junit.jupiter.api.Assertions.fail;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import jakarta.servlet.http.HttpServletResponse;
package com.github.elopteryx.upload.internal.integration;
class JettyIntegrationTest {
private static Server server;
/**
* Sets up the test environment, generates data to upload, starts a
* Jetty instance which will receive the client requests.
* @throws Exception If an error occurred with the servlets
*/
@BeforeAll
static void setUpClass() throws Exception {
server = new Server(8090);
final var handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(AsyncUploadServlet.class, "/async");
handler.addServletWithMapping(BlockingUploadServlet.class, "/blocking");
server.start();
}
@Test
void test_with_a_real_request_simple_async() {
performRequest("http://localhost:8090/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() {
performRequest("http://localhost:8090/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() {
performRequest("http://localhost:8090/async?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_lesser_blocking() {
performRequest("http://localhost:8090/blocking?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_greater_async() { | performRequest("http://localhost:8090/async?" + ClientRequest.THRESHOLD_GREATER, HttpServletResponse.SC_OK, withOneLargerPicture()); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/UndertowIntegrationTest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
| import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.servlet.Servlets;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import jakarta.servlet.http.HttpServletResponse; | .addMapping("/async")
.setAsyncSupported(true),
Servlets.servlet("BlockingUploadServlet", BlockingUploadServlet.class)
.addMapping("/blocking")
.setAsyncSupported(false)
);
final var manager = Servlets.defaultContainer().addDeployment(servletBuilder);
manager.deploy();
final var path = Handlers.path(Handlers.redirect("/")).addPrefixPath("/", manager.start());
server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(path)
.build();
server.start();
}
@Test
void test_with_a_real_request_simple_async() throws IOException {
performRequest("http://localhost:8080/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() throws IOException {
performRequest("http://localhost:8080/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() throws IOException { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/UndertowIntegrationTest.java
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.servlet.Servlets;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import jakarta.servlet.http.HttpServletResponse;
.addMapping("/async")
.setAsyncSupported(true),
Servlets.servlet("BlockingUploadServlet", BlockingUploadServlet.class)
.addMapping("/blocking")
.setAsyncSupported(false)
);
final var manager = Servlets.defaultContainer().addDeployment(servletBuilder);
manager.deploy();
final var path = Handlers.path(Handlers.redirect("/")).addPrefixPath("/", manager.start());
server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(path)
.build();
server.start();
}
@Test
void test_with_a_real_request_simple_async() throws IOException {
performRequest("http://localhost:8080/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() throws IOException {
performRequest("http://localhost:8080/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() throws IOException { | performRequest("http://localhost:8080/async?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture()); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/UndertowIntegrationTest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
| import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.servlet.Servlets;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import jakarta.servlet.http.HttpServletResponse; |
server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(path)
.build();
server.start();
}
@Test
void test_with_a_real_request_simple_async() throws IOException {
performRequest("http://localhost:8080/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() throws IOException {
performRequest("http://localhost:8080/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() throws IOException {
performRequest("http://localhost:8080/async?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_lesser_blocking() throws IOException {
performRequest("http://localhost:8080/blocking?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_greater_async() throws IOException { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/UndertowIntegrationTest.java
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.servlet.Servlets;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import jakarta.servlet.http.HttpServletResponse;
server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(path)
.build();
server.start();
}
@Test
void test_with_a_real_request_simple_async() throws IOException {
performRequest("http://localhost:8080/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() throws IOException {
performRequest("http://localhost:8080/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() throws IOException {
performRequest("http://localhost:8080/async?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_lesser_blocking() throws IOException {
performRequest("http://localhost:8080/blocking?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_greater_async() throws IOException { | performRequest("http://localhost:8080/async?" + ClientRequest.THRESHOLD_GREATER, HttpServletResponse.SC_OK, withOneLargerPicture()); |
Elopteryx/upload-parser | upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/MultipartParser.java | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/MultipartException.java
// public class MultipartException extends IOException {
//
// /**
// * Public constructor.
// * @param message The exception message.
// */
// public MultipartException(final String message) {
// super(message);
// }
// }
| import com.github.elopteryx.upload.errors.MultipartException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset; | if (subState == Integer.MAX_VALUE) {
subState = boundary[2] == b ? 2 : 0;
}
if (b == boundary[subState]) {
subState++;
if (subState == boundary.length) {
subState = -1;
}
} else if (b == boundary[0]) {
subState = 1;
} else {
subState = 0;
}
} else if (subState == -1) {
if (b == CR) {
subState = -2;
}
} else if (subState == -2) {
if (b == LF) {
subState = 0;
state = 1;//preamble is done
headers = new Headers();
return;
} else {
subState = -1;
}
}
}
}
| // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/MultipartException.java
// public class MultipartException extends IOException {
//
// /**
// * Public constructor.
// * @param message The exception message.
// */
// public MultipartException(final String message) {
// super(message);
// }
// }
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/MultipartParser.java
import com.github.elopteryx.upload.errors.MultipartException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
if (subState == Integer.MAX_VALUE) {
subState = boundary[2] == b ? 2 : 0;
}
if (b == boundary[subState]) {
subState++;
if (subState == boundary.length) {
subState = -1;
}
} else if (b == boundary[0]) {
subState = 1;
} else {
subState = 0;
}
} else if (subState == -1) {
if (b == CR) {
subState = -2;
}
} else if (subState == -2) {
if (b == LF) {
subState = 0;
state = 1;//preamble is done
headers = new Headers();
return;
} else {
subState = -1;
}
}
}
}
| private void headerName(final ByteBuffer buffer) throws MultipartException { |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/ClientRequest.java
// static final String BOUNDARY = "--TNoK9riv6EjfMhxBzj22SKGnOaIhZlxhar";
| import static com.github.elopteryx.upload.internal.integration.ClientRequest.BOUNDARY;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random; | package com.github.elopteryx.upload.internal.integration;
/**
* Utility class which is responsible for the request body creation.
*/
final class RequestSupplier {
static final byte[] EMPTY_FILE;
static final byte[] SMALL_FILE;
static final byte[] LARGE_FILE;
static final String TEXT_VALUE_1 = "íéáűúőóüö";
static final String TEXT_VALUE_2 = "abcdef";
static {
EMPTY_FILE = new byte[0];
SMALL_FILE = "0123456789".getBytes(UTF_8);
final var random = new Random();
final var builder = new StringBuilder();
for (var i = 0; i < 100_000; i++) {
builder.append(random.nextInt(100));
}
LARGE_FILE = builder.toString().getBytes(UTF_8);
}
static ByteBuffer withSeveralFields() { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/ClientRequest.java
// static final String BOUNDARY = "--TNoK9riv6EjfMhxBzj22SKGnOaIhZlxhar";
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
import static com.github.elopteryx.upload.internal.integration.ClientRequest.BOUNDARY;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;
package com.github.elopteryx.upload.internal.integration;
/**
* Utility class which is responsible for the request body creation.
*/
final class RequestSupplier {
static final byte[] EMPTY_FILE;
static final byte[] SMALL_FILE;
static final byte[] LARGE_FILE;
static final String TEXT_VALUE_1 = "íéáűúőóüö";
static final String TEXT_VALUE_2 = "abcdef";
static {
EMPTY_FILE = new byte[0];
SMALL_FILE = "0123456789".getBytes(UTF_8);
final var random = new Random();
final var builder = new StringBuilder();
for (var i = 0; i < 100_000; i++) {
builder.append(random.nextInt(100));
}
LARGE_FILE = builder.toString().getBytes(UTF_8);
}
static ByteBuffer withSeveralFields() { | return RequestBuilder.newBuilder(BOUNDARY) |
Elopteryx/upload-parser | upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/BlockingUploadParser.java | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/UploadContext.java
// public interface UploadContext {
//
// /**
// * Returns the given request object for this parser,
// * allowing customization during the stages of the
// * asynchronous processing.
// *
// * @return The request object
// */
// HttpServletRequest getRequest();
//
// /**
// * Returns the given user object for this parser,
// * allowing customization during the stages of the
// * asynchronous processing.
// *
// * @param clazz The class used for casting
// * @param <T> Type parameter
// * @return The user object, or null if it was not supplied
// */
// <T> T getUserObject(Class<T> clazz);
//
// /**
// * Returns the currently processed part stream,
// * allowing the caller to get available information.
// *
// * @return The currently processed part
// */
// PartStream getCurrentPart();
//
// /**
// * Returns the currently active output, which was returned
// * in the latest UploadParser#onPartBegin method. This will
// * return a null during the part begin stage and might be
// * null during the error stage.
// *
// * @return The latest output provided by the caller
// */
// PartOutput getCurrentOutput();
//
// /**
// * Returns the parts which have already been processed. Before
// * the onPartBegin method is called the current PartStream is
// * added into the List returned by this method, meaning that
// * the UploadContext#getCurrentPart will return with the last
// * element of the list.
// * @return The list of the processed parts, in the order they are uploaded
// */
// List<PartStream> getPartStreams();
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/MultipartException.java
// public class MultipartException extends IOException {
//
// /**
// * Public constructor.
// * @param message The exception message.
// */
// public MultipartException(final String message) {
// super(message);
// }
// }
| import com.github.elopteryx.upload.UploadContext;
import com.github.elopteryx.upload.errors.MultipartException;
import java.io.IOException;
import java.io.InputStream;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; | /*
* Copyright (C) 2016 Adam Forgacs
*
* 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.github.elopteryx.upload.internal;
/**
* The blocking implementation of the parser. This parser can be used to perform a
* blocking parse, whether the servlet supports async mode or not.
*/
public final class BlockingUploadParser extends AbstractUploadParser {
/**
* The request object.
*/
private final HttpServletRequest request;
/**
* The stream to read.
*/
private InputStream inputStream;
public BlockingUploadParser(final HttpServletRequest request) {
this.request = request;
}
/**
* Sets up the necessary objects to start the parsing. Depending upon
* the environment the concrete implementations can be very different.
* @throws IOException If an error occurs with the IO
*/
private void init() throws IOException {
init(request);
inputStream = request.getInputStream();
}
/**
* Performs a full parsing and returns the used context object.
* @return The upload context
* @throws IOException If an error occurred with the I/O
* @throws ServletException If an error occurred with the servlet
*/ | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/UploadContext.java
// public interface UploadContext {
//
// /**
// * Returns the given request object for this parser,
// * allowing customization during the stages of the
// * asynchronous processing.
// *
// * @return The request object
// */
// HttpServletRequest getRequest();
//
// /**
// * Returns the given user object for this parser,
// * allowing customization during the stages of the
// * asynchronous processing.
// *
// * @param clazz The class used for casting
// * @param <T> Type parameter
// * @return The user object, or null if it was not supplied
// */
// <T> T getUserObject(Class<T> clazz);
//
// /**
// * Returns the currently processed part stream,
// * allowing the caller to get available information.
// *
// * @return The currently processed part
// */
// PartStream getCurrentPart();
//
// /**
// * Returns the currently active output, which was returned
// * in the latest UploadParser#onPartBegin method. This will
// * return a null during the part begin stage and might be
// * null during the error stage.
// *
// * @return The latest output provided by the caller
// */
// PartOutput getCurrentOutput();
//
// /**
// * Returns the parts which have already been processed. Before
// * the onPartBegin method is called the current PartStream is
// * added into the List returned by this method, meaning that
// * the UploadContext#getCurrentPart will return with the last
// * element of the list.
// * @return The list of the processed parts, in the order they are uploaded
// */
// List<PartStream> getPartStreams();
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/MultipartException.java
// public class MultipartException extends IOException {
//
// /**
// * Public constructor.
// * @param message The exception message.
// */
// public MultipartException(final String message) {
// super(message);
// }
// }
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/BlockingUploadParser.java
import com.github.elopteryx.upload.UploadContext;
import com.github.elopteryx.upload.errors.MultipartException;
import java.io.IOException;
import java.io.InputStream;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
/*
* Copyright (C) 2016 Adam Forgacs
*
* 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.github.elopteryx.upload.internal;
/**
* The blocking implementation of the parser. This parser can be used to perform a
* blocking parse, whether the servlet supports async mode or not.
*/
public final class BlockingUploadParser extends AbstractUploadParser {
/**
* The request object.
*/
private final HttpServletRequest request;
/**
* The stream to read.
*/
private InputStream inputStream;
public BlockingUploadParser(final HttpServletRequest request) {
this.request = request;
}
/**
* Sets up the necessary objects to start the parsing. Depending upon
* the environment the concrete implementations can be very different.
* @throws IOException If an error occurs with the IO
*/
private void init() throws IOException {
init(request);
inputStream = request.getInputStream();
}
/**
* Performs a full parsing and returns the used context object.
* @return The upload context
* @throws IOException If an error occurred with the I/O
* @throws ServletException If an error occurred with the servlet
*/ | public UploadContext doBlockingParse() throws IOException, ServletException { |
Elopteryx/upload-parser | upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/BlockingUploadParser.java | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/UploadContext.java
// public interface UploadContext {
//
// /**
// * Returns the given request object for this parser,
// * allowing customization during the stages of the
// * asynchronous processing.
// *
// * @return The request object
// */
// HttpServletRequest getRequest();
//
// /**
// * Returns the given user object for this parser,
// * allowing customization during the stages of the
// * asynchronous processing.
// *
// * @param clazz The class used for casting
// * @param <T> Type parameter
// * @return The user object, or null if it was not supplied
// */
// <T> T getUserObject(Class<T> clazz);
//
// /**
// * Returns the currently processed part stream,
// * allowing the caller to get available information.
// *
// * @return The currently processed part
// */
// PartStream getCurrentPart();
//
// /**
// * Returns the currently active output, which was returned
// * in the latest UploadParser#onPartBegin method. This will
// * return a null during the part begin stage and might be
// * null during the error stage.
// *
// * @return The latest output provided by the caller
// */
// PartOutput getCurrentOutput();
//
// /**
// * Returns the parts which have already been processed. Before
// * the onPartBegin method is called the current PartStream is
// * added into the List returned by this method, meaning that
// * the UploadContext#getCurrentPart will return with the last
// * element of the list.
// * @return The list of the processed parts, in the order they are uploaded
// */
// List<PartStream> getPartStreams();
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/MultipartException.java
// public class MultipartException extends IOException {
//
// /**
// * Public constructor.
// * @param message The exception message.
// */
// public MultipartException(final String message) {
// super(message);
// }
// }
| import com.github.elopteryx.upload.UploadContext;
import com.github.elopteryx.upload.errors.MultipartException;
import java.io.IOException;
import java.io.InputStream;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; | * @throws ServletException If an error occurred with the servlet
*/
public UploadContext doBlockingParse() throws IOException, ServletException {
init();
try {
blockingRead();
if (requestCallback != null) {
requestCallback.onRequestComplete(context);
}
} catch (final Exception e) {
if (errorCallback != null) {
errorCallback.onError(context, e);
}
}
return context;
}
/**
* Reads everything from the input stream in a blocking mode. It will
* throw an exception if the data is malformed, for example
* it is not closed with the proper characters.
* @throws IOException If an error occurred with the I/O
*/
private void blockingRead() throws IOException {
while (true) {
final var count = inputStream.read(dataBuffer.array());
if (count == -1) {
if (parseState.isComplete()) {
break;
} else { | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/UploadContext.java
// public interface UploadContext {
//
// /**
// * Returns the given request object for this parser,
// * allowing customization during the stages of the
// * asynchronous processing.
// *
// * @return The request object
// */
// HttpServletRequest getRequest();
//
// /**
// * Returns the given user object for this parser,
// * allowing customization during the stages of the
// * asynchronous processing.
// *
// * @param clazz The class used for casting
// * @param <T> Type parameter
// * @return The user object, or null if it was not supplied
// */
// <T> T getUserObject(Class<T> clazz);
//
// /**
// * Returns the currently processed part stream,
// * allowing the caller to get available information.
// *
// * @return The currently processed part
// */
// PartStream getCurrentPart();
//
// /**
// * Returns the currently active output, which was returned
// * in the latest UploadParser#onPartBegin method. This will
// * return a null during the part begin stage and might be
// * null during the error stage.
// *
// * @return The latest output provided by the caller
// */
// PartOutput getCurrentOutput();
//
// /**
// * Returns the parts which have already been processed. Before
// * the onPartBegin method is called the current PartStream is
// * added into the List returned by this method, meaning that
// * the UploadContext#getCurrentPart will return with the last
// * element of the list.
// * @return The list of the processed parts, in the order they are uploaded
// */
// List<PartStream> getPartStreams();
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/MultipartException.java
// public class MultipartException extends IOException {
//
// /**
// * Public constructor.
// * @param message The exception message.
// */
// public MultipartException(final String message) {
// super(message);
// }
// }
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/BlockingUploadParser.java
import com.github.elopteryx.upload.UploadContext;
import com.github.elopteryx.upload.errors.MultipartException;
import java.io.IOException;
import java.io.InputStream;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
* @throws ServletException If an error occurred with the servlet
*/
public UploadContext doBlockingParse() throws IOException, ServletException {
init();
try {
blockingRead();
if (requestCallback != null) {
requestCallback.onRequestComplete(context);
}
} catch (final Exception e) {
if (errorCallback != null) {
errorCallback.onError(context, e);
}
}
return context;
}
/**
* Reads everything from the input stream in a blocking mode. It will
* throw an exception if the data is malformed, for example
* it is not closed with the proper characters.
* @throws IOException If an error occurred with the I/O
*/
private void blockingRead() throws IOException {
while (true) {
final var count = inputStream.read(dataBuffer.array());
if (count == -1) {
if (parseState.isComplete()) {
break;
} else { | throw new MultipartException("Stream ended unexpectedly!"); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/UploadParserTest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/util/NullChannel.java
// public class NullChannel implements ReadableByteChannel, WritableByteChannel {
//
// /**
// * Flag to determine whether the channel is closed or not.
// */
// private boolean open = true;
//
// @Override
// public int read(final ByteBuffer dst) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// return -1;
// }
//
// @Override
// public int write(final ByteBuffer src) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// final var remaining = src.remaining();
// src.position(src.limit());
// return remaining;
// }
//
// @Override
// public boolean isOpen() {
// return open;
// }
//
// @Override
// public void close() {
// open = false;
// }
// }
| import static com.github.elopteryx.upload.util.Servlets.newRequest;
import static com.github.elopteryx.upload.util.Servlets.newResponse;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.util.NullChannel;
import com.google.common.jimfs.Jimfs;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletResponse; | package com.github.elopteryx.upload;
class UploadParserTest implements OnPartBegin, OnPartEnd, OnRequestComplete, OnError {
private static FileSystem fileSystem;
@BeforeAll
static void setUp() {
fileSystem = Jimfs.newFileSystem();
}
@Test
void valid_content_type() throws Exception { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/util/NullChannel.java
// public class NullChannel implements ReadableByteChannel, WritableByteChannel {
//
// /**
// * Flag to determine whether the channel is closed or not.
// */
// private boolean open = true;
//
// @Override
// public int read(final ByteBuffer dst) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// return -1;
// }
//
// @Override
// public int write(final ByteBuffer src) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// final var remaining = src.remaining();
// src.position(src.limit());
// return remaining;
// }
//
// @Override
// public boolean isOpen() {
// return open;
// }
//
// @Override
// public void close() {
// open = false;
// }
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/UploadParserTest.java
import static com.github.elopteryx.upload.util.Servlets.newRequest;
import static com.github.elopteryx.upload.util.Servlets.newResponse;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.util.NullChannel;
import com.google.common.jimfs.Jimfs;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletResponse;
package com.github.elopteryx.upload;
class UploadParserTest implements OnPartBegin, OnPartEnd, OnRequestComplete, OnError {
private static FileSystem fileSystem;
@BeforeAll
static void setUp() {
fileSystem = Jimfs.newFileSystem();
}
@Test
void valid_content_type() throws Exception { | final var request = newRequest(); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/UploadParserTest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/util/NullChannel.java
// public class NullChannel implements ReadableByteChannel, WritableByteChannel {
//
// /**
// * Flag to determine whether the channel is closed or not.
// */
// private boolean open = true;
//
// @Override
// public int read(final ByteBuffer dst) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// return -1;
// }
//
// @Override
// public int write(final ByteBuffer src) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// final var remaining = src.remaining();
// src.position(src.limit());
// return remaining;
// }
//
// @Override
// public boolean isOpen() {
// return open;
// }
//
// @Override
// public void close() {
// open = false;
// }
// }
| import static com.github.elopteryx.upload.util.Servlets.newRequest;
import static com.github.elopteryx.upload.util.Servlets.newResponse;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.util.NullChannel;
import com.google.common.jimfs.Jimfs;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletResponse; | package com.github.elopteryx.upload;
class UploadParserTest implements OnPartBegin, OnPartEnd, OnRequestComplete, OnError {
private static FileSystem fileSystem;
@BeforeAll
static void setUp() {
fileSystem = Jimfs.newFileSystem();
}
@Test
void valid_content_type() throws Exception {
final var request = newRequest();
when(request.getContentType()).thenReturn("multipart/");
assertTrue(UploadParser.isMultipart(request));
}
@Test
void invalid_numeric_arguments() {
assertAll(
() -> assertThrows(IllegalArgumentException.class, () -> UploadParser.newParser().sizeThreshold(-1)),
() -> assertThrows(IllegalArgumentException.class, () -> UploadParser.newParser().maxPartSize(-1)),
() -> assertThrows(IllegalArgumentException.class, () -> UploadParser.newParser().maxRequestSize(-1)),
() -> assertThrows(IllegalArgumentException.class, () -> UploadParser.newParser().maxBytesUsed(-1))
);
}
@Test
void invalid_content_type_async() throws Exception {
final var request = newRequest();
when(request.getContentType()).thenReturn("text/plain;charset=UTF-8");
assertFalse(UploadParser.isMultipart(request)); | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/util/NullChannel.java
// public class NullChannel implements ReadableByteChannel, WritableByteChannel {
//
// /**
// * Flag to determine whether the channel is closed or not.
// */
// private boolean open = true;
//
// @Override
// public int read(final ByteBuffer dst) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// return -1;
// }
//
// @Override
// public int write(final ByteBuffer src) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// final var remaining = src.remaining();
// src.position(src.limit());
// return remaining;
// }
//
// @Override
// public boolean isOpen() {
// return open;
// }
//
// @Override
// public void close() {
// open = false;
// }
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/UploadParserTest.java
import static com.github.elopteryx.upload.util.Servlets.newRequest;
import static com.github.elopteryx.upload.util.Servlets.newResponse;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.util.NullChannel;
import com.google.common.jimfs.Jimfs;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletResponse;
package com.github.elopteryx.upload;
class UploadParserTest implements OnPartBegin, OnPartEnd, OnRequestComplete, OnError {
private static FileSystem fileSystem;
@BeforeAll
static void setUp() {
fileSystem = Jimfs.newFileSystem();
}
@Test
void valid_content_type() throws Exception {
final var request = newRequest();
when(request.getContentType()).thenReturn("multipart/");
assertTrue(UploadParser.isMultipart(request));
}
@Test
void invalid_numeric_arguments() {
assertAll(
() -> assertThrows(IllegalArgumentException.class, () -> UploadParser.newParser().sizeThreshold(-1)),
() -> assertThrows(IllegalArgumentException.class, () -> UploadParser.newParser().maxPartSize(-1)),
() -> assertThrows(IllegalArgumentException.class, () -> UploadParser.newParser().maxRequestSize(-1)),
() -> assertThrows(IllegalArgumentException.class, () -> UploadParser.newParser().maxBytesUsed(-1))
);
}
@Test
void invalid_content_type_async() throws Exception {
final var request = newRequest();
when(request.getContentType()).thenReturn("text/plain;charset=UTF-8");
assertFalse(UploadParser.isMultipart(request)); | assertThrows(IllegalArgumentException.class, () -> UploadParser.newParser().userObject(newResponse()).setupAsyncParse(request)); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/UploadParserTest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/util/NullChannel.java
// public class NullChannel implements ReadableByteChannel, WritableByteChannel {
//
// /**
// * Flag to determine whether the channel is closed or not.
// */
// private boolean open = true;
//
// @Override
// public int read(final ByteBuffer dst) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// return -1;
// }
//
// @Override
// public int write(final ByteBuffer src) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// final var remaining = src.remaining();
// src.position(src.limit());
// return remaining;
// }
//
// @Override
// public boolean isOpen() {
// return open;
// }
//
// @Override
// public void close() {
// open = false;
// }
// }
| import static com.github.elopteryx.upload.util.Servlets.newRequest;
import static com.github.elopteryx.upload.util.Servlets.newResponse;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.util.NullChannel;
import com.google.common.jimfs.Jimfs;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletResponse; | final var test = fileSystem.getPath("test2");
Files.createFile(test);
return PartOutput.from(Files.newOutputStream(test));
});
}
@Test
void output_path() {
UploadParser.newParser()
.onPartBegin((context, buffer) -> {
final var test = fileSystem.getPath("test2");
Files.createFile(test);
return PartOutput.from(test);
});
}
@Test
void use_with_custom_object() {
UploadParser.newParser()
.userObject(newResponse())
.onPartBegin((context, buffer) -> {
final var test = fileSystem.getPath("test2");
Files.createFile(test);
return PartOutput.from(test);
})
.onRequestComplete(context -> context.getUserObject(HttpServletResponse.class).setStatus(HttpServletResponse.SC_OK));
}
@Override
public PartOutput onPartBegin(final UploadContext context, final ByteBuffer buffer) { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/util/NullChannel.java
// public class NullChannel implements ReadableByteChannel, WritableByteChannel {
//
// /**
// * Flag to determine whether the channel is closed or not.
// */
// private boolean open = true;
//
// @Override
// public int read(final ByteBuffer dst) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// return -1;
// }
//
// @Override
// public int write(final ByteBuffer src) throws IOException {
// if (!open) {
// throw new ClosedChannelException();
// }
// final var remaining = src.remaining();
// src.position(src.limit());
// return remaining;
// }
//
// @Override
// public boolean isOpen() {
// return open;
// }
//
// @Override
// public void close() {
// open = false;
// }
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/UploadParserTest.java
import static com.github.elopteryx.upload.util.Servlets.newRequest;
import static com.github.elopteryx.upload.util.Servlets.newResponse;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.util.NullChannel;
import com.google.common.jimfs.Jimfs;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletResponse;
final var test = fileSystem.getPath("test2");
Files.createFile(test);
return PartOutput.from(Files.newOutputStream(test));
});
}
@Test
void output_path() {
UploadParser.newParser()
.onPartBegin((context, buffer) -> {
final var test = fileSystem.getPath("test2");
Files.createFile(test);
return PartOutput.from(test);
});
}
@Test
void use_with_custom_object() {
UploadParser.newParser()
.userObject(newResponse())
.onPartBegin((context, buffer) -> {
final var test = fileSystem.getPath("test2");
Files.createFile(test);
return PartOutput.from(test);
})
.onRequestComplete(context -> context.getUserObject(HttpServletResponse.class).setStatus(HttpServletResponse.SC_OK));
}
@Override
public PartOutput onPartBegin(final UploadContext context, final ByteBuffer buffer) { | return PartOutput.from(new NullChannel()); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/ClientRequest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withSeveralFields() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield1", LARGE_FILE, "application/octet-stream", "file1.txt")
// .addFilePart("filefield2", EMPTY_FILE, "text/plain", "file2.txt")
// .addFilePart("filefield3", SMALL_FILE, "application/octet-stream", "file3.txt")
// .addFormField("textfield1", TEXT_VALUE_1)
// .addFormField("textfield2", TEXT_VALUE_2)
// .addFilePart("filefield4", getContents("test.xlsx"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "test.xlsx")
// .addFilePart("filefield5", getContents("test.docx"), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "test.docx")
// .addFilePart("filefield6", getContents("test.jpg"), "image/jpeg", "test.jpg")
// .finish();
// }
| import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withSeveralFields;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.common.jimfs.Jimfs;
import org.apache.tika.Tika;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.time.Duration; | package com.github.elopteryx.upload.internal.integration;
/**
* Utility class for making multipart requests.
*/
public final class ClientRequest {
static final String BOUNDARY = "--TNoK9riv6EjfMhxBzj22SKGnOaIhZlxhar";
static final String SIMPLE = "simple";
static final String THRESHOLD_LESSER = "threshold_lesser";
static final String THRESHOLD_GREATER = "threshold_greater";
static final String ERROR = "error";
static final String IO_ERROR_UPON_ERROR = "io_error_upon_error";
static final String SERVLET_ERROR_UPON_ERROR = "servlet_error_upon_error";
static final String COMPLEX = "complex";
static final FileSystem FILE_SYSTEM = Jimfs.newFileSystem();
static final Tika TIKA = new Tika();
/**
* Creates and sends a randomized multipart request for the
* given address.
* @param url The target address
* @param expectedStatus The expected HTTP response, can be null
* @throws IOException If an IO error occurred
*/
public static void performRequest(final String url, final Integer expectedStatus) throws IOException { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withSeveralFields() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield1", LARGE_FILE, "application/octet-stream", "file1.txt")
// .addFilePart("filefield2", EMPTY_FILE, "text/plain", "file2.txt")
// .addFilePart("filefield3", SMALL_FILE, "application/octet-stream", "file3.txt")
// .addFormField("textfield1", TEXT_VALUE_1)
// .addFormField("textfield2", TEXT_VALUE_2)
// .addFilePart("filefield4", getContents("test.xlsx"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "test.xlsx")
// .addFilePart("filefield5", getContents("test.docx"), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "test.docx")
// .addFilePart("filefield6", getContents("test.jpg"), "image/jpeg", "test.jpg")
// .finish();
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/ClientRequest.java
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withSeveralFields;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.google.common.jimfs.Jimfs;
import org.apache.tika.Tika;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.time.Duration;
package com.github.elopteryx.upload.internal.integration;
/**
* Utility class for making multipart requests.
*/
public final class ClientRequest {
static final String BOUNDARY = "--TNoK9riv6EjfMhxBzj22SKGnOaIhZlxhar";
static final String SIMPLE = "simple";
static final String THRESHOLD_LESSER = "threshold_lesser";
static final String THRESHOLD_GREATER = "threshold_greater";
static final String ERROR = "error";
static final String IO_ERROR_UPON_ERROR = "io_error_upon_error";
static final String SERVLET_ERROR_UPON_ERROR = "servlet_error_upon_error";
static final String COMPLEX = "complex";
static final FileSystem FILE_SYSTEM = Jimfs.newFileSystem();
static final Tika TIKA = new Tika();
/**
* Creates and sends a randomized multipart request for the
* given address.
* @param url The target address
* @param expectedStatus The expected HTTP response, can be null
* @throws IOException If an IO error occurred
*/
public static void performRequest(final String url, final Integer expectedStatus) throws IOException { | performRequest(url, expectedStatus, withSeveralFields()); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/TomcatIntegrationTest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
| import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import static org.junit.jupiter.api.Assertions.fail;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import jakarta.servlet.http.HttpServletResponse; | server.setBaseDir("build/tomcat");
server.getHost().setAppBase("build/tomcat");
server.getHost().setAutoDeploy(true);
server.getHost().setDeployOnStartup(true);
final var context = (StandardContext) server.addWebapp("", base.toAbsolutePath().toString());
final var additionWebInfClasses = Paths.get("build/classes");
final WebResourceRoot resources = new StandardRoot(context);
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes",
additionWebInfClasses.toAbsolutePath().toString(), "/"));
context.setResources(resources);
context.getJarScanner().setJarScanFilter((jarScanType, jarName) -> false);
server.getConnector();
server.start();
}
@Test
void test_with_a_real_request_simple_async() {
performRequest("http://localhost:8100/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() {
performRequest("http://localhost:8100/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/TomcatIntegrationTest.java
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import static org.junit.jupiter.api.Assertions.fail;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import jakarta.servlet.http.HttpServletResponse;
server.setBaseDir("build/tomcat");
server.getHost().setAppBase("build/tomcat");
server.getHost().setAutoDeploy(true);
server.getHost().setDeployOnStartup(true);
final var context = (StandardContext) server.addWebapp("", base.toAbsolutePath().toString());
final var additionWebInfClasses = Paths.get("build/classes");
final WebResourceRoot resources = new StandardRoot(context);
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes",
additionWebInfClasses.toAbsolutePath().toString(), "/"));
context.setResources(resources);
context.getJarScanner().setJarScanFilter((jarScanType, jarName) -> false);
server.getConnector();
server.start();
}
@Test
void test_with_a_real_request_simple_async() {
performRequest("http://localhost:8100/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() {
performRequest("http://localhost:8100/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() { | performRequest("http://localhost:8100/async?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture()); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/TomcatIntegrationTest.java | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
| import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import static org.junit.jupiter.api.Assertions.fail;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import jakarta.servlet.http.HttpServletResponse; | additionWebInfClasses.toAbsolutePath().toString(), "/"));
context.setResources(resources);
context.getJarScanner().setJarScanFilter((jarScanType, jarName) -> false);
server.getConnector();
server.start();
}
@Test
void test_with_a_real_request_simple_async() {
performRequest("http://localhost:8100/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() {
performRequest("http://localhost:8100/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() {
performRequest("http://localhost:8100/async?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_lesser_blocking() {
performRequest("http://localhost:8100/blocking?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_greater_async() { | // Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneLargerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[2048], "image/jpeg", "test.jpg")
// .finish();
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/RequestSupplier.java
// static ByteBuffer withOneSmallerPicture() {
// return RequestBuilder.newBuilder(BOUNDARY)
// .addFilePart("filefield", new byte[512], "image/jpeg", "test.jpg")
// .finish();
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/integration/TomcatIntegrationTest.java
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneLargerPicture;
import static com.github.elopteryx.upload.internal.integration.RequestSupplier.withOneSmallerPicture;
import static org.junit.jupiter.api.Assertions.fail;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import jakarta.servlet.http.HttpServletResponse;
additionWebInfClasses.toAbsolutePath().toString(), "/"));
context.setResources(resources);
context.getJarScanner().setJarScanFilter((jarScanType, jarName) -> false);
server.getConnector();
server.start();
}
@Test
void test_with_a_real_request_simple_async() {
performRequest("http://localhost:8100/async?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_simple_blocking() {
performRequest("http://localhost:8100/blocking?" + ClientRequest.SIMPLE, HttpServletResponse.SC_OK);
}
@Test
void test_with_a_real_request_threshold_lesser_async() {
performRequest("http://localhost:8100/async?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_lesser_blocking() {
performRequest("http://localhost:8100/blocking?" + ClientRequest.THRESHOLD_LESSER, HttpServletResponse.SC_OK, withOneSmallerPicture());
}
@Test
void test_with_a_real_request_threshold_greater_async() { | performRequest("http://localhost:8100/async?" + ClientRequest.THRESHOLD_GREATER, HttpServletResponse.SC_OK, withOneLargerPicture()); |
Elopteryx/upload-parser | upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/AsyncUploadParser.java | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/MultipartException.java
// public class MultipartException extends IOException {
//
// /**
// * Public constructor.
// * @param message The exception message.
// */
// public MultipartException(final String message) {
// super(message);
// }
// }
| import static java.util.Objects.requireNonNull;
import com.github.elopteryx.upload.errors.MultipartException;
import java.io.IOException;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest; | servletInputStream.setReadListener(this);
}
/**
* When an instance of the ReadListener is registered with a ServletInputStream, this method will be invoked
* by the container the first time when it is possible to read data. Subsequently the container will invoke
* this method if and only if ServletInputStream.isReady() method has been called and has returned false.
* @throws IOException if an I/O related error has occurred during processing
*/
@Override
public void onDataAvailable() throws IOException {
while (servletInputStream.isReady() && !servletInputStream.isFinished()) {
parseCurrentItem();
}
}
/**
* Parses the servlet stream once. Will switch to a new item
* if the current one is fully read.
*
* @return Whether it should be called again
* @throws IOException if an I/O related error has occurred during processing
*/
private boolean parseCurrentItem() throws IOException {
var count = -1;
if (!servletInputStream.isFinished()) {
count = servletInputStream.read(dataBuffer.array());
}
if (count == -1) {
if (!parseState.isComplete()) { | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/MultipartException.java
// public class MultipartException extends IOException {
//
// /**
// * Public constructor.
// * @param message The exception message.
// */
// public MultipartException(final String message) {
// super(message);
// }
// }
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/internal/AsyncUploadParser.java
import static java.util.Objects.requireNonNull;
import com.github.elopteryx.upload.errors.MultipartException;
import java.io.IOException;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
servletInputStream.setReadListener(this);
}
/**
* When an instance of the ReadListener is registered with a ServletInputStream, this method will be invoked
* by the container the first time when it is possible to read data. Subsequently the container will invoke
* this method if and only if ServletInputStream.isReady() method has been called and has returned false.
* @throws IOException if an I/O related error has occurred during processing
*/
@Override
public void onDataAvailable() throws IOException {
while (servletInputStream.isReady() && !servletInputStream.isFinished()) {
parseCurrentItem();
}
}
/**
* Parses the servlet stream once. Will switch to a new item
* if the current one is fully read.
*
* @return Whether it should be called again
* @throws IOException if an I/O related error has occurred during processing
*/
private boolean parseCurrentItem() throws IOException {
var count = -1;
if (!servletInputStream.isFinished()) {
count = servletInputStream.read(dataBuffer.array());
}
if (count == -1) {
if (!parseState.isComplete()) { | throw new MultipartException("Stream ended unexpectedly!"); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/AbstractUploadParserTest.java | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/PartSizeException.java
// public class PartSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception
// * @param permitted The maximum permitted size
// */
// public PartSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/RequestSizeException.java
// public class RequestSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception in bytes
// * @param permitted The maximum permitted size in bytes
// */
// public RequestSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public final class Servlets {
//
// private Servlets() {
// // No need to instantiate
// }
//
// /**
// * Creates a new mock servlet request.
// * @return The mocked request.
// * @throws Exception If an error occurred
// */
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// /**
// * Creates a new mock servlet response.
// * @return The mocked response.
// */
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.errors.PartSizeException;
import com.github.elopteryx.upload.errors.RequestSizeException;
import com.github.elopteryx.upload.util.Servlets;
import org.junit.jupiter.api.Test; | package com.github.elopteryx.upload.internal;
class AbstractUploadParserTest {
private static final long SIZE = 1024 * 1024 * 100L;
private static final long SMALL_SIZE = 1024;
private AbstractUploadParser runSetupForSize(final long requestSize, final long allowedRequestSize, final long allowedPartSize) throws Exception { | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/PartSizeException.java
// public class PartSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception
// * @param permitted The maximum permitted size
// */
// public PartSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/RequestSizeException.java
// public class RequestSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception in bytes
// * @param permitted The maximum permitted size in bytes
// */
// public RequestSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public final class Servlets {
//
// private Servlets() {
// // No need to instantiate
// }
//
// /**
// * Creates a new mock servlet request.
// * @return The mocked request.
// * @throws Exception If an error occurred
// */
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// /**
// * Creates a new mock servlet response.
// * @return The mocked response.
// */
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/AbstractUploadParserTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.errors.PartSizeException;
import com.github.elopteryx.upload.errors.RequestSizeException;
import com.github.elopteryx.upload.util.Servlets;
import org.junit.jupiter.api.Test;
package com.github.elopteryx.upload.internal;
class AbstractUploadParserTest {
private static final long SIZE = 1024 * 1024 * 100L;
private static final long SMALL_SIZE = 1024;
private AbstractUploadParser runSetupForSize(final long requestSize, final long allowedRequestSize, final long allowedPartSize) throws Exception { | final var request = Servlets.newRequest(); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/AbstractUploadParserTest.java | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/PartSizeException.java
// public class PartSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception
// * @param permitted The maximum permitted size
// */
// public PartSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/RequestSizeException.java
// public class RequestSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception in bytes
// * @param permitted The maximum permitted size in bytes
// */
// public RequestSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public final class Servlets {
//
// private Servlets() {
// // No need to instantiate
// }
//
// /**
// * Creates a new mock servlet request.
// * @return The mocked request.
// * @throws Exception If an error occurred
// */
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// /**
// * Creates a new mock servlet response.
// * @return The mocked response.
// */
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.errors.PartSizeException;
import com.github.elopteryx.upload.errors.RequestSizeException;
import com.github.elopteryx.upload.util.Servlets;
import org.junit.jupiter.api.Test; | package com.github.elopteryx.upload.internal;
class AbstractUploadParserTest {
private static final long SIZE = 1024 * 1024 * 100L;
private static final long SMALL_SIZE = 1024;
private AbstractUploadParser runSetupForSize(final long requestSize, final long allowedRequestSize, final long allowedPartSize) throws Exception {
final var request = Servlets.newRequest();
when(request.getContentLengthLong()).thenReturn(requestSize);
final var parser = new AsyncUploadParser(request);
parser.setMaxPartSize(allowedPartSize);
parser.setMaxRequestSize(allowedRequestSize);
parser.setupAsyncParse();
return parser;
}
@Test
void setup_should_work_if_lesser() throws Exception {
runSetupForSize(SIZE - 1, SIZE, -1);
}
@Test
void setup_should_work_if_equals() throws Exception {
runSetupForSize(SIZE, SIZE, -1);
}
@Test
void setup_should_throw_size_exception_if_greater() { | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/PartSizeException.java
// public class PartSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception
// * @param permitted The maximum permitted size
// */
// public PartSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/RequestSizeException.java
// public class RequestSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception in bytes
// * @param permitted The maximum permitted size in bytes
// */
// public RequestSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public final class Servlets {
//
// private Servlets() {
// // No need to instantiate
// }
//
// /**
// * Creates a new mock servlet request.
// * @return The mocked request.
// * @throws Exception If an error occurred
// */
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// /**
// * Creates a new mock servlet response.
// * @return The mocked response.
// */
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/AbstractUploadParserTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.errors.PartSizeException;
import com.github.elopteryx.upload.errors.RequestSizeException;
import com.github.elopteryx.upload.util.Servlets;
import org.junit.jupiter.api.Test;
package com.github.elopteryx.upload.internal;
class AbstractUploadParserTest {
private static final long SIZE = 1024 * 1024 * 100L;
private static final long SMALL_SIZE = 1024;
private AbstractUploadParser runSetupForSize(final long requestSize, final long allowedRequestSize, final long allowedPartSize) throws Exception {
final var request = Servlets.newRequest();
when(request.getContentLengthLong()).thenReturn(requestSize);
final var parser = new AsyncUploadParser(request);
parser.setMaxPartSize(allowedPartSize);
parser.setMaxRequestSize(allowedRequestSize);
parser.setupAsyncParse();
return parser;
}
@Test
void setup_should_work_if_lesser() throws Exception {
runSetupForSize(SIZE - 1, SIZE, -1);
}
@Test
void setup_should_work_if_equals() throws Exception {
runSetupForSize(SIZE, SIZE, -1);
}
@Test
void setup_should_throw_size_exception_if_greater() { | assertThrows(RequestSizeException.class, () -> runSetupForSize(SIZE + 1, SIZE, -1)); |
Elopteryx/upload-parser | upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/AbstractUploadParserTest.java | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/PartSizeException.java
// public class PartSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception
// * @param permitted The maximum permitted size
// */
// public PartSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/RequestSizeException.java
// public class RequestSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception in bytes
// * @param permitted The maximum permitted size in bytes
// */
// public RequestSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public final class Servlets {
//
// private Servlets() {
// // No need to instantiate
// }
//
// /**
// * Creates a new mock servlet request.
// * @return The mocked request.
// * @throws Exception If an error occurred
// */
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// /**
// * Creates a new mock servlet response.
// * @return The mocked response.
// */
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
// }
| import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.errors.PartSizeException;
import com.github.elopteryx.upload.errors.RequestSizeException;
import com.github.elopteryx.upload.util.Servlets;
import org.junit.jupiter.api.Test; |
@Test
void setup_should_work_if_lesser() throws Exception {
runSetupForSize(SIZE - 1, SIZE, -1);
}
@Test
void setup_should_work_if_equals() throws Exception {
runSetupForSize(SIZE, SIZE, -1);
}
@Test
void setup_should_throw_size_exception_if_greater() {
assertThrows(RequestSizeException.class, () -> runSetupForSize(SIZE + 1, SIZE, -1));
}
@Test
void parser_should_throw_exception_for_request_size() {
final var exception = assertThrows(RequestSizeException.class, () -> {
final var parser = runSetupForSize(0, SMALL_SIZE, -1);
for (var i = 0; i < 11; i++) {
parser.checkRequestSize(100);
}
});
assertEquals(exception.getPermittedSize(), SMALL_SIZE);
assertTrue(exception.getActualSize() > SMALL_SIZE);
}
@Test
void parser_should_throw_exception_for_part_size() { | // Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/PartSizeException.java
// public class PartSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception
// * @param permitted The maximum permitted size
// */
// public PartSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-core/src/main/java/com/github/elopteryx/upload/errors/RequestSizeException.java
// public class RequestSizeException extends UploadSizeException {
//
// /**
// * Public constructor.
// * @param message The message of the exception
// * @param actual The known size at the time of the exception in bytes
// * @param permitted The maximum permitted size in bytes
// */
// public RequestSizeException(final String message, final long actual, final long permitted) {
// super(message, actual, permitted);
// }
// }
//
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/util/Servlets.java
// public final class Servlets {
//
// private Servlets() {
// // No need to instantiate
// }
//
// /**
// * Creates a new mock servlet request.
// * @return The mocked request.
// * @throws Exception If an error occurred
// */
// public static HttpServletRequest newRequest() throws Exception {
// final var request = mock(HttpServletRequest.class);
//
// when(request.getMethod()).thenReturn("POST");
// when(request.getContentType()).thenReturn("multipart/");
// when(request.getContentLengthLong()).thenReturn(1024 * 1024L);
// when(request.getInputStream()).thenReturn(new MockServletInputStream());
// when(request.isAsyncSupported()).thenReturn(true);
//
// return request;
// }
//
// /**
// * Creates a new mock servlet response.
// * @return The mocked response.
// */
// public static HttpServletResponse newResponse() {
// final var response = mock(HttpServletResponse.class);
//
// when(response.getStatus()).thenReturn(200);
//
// return response;
// }
// }
// Path: upload-parser-tests/src/test/java/com/github/elopteryx/upload/internal/AbstractUploadParserTest.java
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import com.github.elopteryx.upload.errors.PartSizeException;
import com.github.elopteryx.upload.errors.RequestSizeException;
import com.github.elopteryx.upload.util.Servlets;
import org.junit.jupiter.api.Test;
@Test
void setup_should_work_if_lesser() throws Exception {
runSetupForSize(SIZE - 1, SIZE, -1);
}
@Test
void setup_should_work_if_equals() throws Exception {
runSetupForSize(SIZE, SIZE, -1);
}
@Test
void setup_should_throw_size_exception_if_greater() {
assertThrows(RequestSizeException.class, () -> runSetupForSize(SIZE + 1, SIZE, -1));
}
@Test
void parser_should_throw_exception_for_request_size() {
final var exception = assertThrows(RequestSizeException.class, () -> {
final var parser = runSetupForSize(0, SMALL_SIZE, -1);
for (var i = 0; i < 11; i++) {
parser.checkRequestSize(100);
}
});
assertEquals(exception.getPermittedSize(), SMALL_SIZE);
assertTrue(exception.getActualSize() > SMALL_SIZE);
}
@Test
void parser_should_throw_exception_for_part_size() { | final var exception = assertThrows(PartSizeException.class, () -> { |
Fivium/ScriptRunner | src/com/fivium/scriptrunner2/builder/BuilderManifestEntry.java | // Path: src/com/fivium/scriptrunner2/loader/BuiltInLoader.java
// public abstract class BuiltInLoader
// implements Loader {
//
// public static final String LOADER_NAME_DB_SOURCE = "DatabaseSource";
// public static final String LOADER_NAME_DB_SOURCE_WITH_COMMIT = "DatabaseSourceImplicitCommit";
// public static final String LOADER_NAME_SCRIPTRUNNER_UTIL = "ScriptRunnerUtil";
// public static final String LOADER_NAME_PATCH = "Patch";
// /** Special loader name for the builder only - files associated with this loader are ignored when constructing the manifest. */
// public static final String LOADER_NAME_IGNORE = "Ignore";
//
// private static final Map<String, Loader> gBuiltInLoaderMap;
// static {
// gBuiltInLoaderMap = new HashMap<String, Loader>();
// gBuiltInLoaderMap.put(LOADER_NAME_DB_SOURCE, new DatabaseSourceLoader());
// gBuiltInLoaderMap.put(LOADER_NAME_DB_SOURCE_WITH_COMMIT, new DatabaseSourceLoader(true));
// gBuiltInLoaderMap.put(LOADER_NAME_SCRIPTRUNNER_UTIL, UtilLoader.getInstance());
// gBuiltInLoaderMap.put(LOADER_NAME_PATCH, new PatchScriptLoader());
// }
//
// /**
// * Get the built in loader corresponding to the given name, or null if it does not exist.
// * @param pLoaderName Name of required loader.
// * @return Built-in loader.
// */
// public static Loader getBuiltInLoaderOrNull(String pLoaderName){
// return gBuiltInLoaderMap.get(pLoaderName);
// }
//
// /**
// * Gets the map of built-in loaders. The key of the map is the loader name.
// * @return Map of names to built-in loaders.
// */
// public static Map<String, Loader> getBuiltInLoaderMap() {
// return gBuiltInLoaderMap;
// }
//
// }
| import com.fivium.scriptrunner2.ManifestEntry;
import com.fivium.scriptrunner2.ex.ExInternal;
import com.fivium.scriptrunner2.loader.BuiltInLoader;
import java.util.Map; | package com.fivium.scriptrunner2.builder;
/**
* A ManifestEntry which is being used by a builder during manifest construction. This subclass has a mutable sequence
* position.
*/
public class BuilderManifestEntry
extends ManifestEntry {
/** This cannot be final as it is not known at construction time */
private int mSequencePosition = 0;
public BuilderManifestEntry(boolean pIsAugmentation, String pFilePath, String pLoaderName, int pSequence, Map<String, String> pPropertyMap, boolean pIsForcedDuplicate){
this(pIsAugmentation, pFilePath, pLoaderName, pPropertyMap, pIsForcedDuplicate);
mSequencePosition = pSequence;
}
public BuilderManifestEntry(boolean pIsAugmentation, String pFilePath, String pLoaderName, Map<String, String> pPropertyMap, boolean pIsForcedDuplicate){
super(pIsAugmentation, pFilePath, pLoaderName, pPropertyMap, pIsForcedDuplicate);
//Validate loader name
if(!pIsAugmentation && "".equals(getLoaderName())){
throw new ExInternal("Non-augmentation entry cannot have an empty loader name");
}
}
@Override
public int getSequencePosition(){
return mSequencePosition;
}
public void setSequencePosition(int pSequencePosition) {
mSequencePosition = pSequencePosition;
}
public boolean isIgnoredEntry() { | // Path: src/com/fivium/scriptrunner2/loader/BuiltInLoader.java
// public abstract class BuiltInLoader
// implements Loader {
//
// public static final String LOADER_NAME_DB_SOURCE = "DatabaseSource";
// public static final String LOADER_NAME_DB_SOURCE_WITH_COMMIT = "DatabaseSourceImplicitCommit";
// public static final String LOADER_NAME_SCRIPTRUNNER_UTIL = "ScriptRunnerUtil";
// public static final String LOADER_NAME_PATCH = "Patch";
// /** Special loader name for the builder only - files associated with this loader are ignored when constructing the manifest. */
// public static final String LOADER_NAME_IGNORE = "Ignore";
//
// private static final Map<String, Loader> gBuiltInLoaderMap;
// static {
// gBuiltInLoaderMap = new HashMap<String, Loader>();
// gBuiltInLoaderMap.put(LOADER_NAME_DB_SOURCE, new DatabaseSourceLoader());
// gBuiltInLoaderMap.put(LOADER_NAME_DB_SOURCE_WITH_COMMIT, new DatabaseSourceLoader(true));
// gBuiltInLoaderMap.put(LOADER_NAME_SCRIPTRUNNER_UTIL, UtilLoader.getInstance());
// gBuiltInLoaderMap.put(LOADER_NAME_PATCH, new PatchScriptLoader());
// }
//
// /**
// * Get the built in loader corresponding to the given name, or null if it does not exist.
// * @param pLoaderName Name of required loader.
// * @return Built-in loader.
// */
// public static Loader getBuiltInLoaderOrNull(String pLoaderName){
// return gBuiltInLoaderMap.get(pLoaderName);
// }
//
// /**
// * Gets the map of built-in loaders. The key of the map is the loader name.
// * @return Map of names to built-in loaders.
// */
// public static Map<String, Loader> getBuiltInLoaderMap() {
// return gBuiltInLoaderMap;
// }
//
// }
// Path: src/com/fivium/scriptrunner2/builder/BuilderManifestEntry.java
import com.fivium.scriptrunner2.ManifestEntry;
import com.fivium.scriptrunner2.ex.ExInternal;
import com.fivium.scriptrunner2.loader.BuiltInLoader;
import java.util.Map;
package com.fivium.scriptrunner2.builder;
/**
* A ManifestEntry which is being used by a builder during manifest construction. This subclass has a mutable sequence
* position.
*/
public class BuilderManifestEntry
extends ManifestEntry {
/** This cannot be final as it is not known at construction time */
private int mSequencePosition = 0;
public BuilderManifestEntry(boolean pIsAugmentation, String pFilePath, String pLoaderName, int pSequence, Map<String, String> pPropertyMap, boolean pIsForcedDuplicate){
this(pIsAugmentation, pFilePath, pLoaderName, pPropertyMap, pIsForcedDuplicate);
mSequencePosition = pSequence;
}
public BuilderManifestEntry(boolean pIsAugmentation, String pFilePath, String pLoaderName, Map<String, String> pPropertyMap, boolean pIsForcedDuplicate){
super(pIsAugmentation, pFilePath, pLoaderName, pPropertyMap, pIsForcedDuplicate);
//Validate loader name
if(!pIsAugmentation && "".equals(getLoaderName())){
throw new ExInternal("Non-augmentation entry cannot have an empty loader name");
}
}
@Override
public int getSequencePosition(){
return mSequencePosition;
}
public void setSequencePosition(int pSequencePosition) {
mSequencePosition = pSequencePosition;
}
public boolean isIgnoredEntry() { | return BuiltInLoader.LOADER_NAME_IGNORE.equals(getLoaderName()); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/ContentRootDecoration.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
| import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.ProjectRootsUtil;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import zielu.svntoolbox.projectView.ProjectViewStatus; | /*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class ContentRootDecoration extends AbstractNodeDecoration {
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
return node.getVirtualFile();
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/ContentRootDecoration.java
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.ProjectRootsUtil;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import zielu.svntoolbox.projectView.ProjectViewStatus;
/*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class ContentRootDecoration extends AbstractNodeDecoration {
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
return node.getVirtualFile();
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | ProjectViewStatus status = getBranchStatusAndCache(node); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/FileDecoration.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
| import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.nodes.PsiFileNode;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.SimpleTextAttributes;
import zielu.svntoolbox.projectView.ProjectViewStatus; | /*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class FileDecoration extends AbstractNodeDecoration {
private String getName(ProjectViewNode node) {
PsiFileNode fileNode = (PsiFileNode) node;
return fileNode.getValue().getName();
}
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
PsiFileNode fileNode = (PsiFileNode) node;
return fileNode.getVirtualFile();
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/FileDecoration.java
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.nodes.PsiFileNode;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.SimpleTextAttributes;
import zielu.svntoolbox.projectView.ProjectViewStatus;
/*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class FileDecoration extends AbstractNodeDecoration {
private String getName(ProjectViewNode node) {
PsiFileNode fileNode = (PsiFileNode) node;
return fileNode.getValue().getName();
}
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
PsiFileNode fileNode = (PsiFileNode) node;
return fileNode.getVirtualFile();
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | ProjectViewStatus status = getBranchStatusAndCache(node); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/EmptyDecoration.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecorationType.java
// public enum NodeDecorationType {
// Module,
// Other
// }
| import zielu.svntoolbox.ui.projectView.NodeDecorationType;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import zielu.svntoolbox.ui.projectView.NodeDecoration; | /*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class EmptyDecoration implements NodeDecoration {
public static final NodeDecoration INSTANCE = new EmptyDecoration();
@Override
public boolean isForMe(ProjectViewNode node) {
return true;
}
@Override | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecorationType.java
// public enum NodeDecorationType {
// Module,
// Other
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/EmptyDecoration.java
import zielu.svntoolbox.ui.projectView.NodeDecorationType;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import zielu.svntoolbox.ui.projectView.NodeDecoration;
/*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class EmptyDecoration implements NodeDecoration {
public static final NodeDecoration INSTANCE = new EmptyDecoration();
@Override
public boolean isForMe(ProjectViewNode node) {
return true;
}
@Override | public NodeDecorationType getType() { |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnModuleDecorationAction.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
| import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier; | /*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnModuleDecorationAction extends ToggleAction {
public ToggleSvnModuleDecorationAction() { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnModuleDecorationAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier;
/*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnModuleDecorationAction extends ToggleAction {
public ToggleSvnModuleDecorationAction() { | super(SvnToolBoxBundle.getString("action.show.module.decorations")); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnModuleDecorationAction.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
| import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier; | /*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnModuleDecorationAction extends ToggleAction {
public ToggleSvnModuleDecorationAction() {
super(SvnToolBoxBundle.getString("action.show.module.decorations"));
}
@Override
public boolean isSelected(AnActionEvent e) {
Project project = e.getProject();
if (project != null) { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnModuleDecorationAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier;
/*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnModuleDecorationAction extends ToggleAction {
public ToggleSvnModuleDecorationAction() {
super(SvnToolBoxBundle.getString("action.show.module.decorations"));
}
@Override
public boolean isSelected(AnActionEvent e) {
Project project = e.getProject();
if (project != null) { | return SvnToolBoxProjectState.getInstance(project).showProjectViewModuleDecoration; |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnModuleDecorationAction.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
| import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier; | /*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnModuleDecorationAction extends ToggleAction {
public ToggleSvnModuleDecorationAction() {
super(SvnToolBoxBundle.getString("action.show.module.decorations"));
}
@Override
public boolean isSelected(AnActionEvent e) {
Project project = e.getProject();
if (project != null) {
return SvnToolBoxProjectState.getInstance(project).showProjectViewModuleDecoration;
}
return false;
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
Project project = e.getProject();
if (project != null) {
SvnToolBoxProjectState.getInstance(project).showProjectViewModuleDecoration = state;
project.getMessageBus(). | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnModuleDecorationAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier;
/*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnModuleDecorationAction extends ToggleAction {
public ToggleSvnModuleDecorationAction() {
super(SvnToolBoxBundle.getString("action.show.module.decorations"));
}
@Override
public boolean isSelected(AnActionEvent e) {
Project project = e.getProject();
if (project != null) {
return SvnToolBoxProjectState.getInstance(project).showProjectViewModuleDecoration;
}
return false;
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
Project project = e.getProject();
if (project != null) {
SvnToolBoxProjectState.getInstance(project).showProjectViewModuleDecoration = state;
project.getMessageBus(). | syncPublisher(DecorationToggleNotifier.TOGGLE_TOPIC).decorationChanged(project); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/FileStatusCalculator.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/util/LogStopwatch.java
// public abstract class LogStopwatch {
// private static final Logger LOG = getInstance("#zielu.svntoolbox.perf");
// ;
// private final Supplier<String> myNameSupplier;
// @Nullable
// private final Supplier<Integer> mySequence;
// private final Stopwatch myStopwatch = Stopwatch.createUnstarted();
//
// private String myName;
//
// protected LogStopwatch(@Nullable Supplier<Integer> sequence, Supplier<String> nameSupplier) {
// myNameSupplier = nameSupplier;
// mySequence = sequence;
// }
//
// public static LogStopwatch debugStopwatch(Supplier<String> nameSupplier) {
// return new DebugStopwatch(null, nameSupplier);
// }
//
// public static LogStopwatch debugStopwatch(Supplier<Integer> sequence, Supplier<String> nameSupplier) {
// return new DebugStopwatch(sequence, nameSupplier);
// }
//
// public LogStopwatch start() {
// if (isEnabled()) {
// myStopwatch.start();
// myName = myNameSupplier.get();
// }
// return this;
// }
//
// private String prepareName(String prefix) {
// return "[" + prefix + ":" + myName + (mySequence != null ? "|" + mySequence.get() : "") + "]";
// }
//
// public void tick(String message, Object... args) {
// if (isEnabled()) {
// long time = myStopwatch.elapsed(TimeUnit.MILLISECONDS);
// String formattedMessage = MessageFormat.format(message, args);
// log(prepareName("T") + " " + formattedMessage + " [" + time + " ms]");
// }
// }
//
// public void stop() {
// if (isEnabled()) {
// myStopwatch.stop();
// log(prepareName("S") + " stopped [" + myStopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms]");
// }
// }
//
// protected abstract boolean isEnabled();
//
// protected abstract void log(String message);
//
// private static class DebugStopwatch extends LogStopwatch {
//
// protected DebugStopwatch(@Nullable Supplier<Integer> sequence, Supplier<String> nameSupplier) {
// super(sequence, nameSupplier);
// }
//
// @Override
// protected boolean isEnabled() {
// return LOG.isDebugEnabled();
// }
//
// @Override
// protected void log(String message) {
// LOG.debug(message);
// }
// }
// }
| import com.google.common.collect.Lists;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.SvnConfiguration;
import org.jetbrains.idea.svn.SvnStatusUtil;
import org.jetbrains.idea.svn.SvnUtil;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.api.Url;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationManager;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationNew;
import org.jetbrains.idea.svn.info.Info;
import zielu.svntoolbox.util.LogStopwatch; | }
}
}
}
return result;
}
@NotNull
public FileStatus statusFor(@Nullable Project project, @NotNull VirtualFile vFile) {
if (project == null) {
return FileStatus.EMPTY;
}
SvnVcs svn = SvnVcs.getInstance(project);
return statusFor(svn, project, vFile);
}
private Optional<VirtualFile> getWCRoot(File currentFile) {
//TODO: there is also #getWorkingCopyRootNew for Svn 1.8
File root = SvnUtil.getWorkingCopyRootNew(currentFile);
if (root == null) {
LOG.debug("WC root not found for: file=", currentFile.getAbsolutePath());
return Optional.empty();
} else {
VirtualFile rootVf = SvnUtil.getVirtualFile(root.getPath());
assert rootVf != null: "Root VF not found for: "+root.getPath();
return Optional.of(rootVf);
}
}
private Optional<FileStatus> statusForCli(Project project, Url fileUrl, File currentFile) { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/util/LogStopwatch.java
// public abstract class LogStopwatch {
// private static final Logger LOG = getInstance("#zielu.svntoolbox.perf");
// ;
// private final Supplier<String> myNameSupplier;
// @Nullable
// private final Supplier<Integer> mySequence;
// private final Stopwatch myStopwatch = Stopwatch.createUnstarted();
//
// private String myName;
//
// protected LogStopwatch(@Nullable Supplier<Integer> sequence, Supplier<String> nameSupplier) {
// myNameSupplier = nameSupplier;
// mySequence = sequence;
// }
//
// public static LogStopwatch debugStopwatch(Supplier<String> nameSupplier) {
// return new DebugStopwatch(null, nameSupplier);
// }
//
// public static LogStopwatch debugStopwatch(Supplier<Integer> sequence, Supplier<String> nameSupplier) {
// return new DebugStopwatch(sequence, nameSupplier);
// }
//
// public LogStopwatch start() {
// if (isEnabled()) {
// myStopwatch.start();
// myName = myNameSupplier.get();
// }
// return this;
// }
//
// private String prepareName(String prefix) {
// return "[" + prefix + ":" + myName + (mySequence != null ? "|" + mySequence.get() : "") + "]";
// }
//
// public void tick(String message, Object... args) {
// if (isEnabled()) {
// long time = myStopwatch.elapsed(TimeUnit.MILLISECONDS);
// String formattedMessage = MessageFormat.format(message, args);
// log(prepareName("T") + " " + formattedMessage + " [" + time + " ms]");
// }
// }
//
// public void stop() {
// if (isEnabled()) {
// myStopwatch.stop();
// log(prepareName("S") + " stopped [" + myStopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms]");
// }
// }
//
// protected abstract boolean isEnabled();
//
// protected abstract void log(String message);
//
// private static class DebugStopwatch extends LogStopwatch {
//
// protected DebugStopwatch(@Nullable Supplier<Integer> sequence, Supplier<String> nameSupplier) {
// super(sequence, nameSupplier);
// }
//
// @Override
// protected boolean isEnabled() {
// return LOG.isDebugEnabled();
// }
//
// @Override
// protected void log(String message) {
// LOG.debug(message);
// }
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/FileStatusCalculator.java
import com.google.common.collect.Lists;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.svn.SvnConfiguration;
import org.jetbrains.idea.svn.SvnStatusUtil;
import org.jetbrains.idea.svn.SvnUtil;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.api.Url;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationManager;
import org.jetbrains.idea.svn.branchConfig.SvnBranchConfigurationNew;
import org.jetbrains.idea.svn.info.Info;
import zielu.svntoolbox.util.LogStopwatch;
}
}
}
}
return result;
}
@NotNull
public FileStatus statusFor(@Nullable Project project, @NotNull VirtualFile vFile) {
if (project == null) {
return FileStatus.EMPTY;
}
SvnVcs svn = SvnVcs.getInstance(project);
return statusFor(svn, project, vFile);
}
private Optional<VirtualFile> getWCRoot(File currentFile) {
//TODO: there is also #getWorkingCopyRootNew for Svn 1.8
File root = SvnUtil.getWorkingCopyRootNew(currentFile);
if (root == null) {
LOG.debug("WC root not found for: file=", currentFile.getAbsolutePath());
return Optional.empty();
} else {
VirtualFile rootVf = SvnUtil.getVirtualFile(root.getPath());
assert rootVf != null: "Root VF not found for: "+root.getPath();
return Optional.of(rootVf);
}
}
private Optional<FileStatus> statusForCli(Project project, Url fileUrl, File currentFile) { | LogStopwatch watch = LogStopwatch.debugStopwatch(SvnToolBoxProject.getInstance(project).sequence(), |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/CopyFileUrlAction.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
| import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.svn.SvnUtil;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.api.Url;
import zielu.svntoolbox.SvnToolBoxBundle; | /*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 03.12.13</p>
*
* @author Lukasz Zielinski
*/
public class CopyFileUrlAction extends VirtualFileUnderSvnActionBase {
public CopyFileUrlAction() { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/CopyFileUrlAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.svn.SvnUtil;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.api.Url;
import zielu.svntoolbox.SvnToolBoxBundle;
/*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 03.12.13</p>
*
* @author Lukasz Zielinski
*/
public class CopyFileUrlAction extends VirtualFileUnderSvnActionBase {
public CopyFileUrlAction() { | super(SvnToolBoxBundle.getString("action.copy.file.url")); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/ModuleDecoration.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecorationType.java
// public enum NodeDecorationType {
// Module,
// Other
// }
| import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.ModuleGroup;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import zielu.svntoolbox.projectView.ProjectViewStatus;
import zielu.svntoolbox.ui.projectView.NodeDecorationType; | /*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class ModuleDecoration extends AbstractNodeDecoration {
@Override | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecorationType.java
// public enum NodeDecorationType {
// Module,
// Other
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/ModuleDecoration.java
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.ModuleGroup;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import zielu.svntoolbox.projectView.ProjectViewStatus;
import zielu.svntoolbox.ui.projectView.NodeDecorationType;
/*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class ModuleDecoration extends AbstractNodeDecoration {
@Override | public NodeDecorationType getType() { |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/ModuleDecoration.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecorationType.java
// public enum NodeDecorationType {
// Module,
// Other
// }
| import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.ModuleGroup;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import zielu.svntoolbox.projectView.ProjectViewStatus;
import zielu.svntoolbox.ui.projectView.NodeDecorationType; | /*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class ModuleDecoration extends AbstractNodeDecoration {
@Override
public NodeDecorationType getType() {
return NodeDecorationType.Module;
}
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
return node.getVirtualFile();
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecorationType.java
// public enum NodeDecorationType {
// Module,
// Other
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/ModuleDecoration.java
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.ModuleGroup;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import zielu.svntoolbox.projectView.ProjectViewStatus;
import zielu.svntoolbox.ui.projectView.NodeDecorationType;
/*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class ModuleDecoration extends AbstractNodeDecoration {
@Override
public NodeDecorationType getType() {
return NodeDecorationType.Module;
}
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
return node.getVirtualFile();
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | ProjectViewStatus status = getBranchStatusAndCache(node); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxApp.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/extensions/NodeDecorationEP.java
// public class NodeDecorationEP extends AbstractExtensionPointBean implements Comparable<NodeDecorationEP> {
// public final static ExtensionPointName<NodeDecorationEP>
// POINT_NAME = ExtensionPointName.create("zielu.svntoolbox.nodeDecorationPoint");
//
// @Attribute("priority")
// public Integer priority;
//
// @Attribute("implementationClass")
// public String implementationClass;
//
// public NodeDecoration instantiate() {
// try {
// return instantiate(implementationClass, ApplicationManager.getApplication().getPicoContainer());
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int compareTo(NodeDecorationEP o) {
// return priority.compareTo(o.priority);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/EmptyDecoration.java
// public class EmptyDecoration implements NodeDecoration {
// public static final NodeDecoration INSTANCE = new EmptyDecoration();
//
// @Override
// public boolean isForMe(ProjectViewNode node) {
// return true;
// }
//
// @Override
// public NodeDecorationType getType() {
// return NodeDecorationType.Other;
// }
//
// @Override
// public void decorate(ProjectViewNode node, PresentationData data) {
// }
// }
| import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import org.jetbrains.annotations.NotNull;
import zielu.svntoolbox.extensions.NodeDecorationEP;
import zielu.svntoolbox.ui.projectView.NodeDecoration;
import zielu.svntoolbox.ui.projectView.impl.EmptyDecoration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; | /*
* $Id$
*/
package zielu.svntoolbox;
/**
* <p></p>
* <br/>
* <p>Created on 14.10.13</p>
*
* @author Lukasz Zielinski
*/
public class SvnToolBoxApp implements ApplicationComponent {
private final Logger log = Logger.getInstance(getClass()); | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/extensions/NodeDecorationEP.java
// public class NodeDecorationEP extends AbstractExtensionPointBean implements Comparable<NodeDecorationEP> {
// public final static ExtensionPointName<NodeDecorationEP>
// POINT_NAME = ExtensionPointName.create("zielu.svntoolbox.nodeDecorationPoint");
//
// @Attribute("priority")
// public Integer priority;
//
// @Attribute("implementationClass")
// public String implementationClass;
//
// public NodeDecoration instantiate() {
// try {
// return instantiate(implementationClass, ApplicationManager.getApplication().getPicoContainer());
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int compareTo(NodeDecorationEP o) {
// return priority.compareTo(o.priority);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/EmptyDecoration.java
// public class EmptyDecoration implements NodeDecoration {
// public static final NodeDecoration INSTANCE = new EmptyDecoration();
//
// @Override
// public boolean isForMe(ProjectViewNode node) {
// return true;
// }
//
// @Override
// public NodeDecorationType getType() {
// return NodeDecorationType.Other;
// }
//
// @Override
// public void decorate(ProjectViewNode node, PresentationData data) {
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxApp.java
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import org.jetbrains.annotations.NotNull;
import zielu.svntoolbox.extensions.NodeDecorationEP;
import zielu.svntoolbox.ui.projectView.NodeDecoration;
import zielu.svntoolbox.ui.projectView.impl.EmptyDecoration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/*
* $Id$
*/
package zielu.svntoolbox;
/**
* <p></p>
* <br/>
* <p>Created on 14.10.13</p>
*
* @author Lukasz Zielinski
*/
public class SvnToolBoxApp implements ApplicationComponent {
private final Logger log = Logger.getInstance(getClass()); | private final List<NodeDecoration> myNodeDecorations = Lists.newArrayList(); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxApp.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/extensions/NodeDecorationEP.java
// public class NodeDecorationEP extends AbstractExtensionPointBean implements Comparable<NodeDecorationEP> {
// public final static ExtensionPointName<NodeDecorationEP>
// POINT_NAME = ExtensionPointName.create("zielu.svntoolbox.nodeDecorationPoint");
//
// @Attribute("priority")
// public Integer priority;
//
// @Attribute("implementationClass")
// public String implementationClass;
//
// public NodeDecoration instantiate() {
// try {
// return instantiate(implementationClass, ApplicationManager.getApplication().getPicoContainer());
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int compareTo(NodeDecorationEP o) {
// return priority.compareTo(o.priority);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/EmptyDecoration.java
// public class EmptyDecoration implements NodeDecoration {
// public static final NodeDecoration INSTANCE = new EmptyDecoration();
//
// @Override
// public boolean isForMe(ProjectViewNode node) {
// return true;
// }
//
// @Override
// public NodeDecorationType getType() {
// return NodeDecorationType.Other;
// }
//
// @Override
// public void decorate(ProjectViewNode node, PresentationData data) {
// }
// }
| import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import org.jetbrains.annotations.NotNull;
import zielu.svntoolbox.extensions.NodeDecorationEP;
import zielu.svntoolbox.ui.projectView.NodeDecoration;
import zielu.svntoolbox.ui.projectView.impl.EmptyDecoration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; | }
public NotificationGroup notification() {
return notification;
}
public Future<?> submit(Runnable task) {
return myExecutor.submit(task);
}
public ScheduledFuture<?> schedule(Runnable task, long delay, TimeUnit timeUnit) {
return myScheduledExecutor.schedule(task, delay, timeUnit);
}
@Override
public void initComponent() {
notification = new NotificationGroup("SVN ToolBox Messages", NotificationDisplayType.STICKY_BALLOON, true);
myExecutor = Executors.newCachedThreadPool(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getComponentName()+"-pool-%s")
.setPriority(Thread.NORM_PRIORITY)
.build()
);
myScheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getComponentName() + "-scheduled-pool-%s")
.setPriority(Thread.NORM_PRIORITY)
.build()
); | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/extensions/NodeDecorationEP.java
// public class NodeDecorationEP extends AbstractExtensionPointBean implements Comparable<NodeDecorationEP> {
// public final static ExtensionPointName<NodeDecorationEP>
// POINT_NAME = ExtensionPointName.create("zielu.svntoolbox.nodeDecorationPoint");
//
// @Attribute("priority")
// public Integer priority;
//
// @Attribute("implementationClass")
// public String implementationClass;
//
// public NodeDecoration instantiate() {
// try {
// return instantiate(implementationClass, ApplicationManager.getApplication().getPicoContainer());
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int compareTo(NodeDecorationEP o) {
// return priority.compareTo(o.priority);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/EmptyDecoration.java
// public class EmptyDecoration implements NodeDecoration {
// public static final NodeDecoration INSTANCE = new EmptyDecoration();
//
// @Override
// public boolean isForMe(ProjectViewNode node) {
// return true;
// }
//
// @Override
// public NodeDecorationType getType() {
// return NodeDecorationType.Other;
// }
//
// @Override
// public void decorate(ProjectViewNode node, PresentationData data) {
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxApp.java
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import org.jetbrains.annotations.NotNull;
import zielu.svntoolbox.extensions.NodeDecorationEP;
import zielu.svntoolbox.ui.projectView.NodeDecoration;
import zielu.svntoolbox.ui.projectView.impl.EmptyDecoration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
}
public NotificationGroup notification() {
return notification;
}
public Future<?> submit(Runnable task) {
return myExecutor.submit(task);
}
public ScheduledFuture<?> schedule(Runnable task, long delay, TimeUnit timeUnit) {
return myScheduledExecutor.schedule(task, delay, timeUnit);
}
@Override
public void initComponent() {
notification = new NotificationGroup("SVN ToolBox Messages", NotificationDisplayType.STICKY_BALLOON, true);
myExecutor = Executors.newCachedThreadPool(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getComponentName()+"-pool-%s")
.setPriority(Thread.NORM_PRIORITY)
.build()
);
myScheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getComponentName() + "-scheduled-pool-%s")
.setPriority(Thread.NORM_PRIORITY)
.build()
); | List<NodeDecorationEP> nodeDecorationEPs = Arrays.asList(Extensions.getExtensions(NodeDecorationEP.POINT_NAME)); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxApp.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/extensions/NodeDecorationEP.java
// public class NodeDecorationEP extends AbstractExtensionPointBean implements Comparable<NodeDecorationEP> {
// public final static ExtensionPointName<NodeDecorationEP>
// POINT_NAME = ExtensionPointName.create("zielu.svntoolbox.nodeDecorationPoint");
//
// @Attribute("priority")
// public Integer priority;
//
// @Attribute("implementationClass")
// public String implementationClass;
//
// public NodeDecoration instantiate() {
// try {
// return instantiate(implementationClass, ApplicationManager.getApplication().getPicoContainer());
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int compareTo(NodeDecorationEP o) {
// return priority.compareTo(o.priority);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/EmptyDecoration.java
// public class EmptyDecoration implements NodeDecoration {
// public static final NodeDecoration INSTANCE = new EmptyDecoration();
//
// @Override
// public boolean isForMe(ProjectViewNode node) {
// return true;
// }
//
// @Override
// public NodeDecorationType getType() {
// return NodeDecorationType.Other;
// }
//
// @Override
// public void decorate(ProjectViewNode node, PresentationData data) {
// }
// }
| import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import org.jetbrains.annotations.NotNull;
import zielu.svntoolbox.extensions.NodeDecorationEP;
import zielu.svntoolbox.ui.projectView.NodeDecoration;
import zielu.svntoolbox.ui.projectView.impl.EmptyDecoration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; | public void initComponent() {
notification = new NotificationGroup("SVN ToolBox Messages", NotificationDisplayType.STICKY_BALLOON, true);
myExecutor = Executors.newCachedThreadPool(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getComponentName()+"-pool-%s")
.setPriority(Thread.NORM_PRIORITY)
.build()
);
myScheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getComponentName() + "-scheduled-pool-%s")
.setPriority(Thread.NORM_PRIORITY)
.build()
);
List<NodeDecorationEP> nodeDecorationEPs = Arrays.asList(Extensions.getExtensions(NodeDecorationEP.POINT_NAME));
Collections.sort(nodeDecorationEPs);
for (NodeDecorationEP decorationEP : nodeDecorationEPs) {
NodeDecoration decoration = decorationEP.instantiate();
myNodeDecorations.add(decoration);
log.debug("Added decoration ", decorationEP.priority, " ", decoration);
}
}
public NodeDecoration decorationFor(ProjectViewNode node) {
for (NodeDecoration candidate : myNodeDecorations) {
if (candidate.isForMe(node)) {
return candidate;
}
} | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/extensions/NodeDecorationEP.java
// public class NodeDecorationEP extends AbstractExtensionPointBean implements Comparable<NodeDecorationEP> {
// public final static ExtensionPointName<NodeDecorationEP>
// POINT_NAME = ExtensionPointName.create("zielu.svntoolbox.nodeDecorationPoint");
//
// @Attribute("priority")
// public Integer priority;
//
// @Attribute("implementationClass")
// public String implementationClass;
//
// public NodeDecoration instantiate() {
// try {
// return instantiate(implementationClass, ApplicationManager.getApplication().getPicoContainer());
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public int compareTo(NodeDecorationEP o) {
// return priority.compareTo(o.priority);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/EmptyDecoration.java
// public class EmptyDecoration implements NodeDecoration {
// public static final NodeDecoration INSTANCE = new EmptyDecoration();
//
// @Override
// public boolean isForMe(ProjectViewNode node) {
// return true;
// }
//
// @Override
// public NodeDecorationType getType() {
// return NodeDecorationType.Other;
// }
//
// @Override
// public void decorate(ProjectViewNode node, PresentationData data) {
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxApp.java
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.NotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import org.jetbrains.annotations.NotNull;
import zielu.svntoolbox.extensions.NodeDecorationEP;
import zielu.svntoolbox.ui.projectView.NodeDecoration;
import zielu.svntoolbox.ui.projectView.impl.EmptyDecoration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public void initComponent() {
notification = new NotificationGroup("SVN ToolBox Messages", NotificationDisplayType.STICKY_BALLOON, true);
myExecutor = Executors.newCachedThreadPool(
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getComponentName()+"-pool-%s")
.setPriority(Thread.NORM_PRIORITY)
.build()
);
myScheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getComponentName() + "-scheduled-pool-%s")
.setPriority(Thread.NORM_PRIORITY)
.build()
);
List<NodeDecorationEP> nodeDecorationEPs = Arrays.asList(Extensions.getExtensions(NodeDecorationEP.POINT_NAME));
Collections.sort(nodeDecorationEPs);
for (NodeDecorationEP decorationEP : nodeDecorationEPs) {
NodeDecoration decoration = decorationEP.instantiate();
myNodeDecorations.add(decoration);
log.debug("Added decoration ", decorationEP.priority, " ", decoration);
}
}
public NodeDecoration decorationFor(ProjectViewNode node) {
for (NodeDecoration candidate : myNodeDecorations) {
if (candidate.isForMe(node)) {
return candidate;
}
} | return EmptyDecoration.INSTANCE; |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import zielu.svntoolbox.SvnToolBoxBundle; | /*
* $Id$
*/
package zielu.svntoolbox.projectView;
/**
* <p></p>
* <br/>
* <p>Created on 24.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ProjectViewStatus {
public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
@Override
public boolean equals(Object other) {
return this == other;
}
}; | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import zielu.svntoolbox.SvnToolBoxBundle;
/*
* $Id$
*/
package zielu.svntoolbox.projectView;
/**
* <p></p>
* <br/>
* <p>Created on 24.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ProjectViewStatus {
public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
@Override
public boolean equals(Object other) {
return this == other;
}
}; | public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) { |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/lockinfo/SvnLockOwnerComponent.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxAppState.java
// @State(
// name = "SvnToolBoxAppConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxAppState implements PersistentStateComponent<SvnToolBoxAppState> {
// public boolean customRegularColor;
// public int regularR = 159;
// public int regularG = 107;
// public int regularB = 0;
//
// public boolean customDarkColor;
// public int darkR = 159;
// public int darkG = 107;
// public int darkB = 0;
//
// private String fileCsv;
//
// @Transient
// private static final Color defaultRegularColor = new Color(159, 107, 0);
//
// @Transient
// private static final Color defaultDarkColor = new Color(159, 107, 0);
//
// private static final SvnToolBoxAppState EMPTY = new SvnToolBoxAppState();
//
// public static SvnToolBoxAppState getInstance() {
// return ServiceManager.getService(SvnToolBoxAppState.class);
// }
//
// public String getCsvFile() {
// return Strings.nullToEmpty(fileCsv);
// }
//
// public void setCsvFile(String fileCsv) {
// this.fileCsv = fileCsv;
// }
//
// public boolean checkCsvFileChanged(String csvFile) {
// String currentValue = getCsvFile();
// return !currentValue.equalsIgnoreCase(csvFile);
// }
//
// @Transient
// public Color getCurrentRegularDecorationColor() {
// if (customRegularColor) {
// return getRegularDecorationColor();
// } else {
// return defaultRegularColor;
// }
// }
//
// @Transient
// public Color getRegularDecorationColor() {
// return new Color(regularR, regularG, regularB);
// }
//
// @Transient
// public Color getCurrentDarkDecorationColor() {
// if (customDarkColor) {
// return getDarkDecorationColor();
// } else {
// return defaultDarkColor;
// }
// }
//
// @Transient
// public Color getDarkDecorationColor() {
// return new Color(darkR, darkG, darkB);
// }
//
// private boolean isChanged(Color newColor, int r, int g, int b) {
// return newColor.getRed() != r
// || newColor.getGreen() != g
// || newColor.getBlue() != b;
// }
//
// public void setRegularDecorationColor(boolean enabled, Color color) {
// customRegularColor = enabled;
// if (enabled) {
// regularR = color.getRed();
// regularG = color.getGreen();
// regularB = color.getBlue();
// }
// }
//
// public boolean checkRegularDecorationChanged(boolean enabled, Color color) {
// boolean changed = false;
// if (customRegularColor != enabled) {
// changed = true;
// }
// if (isChanged(color, regularR, regularG, regularB)) {
// changed = true;
// }
// return changed;
// }
//
// public void setDarkDecorationColor(boolean enabled, Color color) {
// customDarkColor = enabled;
// if (enabled) {
// darkR = color.getRed();
// darkG = color.getGreen();
// darkB = color.getBlue();
// }
// }
//
// public boolean checkDarkDecorationChanged(boolean enabled, Color color) {
// boolean changed = false;
// if (customDarkColor != enabled) {
// changed = true;
// }
// if (isChanged(color, darkR, darkG, darkB)) {
// changed = true;
// }
// return changed;
// }
//
// public void fireSettingsChanged() {
// ApplicationManager.getApplication().getMessageBus().
// syncPublisher(DecorationSettingsNotifier.TOGGLE_TOPIC).settingsChanged();
// }
//
// @Transient
// public JBColor getProjectViewDecorationColor() {
// return new JBColor(getCurrentRegularDecorationColor(), getCurrentDarkDecorationColor());
// }
//
// @Nullable
// @Override
// public SvnToolBoxAppState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxAppState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
| import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import zielu.svntoolbox.config.SvnToolBoxAppState;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; | log.error("Failed to load csv file: " + csvFile, e);
}
return Collections.emptyMap();
}
private Optional<String> loadFromMappings(String owner, String csvFile) {
lock.writeLock().lock();
File file = new File(csvFile);
if (file.exists()) {
Map<String, String> mappings = loadFile(file);
ownerMapping.clear();
ownerMapping.putAll(mappings);
lock.readLock().lock();
lock.writeLock().unlock();
try {
return Optional.ofNullable(ownerMapping.get(owner.toLowerCase()));
} finally {
lock.readLock().unlock();
}
} else if (ownerMapping.size() > 0) {
ownerMapping.clear();
}
lock.writeLock().unlock();
return Optional.empty();
}
public String getOwner(String owner) {
if (StringUtils.isBlank(owner)) {
return StringUtils.EMPTY;
} else { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxAppState.java
// @State(
// name = "SvnToolBoxAppConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxAppState implements PersistentStateComponent<SvnToolBoxAppState> {
// public boolean customRegularColor;
// public int regularR = 159;
// public int regularG = 107;
// public int regularB = 0;
//
// public boolean customDarkColor;
// public int darkR = 159;
// public int darkG = 107;
// public int darkB = 0;
//
// private String fileCsv;
//
// @Transient
// private static final Color defaultRegularColor = new Color(159, 107, 0);
//
// @Transient
// private static final Color defaultDarkColor = new Color(159, 107, 0);
//
// private static final SvnToolBoxAppState EMPTY = new SvnToolBoxAppState();
//
// public static SvnToolBoxAppState getInstance() {
// return ServiceManager.getService(SvnToolBoxAppState.class);
// }
//
// public String getCsvFile() {
// return Strings.nullToEmpty(fileCsv);
// }
//
// public void setCsvFile(String fileCsv) {
// this.fileCsv = fileCsv;
// }
//
// public boolean checkCsvFileChanged(String csvFile) {
// String currentValue = getCsvFile();
// return !currentValue.equalsIgnoreCase(csvFile);
// }
//
// @Transient
// public Color getCurrentRegularDecorationColor() {
// if (customRegularColor) {
// return getRegularDecorationColor();
// } else {
// return defaultRegularColor;
// }
// }
//
// @Transient
// public Color getRegularDecorationColor() {
// return new Color(regularR, regularG, regularB);
// }
//
// @Transient
// public Color getCurrentDarkDecorationColor() {
// if (customDarkColor) {
// return getDarkDecorationColor();
// } else {
// return defaultDarkColor;
// }
// }
//
// @Transient
// public Color getDarkDecorationColor() {
// return new Color(darkR, darkG, darkB);
// }
//
// private boolean isChanged(Color newColor, int r, int g, int b) {
// return newColor.getRed() != r
// || newColor.getGreen() != g
// || newColor.getBlue() != b;
// }
//
// public void setRegularDecorationColor(boolean enabled, Color color) {
// customRegularColor = enabled;
// if (enabled) {
// regularR = color.getRed();
// regularG = color.getGreen();
// regularB = color.getBlue();
// }
// }
//
// public boolean checkRegularDecorationChanged(boolean enabled, Color color) {
// boolean changed = false;
// if (customRegularColor != enabled) {
// changed = true;
// }
// if (isChanged(color, regularR, regularG, regularB)) {
// changed = true;
// }
// return changed;
// }
//
// public void setDarkDecorationColor(boolean enabled, Color color) {
// customDarkColor = enabled;
// if (enabled) {
// darkR = color.getRed();
// darkG = color.getGreen();
// darkB = color.getBlue();
// }
// }
//
// public boolean checkDarkDecorationChanged(boolean enabled, Color color) {
// boolean changed = false;
// if (customDarkColor != enabled) {
// changed = true;
// }
// if (isChanged(color, darkR, darkG, darkB)) {
// changed = true;
// }
// return changed;
// }
//
// public void fireSettingsChanged() {
// ApplicationManager.getApplication().getMessageBus().
// syncPublisher(DecorationSettingsNotifier.TOGGLE_TOPIC).settingsChanged();
// }
//
// @Transient
// public JBColor getProjectViewDecorationColor() {
// return new JBColor(getCurrentRegularDecorationColor(), getCurrentDarkDecorationColor());
// }
//
// @Nullable
// @Override
// public SvnToolBoxAppState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxAppState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/lockinfo/SvnLockOwnerComponent.java
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.diagnostic.Logger;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import zielu.svntoolbox.config.SvnToolBoxAppState;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
log.error("Failed to load csv file: " + csvFile, e);
}
return Collections.emptyMap();
}
private Optional<String> loadFromMappings(String owner, String csvFile) {
lock.writeLock().lock();
File file = new File(csvFile);
if (file.exists()) {
Map<String, String> mappings = loadFile(file);
ownerMapping.clear();
ownerMapping.putAll(mappings);
lock.readLock().lock();
lock.writeLock().unlock();
try {
return Optional.ofNullable(ownerMapping.get(owner.toLowerCase()));
} finally {
lock.readLock().unlock();
}
} else if (ownerMapping.size() > 0) {
ownerMapping.clear();
}
lock.writeLock().unlock();
return Optional.empty();
}
public String getOwner(String owner) {
if (StringUtils.isBlank(owner)) {
return StringUtils.EMPTY;
} else { | String csvFile = SvnToolBoxAppState.getInstance().getCsvFile(); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/ClassFileDecoration.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
| import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.nodes.ClassTreeNode;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.util.PsiUtilBase;
import zielu.svntoolbox.projectView.ProjectViewStatus; | /*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class ClassFileDecoration extends AbstractNodeDecoration {
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
ClassTreeNode classNode = (ClassTreeNode) node;
return PsiUtilBase.getVirtualFile(classNode.getPsiClass());
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/ClassFileDecoration.java
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.nodes.ClassTreeNode;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.util.PsiUtilBase;
import zielu.svntoolbox.projectView.ProjectViewStatus;
/*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class ClassFileDecoration extends AbstractNodeDecoration {
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
ClassTreeNode classNode = (ClassTreeNode) node;
return PsiUtilBase.getVirtualFile(classNode.getPsiClass());
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | ProjectViewStatus status = getBranchStatusAndCache(node); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/extensions/NodeDecorationEP.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
| import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.AbstractExtensionPointBean;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.util.xmlb.annotations.Attribute;
import zielu.svntoolbox.ui.projectView.NodeDecoration; | /*
* $Id$
*/
package zielu.svntoolbox.extensions;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class NodeDecorationEP extends AbstractExtensionPointBean implements Comparable<NodeDecorationEP> {
public final static ExtensionPointName<NodeDecorationEP>
POINT_NAME = ExtensionPointName.create("zielu.svntoolbox.nodeDecorationPoint");
@Attribute("priority")
public Integer priority;
@Attribute("implementationClass")
public String implementationClass;
| // Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/NodeDecoration.java
// public interface NodeDecoration {
// boolean isForMe(ProjectViewNode node);
// NodeDecorationType getType();
// void decorate(ProjectViewNode node, PresentationData data);
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/extensions/NodeDecorationEP.java
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.AbstractExtensionPointBean;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.util.xmlb.annotations.Attribute;
import zielu.svntoolbox.ui.projectView.NodeDecoration;
/*
* $Id$
*/
package zielu.svntoolbox.extensions;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class NodeDecorationEP extends AbstractExtensionPointBean implements Comparable<NodeDecorationEP> {
public final static ExtensionPointName<NodeDecorationEP>
POINT_NAME = ExtensionPointName.create("zielu.svntoolbox.nodeDecorationPoint");
@Attribute("priority")
public Integer priority;
@Attribute("implementationClass")
public String implementationClass;
| public NodeDecoration instantiate() { |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/PackageDecoration.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
| import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.ProjectRootsUtil;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import zielu.svntoolbox.projectView.ProjectViewStatus; | /*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class PackageDecoration extends AbstractNodeDecoration {
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
return node.getVirtualFile();
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/ProjectViewStatus.java
// public class ProjectViewStatus {
// public static final ProjectViewStatus EMPTY = new ProjectViewStatus() {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus PENDING = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.pending"), true) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
// public static final ProjectViewStatus NOT_CONFIGURED = new ProjectViewStatus(SvnToolBoxBundle.getString("status.svn.notConfigured"), false) {
// @Override
// public boolean equals(Object other) {
// return this == other;
// }
// };
//
// private final String myBranchName;
// private final boolean myTemporary;
//
// public ProjectViewStatus(String branchName) {
// this(branchName, false);
// }
//
// private ProjectViewStatus(String branchName, boolean temporary) {
// myBranchName = Preconditions.checkNotNull(branchName, "Null branch name");
// myTemporary = temporary;
// }
//
// private ProjectViewStatus() {
// myBranchName = null;
// myTemporary = false;
// }
//
// public boolean isEmpty() {
// return myBranchName == null;
// }
//
// public boolean isTemporary() {
// return myTemporary;
// }
//
// public String getBranchName() {
// return myBranchName;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// ProjectViewStatus that = (ProjectViewStatus) o;
//
// if (myBranchName != null ? !myBranchName.equals(that.myBranchName) : that.myBranchName != null) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return myBranchName != null ? myBranchName.hashCode() : 0;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(this)
// .add("branchName", myBranchName)
// .add("temporary", myTemporary)
// .toString();
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/projectView/impl/PackageDecoration.java
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.impl.ProjectRootsUtil;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import zielu.svntoolbox.projectView.ProjectViewStatus;
/*
* $Id$
*/
package zielu.svntoolbox.ui.projectView.impl;
/**
* <p></p>
* <br/>
* <p>Created on 12.10.13</p>
*
* @author Lukasz Zielinski
*/
public class PackageDecoration extends AbstractNodeDecoration {
@Override
protected VirtualFile getVirtualFile(ProjectViewNode node) {
return node.getVirtualFile();
}
@Override
protected void applyDecorationUnderSvn(ProjectViewNode node, PresentationData data) { | ProjectViewStatus status = getBranchStatusAndCache(node); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxAppState.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationSettingsNotifier.java
// public interface DecorationSettingsNotifier {
// Topic<DecorationSettingsNotifier> TOGGLE_TOPIC = Topic.create("Decoration Settings Change",
// DecorationSettingsNotifier.class);
//
// void settingsChanged();
// }
| import com.google.common.base.Strings;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.ui.JBColor;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.Transient;
import java.awt.Color;
import org.jetbrains.annotations.Nullable;
import zielu.svntoolbox.projectView.DecorationSettingsNotifier; | changed = true;
}
if (isChanged(color, regularR, regularG, regularB)) {
changed = true;
}
return changed;
}
public void setDarkDecorationColor(boolean enabled, Color color) {
customDarkColor = enabled;
if (enabled) {
darkR = color.getRed();
darkG = color.getGreen();
darkB = color.getBlue();
}
}
public boolean checkDarkDecorationChanged(boolean enabled, Color color) {
boolean changed = false;
if (customDarkColor != enabled) {
changed = true;
}
if (isChanged(color, darkR, darkG, darkB)) {
changed = true;
}
return changed;
}
public void fireSettingsChanged() {
ApplicationManager.getApplication().getMessageBus(). | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationSettingsNotifier.java
// public interface DecorationSettingsNotifier {
// Topic<DecorationSettingsNotifier> TOGGLE_TOPIC = Topic.create("Decoration Settings Change",
// DecorationSettingsNotifier.class);
//
// void settingsChanged();
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxAppState.java
import com.google.common.base.Strings;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.ui.JBColor;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.Transient;
import java.awt.Color;
import org.jetbrains.annotations.Nullable;
import zielu.svntoolbox.projectView.DecorationSettingsNotifier;
changed = true;
}
if (isChanged(color, regularR, regularG, regularB)) {
changed = true;
}
return changed;
}
public void setDarkDecorationColor(boolean enabled, Color color) {
customDarkColor = enabled;
if (enabled) {
darkR = color.getRed();
darkG = color.getGreen();
darkB = color.getBlue();
}
}
public boolean checkDarkDecorationChanged(boolean enabled, Color color) {
boolean changed = false;
if (customDarkColor != enabled) {
changed = true;
}
if (isChanged(color, darkR, darkG, darkB)) {
changed = true;
}
return changed;
}
public void fireSettingsChanged() {
ApplicationManager.getApplication().getMessageBus(). | syncPublisher(DecorationSettingsNotifier.TOGGLE_TOPIC).settingsChanged(); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnSwitchedDecorationAction.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
| import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier; | /*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnSwitchedDecorationAction extends ToggleAction {
public ToggleSvnSwitchedDecorationAction() { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnSwitchedDecorationAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier;
/*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnSwitchedDecorationAction extends ToggleAction {
public ToggleSvnSwitchedDecorationAction() { | super(SvnToolBoxBundle.getString("action.show.switched.decorations")); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnSwitchedDecorationAction.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
| import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier; | /*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnSwitchedDecorationAction extends ToggleAction {
public ToggleSvnSwitchedDecorationAction() {
super(SvnToolBoxBundle.getString("action.show.switched.decorations"));
}
@Override
public boolean isSelected(AnActionEvent e) {
Project project = e.getProject();
if (project != null) { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnSwitchedDecorationAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier;
/*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnSwitchedDecorationAction extends ToggleAction {
public ToggleSvnSwitchedDecorationAction() {
super(SvnToolBoxBundle.getString("action.show.switched.decorations"));
}
@Override
public boolean isSelected(AnActionEvent e) {
Project project = e.getProject();
if (project != null) { | return SvnToolBoxProjectState.getInstance(project).showProjectViewSwitchedDecoration; |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnSwitchedDecorationAction.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
| import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier; | /*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnSwitchedDecorationAction extends ToggleAction {
public ToggleSvnSwitchedDecorationAction() {
super(SvnToolBoxBundle.getString("action.show.switched.decorations"));
}
@Override
public boolean isSelected(AnActionEvent e) {
Project project = e.getProject();
if (project != null) {
return SvnToolBoxProjectState.getInstance(project).showProjectViewSwitchedDecoration;
}
return false;
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
Project project = e.getProject();
if (project != null) {
SvnToolBoxProjectState.getInstance(project).showProjectViewSwitchedDecoration = state;
project.getMessageBus(). | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/config/SvnToolBoxProjectState.java
// @State(
// name = "SvnToolBoxConfig",
// storages = @Storage("SvnToolBox.xml")
// )
// public class SvnToolBoxProjectState implements PersistentStateComponent<SvnToolBoxProjectState> {
// public boolean showProjectViewModuleDecoration = true;
// public boolean showProjectViewSwitchedDecoration = true;
//
// public static SvnToolBoxProjectState getInstance(@NotNull Project project) {
// return ServiceManager.getService(project, SvnToolBoxProjectState.class);
// }
//
// public boolean showingAnyDecorations() {
// return showProjectViewModuleDecoration || showProjectViewSwitchedDecoration;
// }
//
// @Nullable
// @Override
// public SvnToolBoxProjectState getState() {
// return this;
// }
//
// @Override
// public void loadState(SvnToolBoxProjectState state) {
// XmlSerializerUtil.copyBean(state, this);
// }
// }
//
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/projectView/DecorationToggleNotifier.java
// public interface DecorationToggleNotifier {
// Topic<DecorationToggleNotifier> TOGGLE_TOPIC = Topic.create("Toggle decorations", DecorationToggleNotifier.class);
//
// void decorationChanged(Project project);
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ToggleSvnSwitchedDecorationAction.java
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import zielu.svntoolbox.SvnToolBoxBundle;
import zielu.svntoolbox.config.SvnToolBoxProjectState;
import zielu.svntoolbox.projectView.DecorationToggleNotifier;
/*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 21.09.13</p>
*
* @author Lukasz Zielinski
*/
public class ToggleSvnSwitchedDecorationAction extends ToggleAction {
public ToggleSvnSwitchedDecorationAction() {
super(SvnToolBoxBundle.getString("action.show.switched.decorations"));
}
@Override
public boolean isSelected(AnActionEvent e) {
Project project = e.getProject();
if (project != null) {
return SvnToolBoxProjectState.getInstance(project).showProjectViewSwitchedDecoration;
}
return false;
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
Project project = e.getProject();
if (project != null) {
SvnToolBoxProjectState.getInstance(project).showProjectViewSwitchedDecoration = state;
project.getMessageBus(). | syncPublisher(DecorationToggleNotifier.TOGGLE_TOPIC).decorationChanged(project); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ShowLockInfoAction.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
| import static zielu.svntoolbox.SvnToolBoxBundle.getString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull; | package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 22.04.15</p>
*
* @author BONO Adil
* @author Lukasz Zielinski
*/
public class ShowLockInfoAction extends VirtualFileUnderSvnActionBase {
public ShowLockInfoAction() { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/actions/ShowLockInfoAction.java
import static zielu.svntoolbox.SvnToolBoxBundle.getString;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
package zielu.svntoolbox.ui.actions;
/**
* <p></p>
* <br/>
* <p>Created on 22.04.15</p>
*
* @author BONO Adil
* @author Lukasz Zielinski
*/
public class ShowLockInfoAction extends VirtualFileUnderSvnActionBase {
public ShowLockInfoAction() { | super(getString("action.show.lock.info")); |
zielu/SVNToolBox | SVNToolBox/src/main/java/zielu/svntoolbox/ui/config/SvnToolBoxForm.java | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
| import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.ui.CheckBoxWithColorChooser;
import zielu.svntoolbox.SvnToolBoxBundle;
import javax.swing.*;
import java.awt.Color; | /*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.config;
/**
* <p></p>
* <br/>
* <p>Created on 29.09.13</p>
*
* @author Lukasz Zielinski
*/
public class SvnToolBoxForm {
private JPanel content;
private CheckBoxWithColorChooser regularColorChooser;
private CheckBoxWithColorChooser darkColorChooser;
private TextFieldWithBrowseButton csvFileChooser;
public JComponent getContent() {
return content;
}
protected void createUIComponents() { | // Path: SVNToolBox/src/main/java/zielu/svntoolbox/SvnToolBoxBundle.java
// public class SvnToolBoxBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "zielu.svntoolbox.SvnToolBoxBundle";
//
// private SvnToolBoxBundle() {
// }
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) {
// return CommonBundle.message(getBundle(), key, params);
// }
//
// public static String getString(@PropertyKey(resourceBundle = BUNDLE) String key) {
// return getBundle().getString(key);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) {
// bundle = ourBundle.get();
// }
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
// Path: SVNToolBox/src/main/java/zielu/svntoolbox/ui/config/SvnToolBoxForm.java
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.ui.CheckBoxWithColorChooser;
import zielu.svntoolbox.SvnToolBoxBundle;
import javax.swing.*;
import java.awt.Color;
/*
* @(#) $Id: $
*/
package zielu.svntoolbox.ui.config;
/**
* <p></p>
* <br/>
* <p>Created on 29.09.13</p>
*
* @author Lukasz Zielinski
*/
public class SvnToolBoxForm {
private JPanel content;
private CheckBoxWithColorChooser regularColorChooser;
private CheckBoxWithColorChooser darkColorChooser;
private TextFieldWithBrowseButton csvFileChooser;
public JComponent getContent() {
return content;
}
protected void createUIComponents() { | regularColorChooser = new CheckBoxWithColorChooser(SvnToolBoxBundle.getString("configurable.app.regularColor.text")); |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/SmsStatusPullReplyResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.ArrayList; | }
if (json.has("text")) {
text = json.getString("text");
}
if (json.has("text")) {
sign = json.getString("text");
}
if (json.has("time")) {
time = json.getLong("time");
}
if (json.has("extend")) {
extend = json.getString("extend");
}
return this;
}
}
public int result;
public String errMsg;
public int count;
public ArrayList<Reply> replys;
public SmsStatusPullReplyResult() {
this.errMsg = "";
this.count = 0;
this.replys = new ArrayList<Reply>();
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/SmsStatusPullReplyResult.java
import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.ArrayList;
}
if (json.has("text")) {
text = json.getString("text");
}
if (json.has("text")) {
sign = json.getString("text");
}
if (json.has("time")) {
time = json.getLong("time");
}
if (json.has("extend")) {
extend = json.getString("extend");
}
return this;
}
}
public int result;
public String errMsg;
public int count;
public ArrayList<Reply> replys;
public SmsStatusPullReplyResult() {
this.errMsg = "";
this.count = 0;
this.replys = new ArrayList<Reply>();
}
@Override | public SmsStatusPullReplyResult parseFromHTTPResponse(HTTPResponse response) |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/VoiceFileStatusResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException; | package com.github.qcloudsms;
public class VoiceFileStatusResult extends SmsResultBase {
public int result;
public String errMsg;
public int status;
public VoiceFileStatusResult() {
this.errMsg = "";
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/VoiceFileStatusResult.java
import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException;
package com.github.qcloudsms;
public class VoiceFileStatusResult extends SmsResultBase {
public int result;
public String errMsg;
public int status;
public VoiceFileStatusResult() {
this.errMsg = "";
}
@Override | public VoiceFileStatusResult parseFromHTTPResponse(HTTPResponse response) |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/TtsVoiceSenderResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException; | package com.github.qcloudsms;
public class TtsVoiceSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String callid;
public TtsVoiceSenderResult() {
this.errMsg = "";
this.ext = "";
this.callid = "";
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/TtsVoiceSenderResult.java
import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException;
package com.github.qcloudsms;
public class TtsVoiceSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String callid;
public TtsVoiceSenderResult() {
this.errMsg = "";
this.ext = "";
this.callid = "";
}
@Override | public TtsVoiceSenderResult parseFromHTTPResponse(HTTPResponse response) |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/SmsMultiSenderResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.ArrayList; |
if (json.has("mobile")) {
mobile = json.getString("mobile");
}
if (json.has("nationcode")) {
nationcode = json.getString("nationcode");
}
if (json.has("sid")) {
sid = json.getString("sid");
}
if (json.has("fee")) {
fee = json.getInt("fee");
}
return this;
}
}
public int result;
public String errMsg;
public String ext;
public ArrayList<Detail> details;
public SmsMultiSenderResult() {
this.errMsg = "";
this.ext = "";
this.details = new ArrayList<Detail>();
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/SmsMultiSenderResult.java
import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.ArrayList;
if (json.has("mobile")) {
mobile = json.getString("mobile");
}
if (json.has("nationcode")) {
nationcode = json.getString("nationcode");
}
if (json.has("sid")) {
sid = json.getString("sid");
}
if (json.has("fee")) {
fee = json.getInt("fee");
}
return this;
}
}
public int result;
public String errMsg;
public String ext;
public ArrayList<Detail> details;
public SmsMultiSenderResult() {
this.errMsg = "";
this.ext = "";
this.details = new ArrayList<Detail>();
}
@Override | public SmsMultiSenderResult parseFromHTTPResponse(HTTPResponse response) |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/SmsVoicePromptSenderResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException; | package com.github.qcloudsms;
public class SmsVoicePromptSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String callid;
public SmsVoicePromptSenderResult() {
this.errMsg = "";
this.ext = "";
this.callid = "";
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/SmsVoicePromptSenderResult.java
import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException;
package com.github.qcloudsms;
public class SmsVoicePromptSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String callid;
public SmsVoicePromptSenderResult() {
this.errMsg = "";
this.ext = "";
this.callid = "";
}
@Override | public SmsVoicePromptSenderResult parseFromHTTPResponse(HTTPResponse response) |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/SmsSingleSenderResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import org.json.JSONObject;
import org.json.JSONException;
import com.github.qcloudsms.httpclient.HTTPResponse; | package com.github.qcloudsms;
public class SmsSingleSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String sid;
public int fee;
public SmsSingleSenderResult() {
this.errMsg = "";
this.ext = "";
this.sid = "";
this.fee = 0;
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/SmsSingleSenderResult.java
import org.json.JSONObject;
import org.json.JSONException;
import com.github.qcloudsms.httpclient.HTTPResponse;
package com.github.qcloudsms;
public class SmsSingleSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String sid;
public int fee;
public SmsSingleSenderResult() {
this.errMsg = "";
this.ext = "";
this.sid = "";
this.fee = 0;
}
@Override | public SmsSingleSenderResult parseFromHTTPResponse(HTTPResponse response) |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/SmsVoiceVerifyCodeSenderResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException; | package com.github.qcloudsms;
public class SmsVoiceVerifyCodeSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String callid;
public SmsVoiceVerifyCodeSenderResult() {
this.errMsg = "";
this.ext = "";
this.callid = "";
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/SmsVoiceVerifyCodeSenderResult.java
import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException;
package com.github.qcloudsms;
public class SmsVoiceVerifyCodeSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String callid;
public SmsVoiceVerifyCodeSenderResult() {
this.errMsg = "";
this.ext = "";
this.callid = "";
}
@Override | public SmsVoiceVerifyCodeSenderResult parseFromHTTPResponse(HTTPResponse response) |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/VoiceFileUploaderResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException; | package com.github.qcloudsms;
public class VoiceFileUploaderResult extends SmsResultBase {
public int result;
public String errMsg;
public String fid;
public VoiceFileUploaderResult() {
this.errMsg = "";
this.fid = "";
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/VoiceFileUploaderResult.java
import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException;
package com.github.qcloudsms;
public class VoiceFileUploaderResult extends SmsResultBase {
public int result;
public String errMsg;
public String fid;
public VoiceFileUploaderResult() {
this.errMsg = "";
this.fid = "";
}
@Override | public VoiceFileUploaderResult parseFromHTTPResponse(HTTPResponse response) |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/SmsBase.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPClient.java
// public interface HTTPClient {
//
// /**
// * Fetch HTTP response by given HTTP request,
// *
// * @param request Specify which to be fetched.
// *
// * @return the response to the request.
// * @throws IOException connection problem.
// * @throws URISyntaxException url syntax problem.
// */
// HTTPResponse fetch(HTTPRequest request)
// throws IOException, URISyntaxException;
//
// /**
// * Close http client and release resource
// *
// */
// void close();
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPException.java
// public class HTTPException extends Exception {
//
// private final int statusCode;
// private final String reason;
//
// public HTTPException(final int statusCode, final String reason) {
// super("HTTP statusCode: " + statusCode + ", reasons: " + reason);
// this.reason = reason;
// this.statusCode = statusCode;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getReason() {
// return reason;
// }
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPClient;
import com.github.qcloudsms.httpclient.HTTPException;
import com.github.qcloudsms.httpclient.HTTPResponse; | package com.github.qcloudsms;
public class SmsBase {
protected int appid;
protected String appkey; | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPClient.java
// public interface HTTPClient {
//
// /**
// * Fetch HTTP response by given HTTP request,
// *
// * @param request Specify which to be fetched.
// *
// * @return the response to the request.
// * @throws IOException connection problem.
// * @throws URISyntaxException url syntax problem.
// */
// HTTPResponse fetch(HTTPRequest request)
// throws IOException, URISyntaxException;
//
// /**
// * Close http client and release resource
// *
// */
// void close();
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPException.java
// public class HTTPException extends Exception {
//
// private final int statusCode;
// private final String reason;
//
// public HTTPException(final int statusCode, final String reason) {
// super("HTTP statusCode: " + statusCode + ", reasons: " + reason);
// this.reason = reason;
// this.statusCode = statusCode;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getReason() {
// return reason;
// }
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/SmsBase.java
import com.github.qcloudsms.httpclient.HTTPClient;
import com.github.qcloudsms.httpclient.HTTPException;
import com.github.qcloudsms.httpclient.HTTPResponse;
package com.github.qcloudsms;
public class SmsBase {
protected int appid;
protected String appkey; | protected HTTPClient httpclient; |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/SmsBase.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPClient.java
// public interface HTTPClient {
//
// /**
// * Fetch HTTP response by given HTTP request,
// *
// * @param request Specify which to be fetched.
// *
// * @return the response to the request.
// * @throws IOException connection problem.
// * @throws URISyntaxException url syntax problem.
// */
// HTTPResponse fetch(HTTPRequest request)
// throws IOException, URISyntaxException;
//
// /**
// * Close http client and release resource
// *
// */
// void close();
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPException.java
// public class HTTPException extends Exception {
//
// private final int statusCode;
// private final String reason;
//
// public HTTPException(final int statusCode, final String reason) {
// super("HTTP statusCode: " + statusCode + ", reasons: " + reason);
// this.reason = reason;
// this.statusCode = statusCode;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getReason() {
// return reason;
// }
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPClient;
import com.github.qcloudsms.httpclient.HTTPException;
import com.github.qcloudsms.httpclient.HTTPResponse; | package com.github.qcloudsms;
public class SmsBase {
protected int appid;
protected String appkey;
protected HTTPClient httpclient;
/**
* SmsBase constructor
*
* @param appid sdk appid
* @param appkey sdk appkey
* @param httpclient http client
*/
public SmsBase(int appid, String appkey, HTTPClient httpclient) {
this.appid = appid;
this.appkey = appkey;
this.httpclient = httpclient;
}
/**
* Handle http status error
*
* @param response raw http response
* @return response raw http response
* @throws HTTPException http status exception
*/ | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPClient.java
// public interface HTTPClient {
//
// /**
// * Fetch HTTP response by given HTTP request,
// *
// * @param request Specify which to be fetched.
// *
// * @return the response to the request.
// * @throws IOException connection problem.
// * @throws URISyntaxException url syntax problem.
// */
// HTTPResponse fetch(HTTPRequest request)
// throws IOException, URISyntaxException;
//
// /**
// * Close http client and release resource
// *
// */
// void close();
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPException.java
// public class HTTPException extends Exception {
//
// private final int statusCode;
// private final String reason;
//
// public HTTPException(final int statusCode, final String reason) {
// super("HTTP statusCode: " + statusCode + ", reasons: " + reason);
// this.reason = reason;
// this.statusCode = statusCode;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getReason() {
// return reason;
// }
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/SmsBase.java
import com.github.qcloudsms.httpclient.HTTPClient;
import com.github.qcloudsms.httpclient.HTTPException;
import com.github.qcloudsms.httpclient.HTTPResponse;
package com.github.qcloudsms;
public class SmsBase {
protected int appid;
protected String appkey;
protected HTTPClient httpclient;
/**
* SmsBase constructor
*
* @param appid sdk appid
* @param appkey sdk appkey
* @param httpclient http client
*/
public SmsBase(int appid, String appkey, HTTPClient httpclient) {
this.appid = appid;
this.appkey = appkey;
this.httpclient = httpclient;
}
/**
* Handle http status error
*
* @param response raw http response
* @return response raw http response
* @throws HTTPException http status exception
*/ | public HTTPResponse handleError(HTTPResponse response) throws HTTPException { |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/SmsBase.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPClient.java
// public interface HTTPClient {
//
// /**
// * Fetch HTTP response by given HTTP request,
// *
// * @param request Specify which to be fetched.
// *
// * @return the response to the request.
// * @throws IOException connection problem.
// * @throws URISyntaxException url syntax problem.
// */
// HTTPResponse fetch(HTTPRequest request)
// throws IOException, URISyntaxException;
//
// /**
// * Close http client and release resource
// *
// */
// void close();
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPException.java
// public class HTTPException extends Exception {
//
// private final int statusCode;
// private final String reason;
//
// public HTTPException(final int statusCode, final String reason) {
// super("HTTP statusCode: " + statusCode + ", reasons: " + reason);
// this.reason = reason;
// this.statusCode = statusCode;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getReason() {
// return reason;
// }
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPClient;
import com.github.qcloudsms.httpclient.HTTPException;
import com.github.qcloudsms.httpclient.HTTPResponse; | package com.github.qcloudsms;
public class SmsBase {
protected int appid;
protected String appkey;
protected HTTPClient httpclient;
/**
* SmsBase constructor
*
* @param appid sdk appid
* @param appkey sdk appkey
* @param httpclient http client
*/
public SmsBase(int appid, String appkey, HTTPClient httpclient) {
this.appid = appid;
this.appkey = appkey;
this.httpclient = httpclient;
}
/**
* Handle http status error
*
* @param response raw http response
* @return response raw http response
* @throws HTTPException http status exception
*/ | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPClient.java
// public interface HTTPClient {
//
// /**
// * Fetch HTTP response by given HTTP request,
// *
// * @param request Specify which to be fetched.
// *
// * @return the response to the request.
// * @throws IOException connection problem.
// * @throws URISyntaxException url syntax problem.
// */
// HTTPResponse fetch(HTTPRequest request)
// throws IOException, URISyntaxException;
//
// /**
// * Close http client and release resource
// *
// */
// void close();
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPException.java
// public class HTTPException extends Exception {
//
// private final int statusCode;
// private final String reason;
//
// public HTTPException(final int statusCode, final String reason) {
// super("HTTP statusCode: " + statusCode + ", reasons: " + reason);
// this.reason = reason;
// this.statusCode = statusCode;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getReason() {
// return reason;
// }
// }
//
// Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/SmsBase.java
import com.github.qcloudsms.httpclient.HTTPClient;
import com.github.qcloudsms.httpclient.HTTPException;
import com.github.qcloudsms.httpclient.HTTPResponse;
package com.github.qcloudsms;
public class SmsBase {
protected int appid;
protected String appkey;
protected HTTPClient httpclient;
/**
* SmsBase constructor
*
* @param appid sdk appid
* @param appkey sdk appkey
* @param httpclient http client
*/
public SmsBase(int appid, String appkey, HTTPClient httpclient) {
this.appid = appid;
this.appkey = appkey;
this.httpclient = httpclient;
}
/**
* Handle http status error
*
* @param response raw http response
* @return response raw http response
* @throws HTTPException http status exception
*/ | public HTTPResponse handleError(HTTPResponse response) throws HTTPException { |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/SmsStatusPullCallbackResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.ArrayList; | }
if (json.has("report_status")) {
report_status = json.getString("report_status");
}
if (json.has("errmsg")) {
errmsg = json.getString("errmsg");
}
if (json.has("description")) {
description = json.getString("description");
}
if (json.has("sid")) {
sid = json.getString("sid");
}
return this;
}
}
public int result;
public String errMsg;
public int count;
public ArrayList<Callback> callbacks;
public SmsStatusPullCallbackResult() {
this.errMsg = "";
this.count = 0;
this.callbacks = new ArrayList<Callback>();
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/SmsStatusPullCallbackResult.java
import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.ArrayList;
}
if (json.has("report_status")) {
report_status = json.getString("report_status");
}
if (json.has("errmsg")) {
errmsg = json.getString("errmsg");
}
if (json.has("description")) {
description = json.getString("description");
}
if (json.has("sid")) {
sid = json.getString("sid");
}
return this;
}
}
public int result;
public String errMsg;
public int count;
public ArrayList<Callback> callbacks;
public SmsStatusPullCallbackResult() {
this.errMsg = "";
this.count = 0;
this.callbacks = new ArrayList<Callback>();
}
@Override | public SmsStatusPullCallbackResult parseFromHTTPResponse(HTTPResponse response) |
qcloudsms/qcloudsms_java | src/main/java/com/github/qcloudsms/FileVoiceSenderResult.java | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
| import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException; | package com.github.qcloudsms;
public class FileVoiceSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String callid;
public FileVoiceSenderResult() {
this.errMsg = "";
this.ext = "";
this.callid = "";
}
@Override | // Path: src/main/java/com/github/qcloudsms/httpclient/HTTPResponse.java
// public class HTTPResponse {
//
// public HTTPRequest request;
// public int statusCode;
// public String reason;
// public String body;
// public HashMap<String, String> headers;
//
// public HTTPResponse() {
// this.headers = new HashMap<String, String>();
// }
//
// public HTTPResponse(final int statusCode) {
// this();
// this.statusCode = statusCode;
// }
//
// public HTTPResponse(final int statusCode, final String body) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// }
//
// public HTTPResponse(final int statusCode, final String body, final String reason) {
// super();
// this.statusCode = statusCode;
// this.body = body;
// this.reason = reason;
// }
//
// public HTTPResponse setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// return this;
// }
//
// public HTTPResponse setBody(String body) {
// this.body = body;
// return this;
// }
//
// public HTTPResponse setReason(String reason) {
// this.reason = reason;
// return this;
// }
//
// public HTTPResponse addHeader(String name, String value) {
// headers.put(name, value);
// return this;
// }
//
// public HTTPResponse setRequest(HTTPRequest request) {
// this.request = request;
// return this;
// }
// }
// Path: src/main/java/com/github/qcloudsms/FileVoiceSenderResult.java
import com.github.qcloudsms.httpclient.HTTPResponse;
import org.json.JSONObject;
import org.json.JSONException;
package com.github.qcloudsms;
public class FileVoiceSenderResult extends SmsResultBase {
public int result;
public String errMsg;
public String ext;
public String callid;
public FileVoiceSenderResult() {
this.errMsg = "";
this.ext = "";
this.callid = "";
}
@Override | public FileVoiceSenderResult parseFromHTTPResponse(HTTPResponse response) |
HY-ZhengWei/XSSO | src/org/hy/xsso/appInterfaces/servlet/GetAccessTokenServlet.java | // Path: src/org/hy/xsso/appInterfaces/servlet/bean/TokenResponse.java
// public class TokenResponse extends BaseResponse
// {
//
// private static final long serialVersionUID = 2652864387178948149L;
//
// /** 响应数据 */
// private TokenResponseData data;
//
//
//
// /**
// * 获取:响应数据
// */
// public TokenResponseData getData()
// {
// return data;
// }
//
//
// /**
// * 设置:响应数据
// *
// * @param data
// */
// public void setData(TokenResponseData data)
// {
// this.data = data;
// }
//
// }
//
// Path: src/org/hy/xsso/appInterfaces/servlet/bean/TokenResponseData.java
// public class TokenResponseData extends SerializableDef
// {
//
// private static final long serialVersionUID = 2029220892157842421L;
//
// /** 过期时长(单位:秒) */
// private Integer expire;
//
// /** 访问Token */
// private String access_token;
//
//
//
// /**
// * 获取:过期时长(单位:秒)
// */
// public Integer getExpire()
// {
// return expire;
// }
//
//
// /**
// * 获取:访问Token
// */
// public String getAccess_token()
// {
// return access_token;
// }
//
//
// /**
// * 设置:过期时长(单位:秒)
// *
// * @param expire
// */
// public void setExpire(Integer expire)
// {
// this.expire = expire;
// }
//
//
// /**
// * 设置:访问Token
// *
// * @param access_token
// */
// public void setAccess_token(String access_token)
// {
// this.access_token = access_token;
// }
//
// }
//
// Path: src/org/hy/xsso/common/BaseServlet.java
// public class BaseServlet extends HttpServlet
// {
//
// private static final long serialVersionUID = 123638522879125889L;
//
// public static final String $Succeed = "200";
//
//
//
// /**
// * 返回Json字符格式的结果
// *
// * @author ZhengWei(HY)
// * @createDate 2020-12-28
// * @version v1.0
// *
// * @param i_Data
// * @return
// * @throws Exception
// */
// protected String toReturn(Object i_Data) throws Exception
// {
// XJSON v_XJ = new XJSON();
//
// v_XJ.setReturnNVL(false);
//
// return v_XJ.toJson(i_Data).toJSONString();
// }
//
//
//
// /**
// * 获取Post请求Body中的数据
// *
// * @author ZhengWei(HY)
// * @createDate 2020-12-31
// * @version v1.0
// *
// * @param i_Request
// * @return
// */
// protected String getPostData(HttpServletRequest i_Request)
// {
// return FileHelp.getContent(i_Request);
// }
// }
| import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hy.common.Date;
import org.hy.common.ExpireMap;
import org.hy.common.Help;
import org.hy.common.StringHelp;
import org.hy.common.license.AppKey;
import org.hy.common.license.SignProvider;
import org.hy.common.xml.XJava;
import org.hy.common.xml.log.Logger;
import org.hy.xsso.appInterfaces.servlet.bean.TokenResponse;
import org.hy.xsso.appInterfaces.servlet.bean.TokenResponseData;
import org.hy.xsso.common.BaseServlet; | v_ResponseData.setCode("10012");
v_ResponseData.setMessage("时间戳无效或已过期!");
i_Response.getWriter().println(this.toReturn(v_ResponseData));
return;
}
if ( Help.isNull(v_Signature) )
{
v_ResponseData.setCode("10013");
v_ResponseData.setMessage("签名不正确!");
i_Response.getWriter().println(this.toReturn(v_ResponseData));
return;
}
String v_Code = "appKey" + v_AppKeyStr + "timestamp" + v_Timestamp;
AppKey v_AppKey = $AppKeys.get(v_AppKeyStr);
boolean v_Verify = SignProvider.verify(v_AppKey.getPublicKey().getBytes() ,v_Code ,v_Signature.getBytes("UTF-8"));
if ( !v_Verify )
{
v_ResponseData.setCode("10013");
v_ResponseData.setMessage("签名不正确!");
i_Response.getWriter().println(this.toReturn(v_ResponseData));
return;
}
v_ResponseData.setCode($Succeed);
v_ResponseData.setMessage("成功"); | // Path: src/org/hy/xsso/appInterfaces/servlet/bean/TokenResponse.java
// public class TokenResponse extends BaseResponse
// {
//
// private static final long serialVersionUID = 2652864387178948149L;
//
// /** 响应数据 */
// private TokenResponseData data;
//
//
//
// /**
// * 获取:响应数据
// */
// public TokenResponseData getData()
// {
// return data;
// }
//
//
// /**
// * 设置:响应数据
// *
// * @param data
// */
// public void setData(TokenResponseData data)
// {
// this.data = data;
// }
//
// }
//
// Path: src/org/hy/xsso/appInterfaces/servlet/bean/TokenResponseData.java
// public class TokenResponseData extends SerializableDef
// {
//
// private static final long serialVersionUID = 2029220892157842421L;
//
// /** 过期时长(单位:秒) */
// private Integer expire;
//
// /** 访问Token */
// private String access_token;
//
//
//
// /**
// * 获取:过期时长(单位:秒)
// */
// public Integer getExpire()
// {
// return expire;
// }
//
//
// /**
// * 获取:访问Token
// */
// public String getAccess_token()
// {
// return access_token;
// }
//
//
// /**
// * 设置:过期时长(单位:秒)
// *
// * @param expire
// */
// public void setExpire(Integer expire)
// {
// this.expire = expire;
// }
//
//
// /**
// * 设置:访问Token
// *
// * @param access_token
// */
// public void setAccess_token(String access_token)
// {
// this.access_token = access_token;
// }
//
// }
//
// Path: src/org/hy/xsso/common/BaseServlet.java
// public class BaseServlet extends HttpServlet
// {
//
// private static final long serialVersionUID = 123638522879125889L;
//
// public static final String $Succeed = "200";
//
//
//
// /**
// * 返回Json字符格式的结果
// *
// * @author ZhengWei(HY)
// * @createDate 2020-12-28
// * @version v1.0
// *
// * @param i_Data
// * @return
// * @throws Exception
// */
// protected String toReturn(Object i_Data) throws Exception
// {
// XJSON v_XJ = new XJSON();
//
// v_XJ.setReturnNVL(false);
//
// return v_XJ.toJson(i_Data).toJSONString();
// }
//
//
//
// /**
// * 获取Post请求Body中的数据
// *
// * @author ZhengWei(HY)
// * @createDate 2020-12-31
// * @version v1.0
// *
// * @param i_Request
// * @return
// */
// protected String getPostData(HttpServletRequest i_Request)
// {
// return FileHelp.getContent(i_Request);
// }
// }
// Path: src/org/hy/xsso/appInterfaces/servlet/GetAccessTokenServlet.java
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hy.common.Date;
import org.hy.common.ExpireMap;
import org.hy.common.Help;
import org.hy.common.StringHelp;
import org.hy.common.license.AppKey;
import org.hy.common.license.SignProvider;
import org.hy.common.xml.XJava;
import org.hy.common.xml.log.Logger;
import org.hy.xsso.appInterfaces.servlet.bean.TokenResponse;
import org.hy.xsso.appInterfaces.servlet.bean.TokenResponseData;
import org.hy.xsso.common.BaseServlet;
v_ResponseData.setCode("10012");
v_ResponseData.setMessage("时间戳无效或已过期!");
i_Response.getWriter().println(this.toReturn(v_ResponseData));
return;
}
if ( Help.isNull(v_Signature) )
{
v_ResponseData.setCode("10013");
v_ResponseData.setMessage("签名不正确!");
i_Response.getWriter().println(this.toReturn(v_ResponseData));
return;
}
String v_Code = "appKey" + v_AppKeyStr + "timestamp" + v_Timestamp;
AppKey v_AppKey = $AppKeys.get(v_AppKeyStr);
boolean v_Verify = SignProvider.verify(v_AppKey.getPublicKey().getBytes() ,v_Code ,v_Signature.getBytes("UTF-8"));
if ( !v_Verify )
{
v_ResponseData.setCode("10013");
v_ResponseData.setMessage("签名不正确!");
i_Response.getWriter().println(this.toReturn(v_ResponseData));
return;
}
v_ResponseData.setCode($Succeed);
v_ResponseData.setMessage("成功"); | v_ResponseData.setData(new TokenResponseData()); |
HY-ZhengWei/XSSO | src/org/hy/xsso/appInterfaces/servlet/LogoutUserServlet.java | // Path: src/org/hy/xsso/common/BaseResponse.java
// public class BaseResponse extends SerializableDef
// {
//
// private static final long serialVersionUID = -393692673433172315L;
//
//
//
// /** 响应代码 */
// private String code;
//
// /** 响应消息 */
// private String message;
//
//
//
// /**
// * 获取:响应代码
// */
// public String getCode()
// {
// return code;
// }
//
//
// /**
// * 获取:响应消息
// */
// public String getMessage()
// {
// return message;
// }
//
//
// /**
// * 设置:响应代码
// *
// * @param code
// */
// public void setCode(String code)
// {
// this.code = code;
// }
//
//
// /**
// * 设置:响应消息
// *
// * @param message
// */
// public void setMessage(String message)
// {
// this.message = message;
// }
//
// }
//
// Path: src/org/hy/xsso/common/BaseServlet.java
// public class BaseServlet extends HttpServlet
// {
//
// private static final long serialVersionUID = 123638522879125889L;
//
// public static final String $Succeed = "200";
//
//
//
// /**
// * 返回Json字符格式的结果
// *
// * @author ZhengWei(HY)
// * @createDate 2020-12-28
// * @version v1.0
// *
// * @param i_Data
// * @return
// * @throws Exception
// */
// protected String toReturn(Object i_Data) throws Exception
// {
// XJSON v_XJ = new XJSON();
//
// v_XJ.setReturnNVL(false);
//
// return v_XJ.toJson(i_Data).toJSONString();
// }
//
//
//
// /**
// * 获取Post请求Body中的数据
// *
// * @author ZhengWei(HY)
// * @createDate 2020-12-31
// * @version v1.0
// *
// * @param i_Request
// * @return
// */
// protected String getPostData(HttpServletRequest i_Request)
// {
// return FileHelp.getContent(i_Request);
// }
// }
//
// Path: src/org/hy/xsso/net/LogoutListener.java
// public class LogoutListener implements CommunicationListener
// {
//
// /**
// * 数据通讯的事件类型。即通知哪一个事件监听者来处理数据通讯(对应 ServerSocket.listeners 的分区标识)
// *
// * 事件类型区分大小写
// *
// * @author ZhengWei(HY)
// * @createDate 2017-02-04
// * @version v1.0
// *
// * @return
// */
// public String getEventType()
// {
// return "logout";
// }
//
//
//
// /**
// * 数据通讯事件的执行动作
// *
// * @author ZhengWei(HY)
// * @createDate 2017-02-04
// * @version v1.0
// *
// * @param i_RequestData
// * @return
// */
// public CommunicationResponse communication(CommunicationRequest i_RequestData)
// {
// CommunicationResponse v_ResponseData = new CommunicationResponse();
//
// if ( Help.isNull(i_RequestData.getDataXID()) )
// {
// v_ResponseData.setResult(1);
// return v_ResponseData;
// }
//
// v_ResponseData.setDataXID(i_RequestData.getDataXID());
// logout(i_RequestData.getDataXID());
//
// return v_ResponseData;
// }
//
//
//
// /**
// * 用户退出
// *
// * @author ZhengWei(HY)
// * @createDate 2021-01-05
// * @version v1.0
// *
// * @param i_DataXID
// */
// public static void logout(String i_DataXID)
// {
// Log.log(":USID 用户退出,票据失效。" ,i_DataXID);
//
// XJava.remove(i_DataXID);
// AppCluster.logoutCluster(i_DataXID);
// }
//
// }
| import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hy.common.Help;
import org.hy.common.StringHelp;
import org.hy.common.xml.log.Logger;
import org.hy.xsso.common.BaseResponse;
import org.hy.xsso.common.BaseServlet;
import org.hy.xsso.net.LogoutListener; | package org.hy.xsso.appInterfaces.servlet;
/**
* 单点登录第五步:用户退出。
*
* @author ZhengWei(HY)
* @createDate 2021-01-05
* @version v1.0
*/
public class LogoutUserServlet extends BaseServlet
{
private static final long serialVersionUID = 3708848763509595148L;
private static final Logger $Logger = new Logger(LogoutUserServlet.class);
public void doGet(HttpServletRequest i_Request, HttpServletResponse i_Response) throws ServletException, IOException
{
i_Response.setCharacterEncoding("UTF-8");
i_Response.setContentType("application/json");
| // Path: src/org/hy/xsso/common/BaseResponse.java
// public class BaseResponse extends SerializableDef
// {
//
// private static final long serialVersionUID = -393692673433172315L;
//
//
//
// /** 响应代码 */
// private String code;
//
// /** 响应消息 */
// private String message;
//
//
//
// /**
// * 获取:响应代码
// */
// public String getCode()
// {
// return code;
// }
//
//
// /**
// * 获取:响应消息
// */
// public String getMessage()
// {
// return message;
// }
//
//
// /**
// * 设置:响应代码
// *
// * @param code
// */
// public void setCode(String code)
// {
// this.code = code;
// }
//
//
// /**
// * 设置:响应消息
// *
// * @param message
// */
// public void setMessage(String message)
// {
// this.message = message;
// }
//
// }
//
// Path: src/org/hy/xsso/common/BaseServlet.java
// public class BaseServlet extends HttpServlet
// {
//
// private static final long serialVersionUID = 123638522879125889L;
//
// public static final String $Succeed = "200";
//
//
//
// /**
// * 返回Json字符格式的结果
// *
// * @author ZhengWei(HY)
// * @createDate 2020-12-28
// * @version v1.0
// *
// * @param i_Data
// * @return
// * @throws Exception
// */
// protected String toReturn(Object i_Data) throws Exception
// {
// XJSON v_XJ = new XJSON();
//
// v_XJ.setReturnNVL(false);
//
// return v_XJ.toJson(i_Data).toJSONString();
// }
//
//
//
// /**
// * 获取Post请求Body中的数据
// *
// * @author ZhengWei(HY)
// * @createDate 2020-12-31
// * @version v1.0
// *
// * @param i_Request
// * @return
// */
// protected String getPostData(HttpServletRequest i_Request)
// {
// return FileHelp.getContent(i_Request);
// }
// }
//
// Path: src/org/hy/xsso/net/LogoutListener.java
// public class LogoutListener implements CommunicationListener
// {
//
// /**
// * 数据通讯的事件类型。即通知哪一个事件监听者来处理数据通讯(对应 ServerSocket.listeners 的分区标识)
// *
// * 事件类型区分大小写
// *
// * @author ZhengWei(HY)
// * @createDate 2017-02-04
// * @version v1.0
// *
// * @return
// */
// public String getEventType()
// {
// return "logout";
// }
//
//
//
// /**
// * 数据通讯事件的执行动作
// *
// * @author ZhengWei(HY)
// * @createDate 2017-02-04
// * @version v1.0
// *
// * @param i_RequestData
// * @return
// */
// public CommunicationResponse communication(CommunicationRequest i_RequestData)
// {
// CommunicationResponse v_ResponseData = new CommunicationResponse();
//
// if ( Help.isNull(i_RequestData.getDataXID()) )
// {
// v_ResponseData.setResult(1);
// return v_ResponseData;
// }
//
// v_ResponseData.setDataXID(i_RequestData.getDataXID());
// logout(i_RequestData.getDataXID());
//
// return v_ResponseData;
// }
//
//
//
// /**
// * 用户退出
// *
// * @author ZhengWei(HY)
// * @createDate 2021-01-05
// * @version v1.0
// *
// * @param i_DataXID
// */
// public static void logout(String i_DataXID)
// {
// Log.log(":USID 用户退出,票据失效。" ,i_DataXID);
//
// XJava.remove(i_DataXID);
// AppCluster.logoutCluster(i_DataXID);
// }
//
// }
// Path: src/org/hy/xsso/appInterfaces/servlet/LogoutUserServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hy.common.Help;
import org.hy.common.StringHelp;
import org.hy.common.xml.log.Logger;
import org.hy.xsso.common.BaseResponse;
import org.hy.xsso.common.BaseServlet;
import org.hy.xsso.net.LogoutListener;
package org.hy.xsso.appInterfaces.servlet;
/**
* 单点登录第五步:用户退出。
*
* @author ZhengWei(HY)
* @createDate 2021-01-05
* @version v1.0
*/
public class LogoutUserServlet extends BaseServlet
{
private static final long serialVersionUID = 3708848763509595148L;
private static final Logger $Logger = new Logger(LogoutUserServlet.class);
public void doGet(HttpServletRequest i_Request, HttpServletResponse i_Response) throws ServletException, IOException
{
i_Response.setCharacterEncoding("UTF-8");
i_Response.setContentType("application/json");
| BaseResponse v_ResponseData = new BaseResponse(); |
crukci-bioinformatics/MGA | src/main/java/org/cruk/mga/MultiGenomeAlignmentSummary.java | // Path: src/main/java/org/cruk/util/OrderedProperties.java
// public class OrderedProperties extends LinkedMap<String, String>
// {
// private static final long serialVersionUID = 8837732667981161564L;
//
// /**
// * Get the key set as an array.
// *
// * @return The key set as an array.
// *
// * @deprecated Use {@link #keySet()} instead and work with the collection.
// */
// @Deprecated
// public String[] getPropertyNames()
// {
// return keySet().toArray(new String[0]);
// }
//
// /**
// * Set a key to a value.
// *
// * @param name The key.
// * @param value The value;
// *
// * @deprecated Use {@link #put(String, String)} instead.
// */
// @Deprecated
// public void setProperty(String name, String value)
// {
// put(name, value);
// }
//
// /**
// * Get a value by key.
// *
// * @param name The key of the value to get.
// *
// * @return The value matching the given key, or null if there is no match.
// *
// * @deprecated Use {@link #get(Object)} instead.
// */
// public String getProperty(String name)
// {
// return get(name);
// }
//
// /**
// * Returns the value of the property matching the first of the given
// * set of names.
// *
// * @param names the possible names for the property.
// * @return the property value.
// */
// public String getProperty(String[] names)
// {
// for (String name : names)
// {
// String value = get(name);
// if (value != null) return value;
// }
// return null;
// }
//
// /**
// * Remove a key and value from the map.
// *
// * @param name The key.
// * @return The value removed, or null.
// *
// * @deprecated Use {@link #remove(Object)} instead.
// */
// @Deprecated
// public String removeProperty(String name)
// {
// return remove(name);
// }
// }
| import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.cruk.util.OrderedProperties;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Cancer Research UK Cambridge Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.cruk.mga;
/**
* Class used to represent the summary of alignments of a sequence
* dataset against a multiple reference genomes.
*
* @author eldrid01
*
*/
public class MultiGenomeAlignmentSummary implements Serializable
{
private static final long serialVersionUID = 7594987898110254817L;
private String datasetId;
private long sequenceCount;
private int sampledCount;
private int trimLength;
private int adapterCount;
private int alignedCount;
private Map<String, AlignmentSummary> alignmentSummaries = new HashMap<String, AlignmentSummary>(); | // Path: src/main/java/org/cruk/util/OrderedProperties.java
// public class OrderedProperties extends LinkedMap<String, String>
// {
// private static final long serialVersionUID = 8837732667981161564L;
//
// /**
// * Get the key set as an array.
// *
// * @return The key set as an array.
// *
// * @deprecated Use {@link #keySet()} instead and work with the collection.
// */
// @Deprecated
// public String[] getPropertyNames()
// {
// return keySet().toArray(new String[0]);
// }
//
// /**
// * Set a key to a value.
// *
// * @param name The key.
// * @param value The value;
// *
// * @deprecated Use {@link #put(String, String)} instead.
// */
// @Deprecated
// public void setProperty(String name, String value)
// {
// put(name, value);
// }
//
// /**
// * Get a value by key.
// *
// * @param name The key of the value to get.
// *
// * @return The value matching the given key, or null if there is no match.
// *
// * @deprecated Use {@link #get(Object)} instead.
// */
// public String getProperty(String name)
// {
// return get(name);
// }
//
// /**
// * Returns the value of the property matching the first of the given
// * set of names.
// *
// * @param names the possible names for the property.
// * @return the property value.
// */
// public String getProperty(String[] names)
// {
// for (String name : names)
// {
// String value = get(name);
// if (value != null) return value;
// }
// return null;
// }
//
// /**
// * Remove a key and value from the map.
// *
// * @param name The key.
// * @return The value removed, or null.
// *
// * @deprecated Use {@link #remove(Object)} instead.
// */
// @Deprecated
// public String removeProperty(String name)
// {
// return remove(name);
// }
// }
// Path: src/main/java/org/cruk/mga/MultiGenomeAlignmentSummary.java
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.cruk.util.OrderedProperties;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Cancer Research UK Cambridge Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.cruk.mga;
/**
* Class used to represent the summary of alignments of a sequence
* dataset against a multiple reference genomes.
*
* @author eldrid01
*
*/
public class MultiGenomeAlignmentSummary implements Serializable
{
private static final long serialVersionUID = 7594987898110254817L;
private String datasetId;
private long sequenceCount;
private int sampledCount;
private int trimLength;
private int adapterCount;
private int alignedCount;
private Map<String, AlignmentSummary> alignmentSummaries = new HashMap<String, AlignmentSummary>(); | private List<OrderedProperties> sampleProperties = new ArrayList<OrderedProperties>(); |
crukci-bioinformatics/MGA | src/main/java/org/cruk/mga/export/Properties.java | // Path: src/main/java/org/cruk/util/OrderedProperties.java
// public class OrderedProperties extends LinkedMap<String, String>
// {
// private static final long serialVersionUID = 8837732667981161564L;
//
// /**
// * Get the key set as an array.
// *
// * @return The key set as an array.
// *
// * @deprecated Use {@link #keySet()} instead and work with the collection.
// */
// @Deprecated
// public String[] getPropertyNames()
// {
// return keySet().toArray(new String[0]);
// }
//
// /**
// * Set a key to a value.
// *
// * @param name The key.
// * @param value The value;
// *
// * @deprecated Use {@link #put(String, String)} instead.
// */
// @Deprecated
// public void setProperty(String name, String value)
// {
// put(name, value);
// }
//
// /**
// * Get a value by key.
// *
// * @param name The key of the value to get.
// *
// * @return The value matching the given key, or null if there is no match.
// *
// * @deprecated Use {@link #get(Object)} instead.
// */
// public String getProperty(String name)
// {
// return get(name);
// }
//
// /**
// * Returns the value of the property matching the first of the given
// * set of names.
// *
// * @param names the possible names for the property.
// * @return the property value.
// */
// public String getProperty(String[] names)
// {
// for (String name : names)
// {
// String value = get(name);
// if (value != null) return value;
// }
// return null;
// }
//
// /**
// * Remove a key and value from the map.
// *
// * @param name The key.
// * @return The value removed, or null.
// *
// * @deprecated Use {@link #remove(Object)} instead.
// */
// @Deprecated
// public String removeProperty(String name)
// {
// return remove(name);
// }
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.cruk.util.OrderedProperties; | package org.cruk.mga.export;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType
public class Properties implements Serializable
{
private static final long serialVersionUID = -8315790482372848478L;
@XmlElement(name = "Property")
private List<Property> properties;
public Properties()
{
}
| // Path: src/main/java/org/cruk/util/OrderedProperties.java
// public class OrderedProperties extends LinkedMap<String, String>
// {
// private static final long serialVersionUID = 8837732667981161564L;
//
// /**
// * Get the key set as an array.
// *
// * @return The key set as an array.
// *
// * @deprecated Use {@link #keySet()} instead and work with the collection.
// */
// @Deprecated
// public String[] getPropertyNames()
// {
// return keySet().toArray(new String[0]);
// }
//
// /**
// * Set a key to a value.
// *
// * @param name The key.
// * @param value The value;
// *
// * @deprecated Use {@link #put(String, String)} instead.
// */
// @Deprecated
// public void setProperty(String name, String value)
// {
// put(name, value);
// }
//
// /**
// * Get a value by key.
// *
// * @param name The key of the value to get.
// *
// * @return The value matching the given key, or null if there is no match.
// *
// * @deprecated Use {@link #get(Object)} instead.
// */
// public String getProperty(String name)
// {
// return get(name);
// }
//
// /**
// * Returns the value of the property matching the first of the given
// * set of names.
// *
// * @param names the possible names for the property.
// * @return the property value.
// */
// public String getProperty(String[] names)
// {
// for (String name : names)
// {
// String value = get(name);
// if (value != null) return value;
// }
// return null;
// }
//
// /**
// * Remove a key and value from the map.
// *
// * @param name The key.
// * @return The value removed, or null.
// *
// * @deprecated Use {@link #remove(Object)} instead.
// */
// @Deprecated
// public String removeProperty(String name)
// {
// return remove(name);
// }
// }
// Path: src/main/java/org/cruk/mga/export/Properties.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.cruk.util.OrderedProperties;
package org.cruk.mga.export;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType
public class Properties implements Serializable
{
private static final long serialVersionUID = -8315790482372848478L;
@XmlElement(name = "Property")
private List<Property> properties;
public Properties()
{
}
| public Properties(OrderedProperties props) |
crukci-bioinformatics/MGA | src/main/java/org/cruk/mga/export/Sample.java | // Path: src/main/java/org/cruk/util/OrderedProperties.java
// public class OrderedProperties extends LinkedMap<String, String>
// {
// private static final long serialVersionUID = 8837732667981161564L;
//
// /**
// * Get the key set as an array.
// *
// * @return The key set as an array.
// *
// * @deprecated Use {@link #keySet()} instead and work with the collection.
// */
// @Deprecated
// public String[] getPropertyNames()
// {
// return keySet().toArray(new String[0]);
// }
//
// /**
// * Set a key to a value.
// *
// * @param name The key.
// * @param value The value;
// *
// * @deprecated Use {@link #put(String, String)} instead.
// */
// @Deprecated
// public void setProperty(String name, String value)
// {
// put(name, value);
// }
//
// /**
// * Get a value by key.
// *
// * @param name The key of the value to get.
// *
// * @return The value matching the given key, or null if there is no match.
// *
// * @deprecated Use {@link #get(Object)} instead.
// */
// public String getProperty(String name)
// {
// return get(name);
// }
//
// /**
// * Returns the value of the property matching the first of the given
// * set of names.
// *
// * @param names the possible names for the property.
// * @return the property value.
// */
// public String getProperty(String[] names)
// {
// for (String name : names)
// {
// String value = get(name);
// if (value != null) return value;
// }
// return null;
// }
//
// /**
// * Remove a key and value from the map.
// *
// * @param name The key.
// * @return The value removed, or null.
// *
// * @deprecated Use {@link #remove(Object)} instead.
// */
// @Deprecated
// public String removeProperty(String name)
// {
// return remove(name);
// }
// }
| import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.cruk.util.OrderedProperties; | package org.cruk.mga.export;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType
public class Sample implements Serializable
{
private static final long serialVersionUID = -8710245839002445380L;
@XmlElement(name = "Properties")
private Properties properties;
public Sample()
{
}
| // Path: src/main/java/org/cruk/util/OrderedProperties.java
// public class OrderedProperties extends LinkedMap<String, String>
// {
// private static final long serialVersionUID = 8837732667981161564L;
//
// /**
// * Get the key set as an array.
// *
// * @return The key set as an array.
// *
// * @deprecated Use {@link #keySet()} instead and work with the collection.
// */
// @Deprecated
// public String[] getPropertyNames()
// {
// return keySet().toArray(new String[0]);
// }
//
// /**
// * Set a key to a value.
// *
// * @param name The key.
// * @param value The value;
// *
// * @deprecated Use {@link #put(String, String)} instead.
// */
// @Deprecated
// public void setProperty(String name, String value)
// {
// put(name, value);
// }
//
// /**
// * Get a value by key.
// *
// * @param name The key of the value to get.
// *
// * @return The value matching the given key, or null if there is no match.
// *
// * @deprecated Use {@link #get(Object)} instead.
// */
// public String getProperty(String name)
// {
// return get(name);
// }
//
// /**
// * Returns the value of the property matching the first of the given
// * set of names.
// *
// * @param names the possible names for the property.
// * @return the property value.
// */
// public String getProperty(String[] names)
// {
// for (String name : names)
// {
// String value = get(name);
// if (value != null) return value;
// }
// return null;
// }
//
// /**
// * Remove a key and value from the map.
// *
// * @param name The key.
// * @return The value removed, or null.
// *
// * @deprecated Use {@link #remove(Object)} instead.
// */
// @Deprecated
// public String removeProperty(String name)
// {
// return remove(name);
// }
// }
// Path: src/main/java/org/cruk/mga/export/Sample.java
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.cruk.util.OrderedProperties;
package org.cruk.mga.export;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType
public class Sample implements Serializable
{
private static final long serialVersionUID = -8710245839002445380L;
@XmlElement(name = "Properties")
private Properties properties;
public Sample()
{
}
| public Sample(OrderedProperties props) |
knightliao/disconf | disconf-client/src/main/java/com/baidu/disconf/client/watch/WatchMgr.java | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
| import com.baidu.disconf.client.common.model.DisConfCommonModel;
import com.baidu.disconf.client.core.processor.DisconfCoreProcessor;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum; | package com.baidu.disconf.client.watch;
/**
* 监控的接口
*
* @author liaoqiqi
* @version 2014-7-29
*/
public interface WatchMgr {
/**
* 初始化
*
* @throws Exception
*/
void init(String hosts, String zooUrlPrefix, boolean debug) throws Exception;
/**
* 监控路径,监控前会事先创建路径,并且会新建一个自己的Temp子结点
*/
void watchPath(DisconfCoreProcessor disconfCoreMgr, DisConfCommonModel disConfCommonModel, String keyName, | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
// Path: disconf-client/src/main/java/com/baidu/disconf/client/watch/WatchMgr.java
import com.baidu.disconf.client.common.model.DisConfCommonModel;
import com.baidu.disconf.client.core.processor.DisconfCoreProcessor;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
package com.baidu.disconf.client.watch;
/**
* 监控的接口
*
* @author liaoqiqi
* @version 2014-7-29
*/
public interface WatchMgr {
/**
* 初始化
*
* @throws Exception
*/
void init(String hosts, String zooUrlPrefix, boolean debug) throws Exception;
/**
* 监控路径,监控前会事先创建路径,并且会新建一个自己的Temp子结点
*/
void watchPath(DisconfCoreProcessor disconfCoreMgr, DisConfCommonModel disConfCommonModel, String keyName, | DisConfigTypeEnum disConfigTypeEnum, String value) throws Exception; |
knightliao/disconf | disconf-core/src/main/java/com/baidu/disconf/core/common/restful/type/RestfulGet.java | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/utils/http/impl/HttpResponseCallbackHandlerJsonHandler.java
// public class HttpResponseCallbackHandlerJsonHandler<T> implements HttpResponseCallbackHandler<T> {
//
// private Class<T> clazz = null;
//
// public HttpResponseCallbackHandlerJsonHandler(Class<T> clazz) {
// this.clazz = clazz;
// }
//
// @Override
// public T handleResponse(String requestBody, HttpEntity entity) throws IOException {
//
// String json = EntityUtils.toString(entity, "UTF-8");
//
// com.google.gson.Gson gson = new com.google.gson.Gson();
// T response = gson.fromJson(json, clazz);
//
// return response;
// }
// }
| import java.net.URL;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.disconf.core.common.restful.core.UnreliableInterface;
import com.baidu.disconf.core.common.utils.http.impl.HttpResponseCallbackHandlerJsonHandler;
import com.baidu.disconf.core.common.utils.http.HttpClientUtil;
import com.baidu.disconf.core.common.utils.http.HttpResponseCallbackHandler; | package com.baidu.disconf.core.common.restful.type;
/**
* RestFul get
*
* @author liaoqiqi
* @version 2014-6-16
*/
public class RestfulGet<T> implements UnreliableInterface {
protected static final Logger LOGGER = LoggerFactory.getLogger(RestfulGet.class);
private HttpRequestBase request = null;
private HttpResponseCallbackHandler<T> httpResponseCallbackHandler = null;
public RestfulGet(Class<T> clazz, URL url) {
HttpGet request = new HttpGet(url.toString());
request.addHeader("content-type", "application/json");
this.request = request;
this.httpResponseCallbackHandler = new | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/utils/http/impl/HttpResponseCallbackHandlerJsonHandler.java
// public class HttpResponseCallbackHandlerJsonHandler<T> implements HttpResponseCallbackHandler<T> {
//
// private Class<T> clazz = null;
//
// public HttpResponseCallbackHandlerJsonHandler(Class<T> clazz) {
// this.clazz = clazz;
// }
//
// @Override
// public T handleResponse(String requestBody, HttpEntity entity) throws IOException {
//
// String json = EntityUtils.toString(entity, "UTF-8");
//
// com.google.gson.Gson gson = new com.google.gson.Gson();
// T response = gson.fromJson(json, clazz);
//
// return response;
// }
// }
// Path: disconf-core/src/main/java/com/baidu/disconf/core/common/restful/type/RestfulGet.java
import java.net.URL;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.disconf.core.common.restful.core.UnreliableInterface;
import com.baidu.disconf.core.common.utils.http.impl.HttpResponseCallbackHandlerJsonHandler;
import com.baidu.disconf.core.common.utils.http.HttpClientUtil;
import com.baidu.disconf.core.common.utils.http.HttpResponseCallbackHandler;
package com.baidu.disconf.core.common.restful.type;
/**
* RestFul get
*
* @author liaoqiqi
* @version 2014-6-16
*/
public class RestfulGet<T> implements UnreliableInterface {
protected static final Logger LOGGER = LoggerFactory.getLogger(RestfulGet.class);
private HttpRequestBase request = null;
private HttpResponseCallbackHandler<T> httpResponseCallbackHandler = null;
public RestfulGet(Class<T> clazz, URL url) {
HttpGet request = new HttpGet(url.toString());
request.addHeader("content-type", "application/json");
this.request = request;
this.httpResponseCallbackHandler = new | HttpResponseCallbackHandlerJsonHandler<T>(clazz); |
knightliao/disconf | disconf-web/src/main/java/com/baidu/disconf/web/service/config/service/ConfigMgr.java | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
| import java.io.File;
import java.util.List;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.web.service.config.bo.Config;
import com.baidu.disconf.web.service.config.form.ConfListForm;
import com.baidu.disconf.web.service.config.form.ConfNewItemForm;
import com.baidu.disconf.web.service.config.vo.ConfListVo;
import com.baidu.disconf.web.service.config.vo.MachineListVo;
import com.baidu.ub.common.db.DaoPageResult; | package com.baidu.disconf.web.service.config.service;
/**
* @author liaoqiqi
* @version 2014-6-16
*/
public interface ConfigMgr {
/**
* @param
*
* @return
*/
List<String> getVersionListByAppEnv(Long appId, Long envId);
/**
* @return
*/
DaoPageResult<ConfListVo> getConfigList(ConfListForm confListForm, boolean fetchZk, final boolean getErrorMessage);
/**
* @param configId
*
* @return
*/
ConfListVo getConfVo(Long configId);
/**
* @param configId
*
* @return
*/
MachineListVo getConfVoWithZk(Long configId);
/**
* @param configId
*
* @return
*/
Config getConfigById(Long configId);
/**
* 更新 配置项/配置文件
*
* @param configId
*
* @return
*/
String updateItemValue(Long configId, String value);
/**
* 获取config value
*
* @param configId
*
* @return
*/
String getValue(Long configId);
/**
* 通知zk
*
* @param configId
*/
void notifyZookeeper(Long configId);
/**
* 新建一个config
*
* @param confNewForm
* @param disConfigTypeEnum
*/ | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
// Path: disconf-web/src/main/java/com/baidu/disconf/web/service/config/service/ConfigMgr.java
import java.io.File;
import java.util.List;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.web.service.config.bo.Config;
import com.baidu.disconf.web.service.config.form.ConfListForm;
import com.baidu.disconf.web.service.config.form.ConfNewItemForm;
import com.baidu.disconf.web.service.config.vo.ConfListVo;
import com.baidu.disconf.web.service.config.vo.MachineListVo;
import com.baidu.ub.common.db.DaoPageResult;
package com.baidu.disconf.web.service.config.service;
/**
* @author liaoqiqi
* @version 2014-6-16
*/
public interface ConfigMgr {
/**
* @param
*
* @return
*/
List<String> getVersionListByAppEnv(Long appId, Long envId);
/**
* @return
*/
DaoPageResult<ConfListVo> getConfigList(ConfListForm confListForm, boolean fetchZk, final boolean getErrorMessage);
/**
* @param configId
*
* @return
*/
ConfListVo getConfVo(Long configId);
/**
* @param configId
*
* @return
*/
MachineListVo getConfVoWithZk(Long configId);
/**
* @param configId
*
* @return
*/
Config getConfigById(Long configId);
/**
* 更新 配置项/配置文件
*
* @param configId
*
* @return
*/
String updateItemValue(Long configId, String value);
/**
* 获取config value
*
* @param configId
*
* @return
*/
String getValue(Long configId);
/**
* 通知zk
*
* @param configId
*/
void notifyZookeeper(Long configId);
/**
* 新建一个config
*
* @param confNewForm
* @param disConfigTypeEnum
*/ | void newConfig(ConfNewItemForm confNewForm, DisConfigTypeEnum disConfigTypeEnum); |
knightliao/disconf | disconf-client/src/main/java/com/baidu/disconf/client/DisconfMgrBean.java | // Path: disconf-client/src/main/java/com/baidu/disconf/client/store/aspect/DisconfAspectJ.java
// @Aspect
// public class DisconfAspectJ {
//
// protected static final Logger LOGGER = LoggerFactory.getLogger(DisconfAspectJ.class);
//
// @Pointcut(value = "execution(public * *(..))")
// public void anyPublicMethod() {
// }
//
// /**
// * 获取配置文件数据, 只有开启disconf远程才会进行切面
// *
// * @throws Throwable
// */
// @Around("anyPublicMethod() && @annotation(disconfFileItem)")
// public Object decideAccess(ProceedingJoinPoint pjp, DisconfFileItem disconfFileItem) throws Throwable {
//
// if (DisClientConfig.getInstance().ENABLE_DISCONF) {
//
// MethodSignature ms = (MethodSignature) pjp.getSignature();
// Method method = ms.getMethod();
//
// //
// // 文件名
// //
// Class<?> cls = method.getDeclaringClass();
// DisconfFile disconfFile = cls.getAnnotation(DisconfFile.class);
//
// //
// // Field名
// //
// Field field = MethodUtils.getFieldFromMethod(method, cls.getDeclaredFields(), DisConfigTypeEnum.FILE);
// if (field != null) {
//
// //
// // 请求仓库配置数据
// //
// DisconfStoreProcessor disconfStoreProcessor =
// DisconfStoreProcessorFactory.getDisconfStoreFileProcessor();
// Object ret = disconfStoreProcessor.getConfig(disconfFile.filename(), disconfFileItem.name());
// if (ret != null) {
// LOGGER.debug("using disconf store value: " + disconfFile.filename() + " ("
// + disconfFileItem.name() +
// " , " + ret + ")");
// return ret;
// }
// }
// }
//
// Object rtnOb;
//
// try {
// // 返回原值
// rtnOb = pjp.proceed();
// } catch (Throwable t) {
// LOGGER.info(t.getMessage());
// throw t;
// }
//
// return rtnOb;
// }
//
// /**
// * 获取配置项数据, 只有开启disconf远程才会进行切面
// *
// * @throws Throwable
// */
// @Around("anyPublicMethod() && @annotation(disconfItem)")
// public Object decideAccess(ProceedingJoinPoint pjp, DisconfItem disconfItem) throws Throwable {
//
// if (DisClientConfig.getInstance().ENABLE_DISCONF) {
// //
// // 请求仓库配置数据
// //
// DisconfStoreProcessor disconfStoreProcessor = DisconfStoreProcessorFactory.getDisconfStoreItemProcessor();
// Object ret = disconfStoreProcessor.getConfig(null, disconfItem.key());
// if (ret != null) {
// LOGGER.debug("using disconf store value: (" + disconfItem.key() + " , " + ret + ")");
// return ret;
// }
// }
//
// Object rtnOb;
//
// try {
// // 返回原值
// rtnOb = pjp.proceed();
// } catch (Throwable t) {
// LOGGER.info(t.getMessage());
// throw t;
// }
//
// return rtnOb;
// }
// }
| import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import com.baidu.disconf.client.store.aspect.DisconfAspectJ;
import com.baidu.disconf.client.store.inner.DisconfCenterHostFilesStore;
import com.baidu.disconf.client.support.utils.StringUtil; | DisconfCenterHostFilesStore.getInstance().addJustHostFileSet(fileList);
List<String> scanPackList = StringUtil.parseStringToStringList(scanPackage, SCAN_SPLIT_TOKEN);
// unique
Set<String> hs = new HashSet<String>();
hs.addAll(scanPackList);
scanPackList.clear();
scanPackList.addAll(hs);
// 进行扫描
DisconfMgr.getInstance().setApplicationContext(applicationContext);
DisconfMgr.getInstance().firstScan(scanPackList);
// register java bean
registerAspect(registry);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* register aspectJ for disconf get request
*
* @param registry
*/
private void registerAspect(BeanDefinitionRegistry registry) {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); | // Path: disconf-client/src/main/java/com/baidu/disconf/client/store/aspect/DisconfAspectJ.java
// @Aspect
// public class DisconfAspectJ {
//
// protected static final Logger LOGGER = LoggerFactory.getLogger(DisconfAspectJ.class);
//
// @Pointcut(value = "execution(public * *(..))")
// public void anyPublicMethod() {
// }
//
// /**
// * 获取配置文件数据, 只有开启disconf远程才会进行切面
// *
// * @throws Throwable
// */
// @Around("anyPublicMethod() && @annotation(disconfFileItem)")
// public Object decideAccess(ProceedingJoinPoint pjp, DisconfFileItem disconfFileItem) throws Throwable {
//
// if (DisClientConfig.getInstance().ENABLE_DISCONF) {
//
// MethodSignature ms = (MethodSignature) pjp.getSignature();
// Method method = ms.getMethod();
//
// //
// // 文件名
// //
// Class<?> cls = method.getDeclaringClass();
// DisconfFile disconfFile = cls.getAnnotation(DisconfFile.class);
//
// //
// // Field名
// //
// Field field = MethodUtils.getFieldFromMethod(method, cls.getDeclaredFields(), DisConfigTypeEnum.FILE);
// if (field != null) {
//
// //
// // 请求仓库配置数据
// //
// DisconfStoreProcessor disconfStoreProcessor =
// DisconfStoreProcessorFactory.getDisconfStoreFileProcessor();
// Object ret = disconfStoreProcessor.getConfig(disconfFile.filename(), disconfFileItem.name());
// if (ret != null) {
// LOGGER.debug("using disconf store value: " + disconfFile.filename() + " ("
// + disconfFileItem.name() +
// " , " + ret + ")");
// return ret;
// }
// }
// }
//
// Object rtnOb;
//
// try {
// // 返回原值
// rtnOb = pjp.proceed();
// } catch (Throwable t) {
// LOGGER.info(t.getMessage());
// throw t;
// }
//
// return rtnOb;
// }
//
// /**
// * 获取配置项数据, 只有开启disconf远程才会进行切面
// *
// * @throws Throwable
// */
// @Around("anyPublicMethod() && @annotation(disconfItem)")
// public Object decideAccess(ProceedingJoinPoint pjp, DisconfItem disconfItem) throws Throwable {
//
// if (DisClientConfig.getInstance().ENABLE_DISCONF) {
// //
// // 请求仓库配置数据
// //
// DisconfStoreProcessor disconfStoreProcessor = DisconfStoreProcessorFactory.getDisconfStoreItemProcessor();
// Object ret = disconfStoreProcessor.getConfig(null, disconfItem.key());
// if (ret != null) {
// LOGGER.debug("using disconf store value: (" + disconfItem.key() + " , " + ret + ")");
// return ret;
// }
// }
//
// Object rtnOb;
//
// try {
// // 返回原值
// rtnOb = pjp.proceed();
// } catch (Throwable t) {
// LOGGER.info(t.getMessage());
// throw t;
// }
//
// return rtnOb;
// }
// }
// Path: disconf-client/src/main/java/com/baidu/disconf/client/DisconfMgrBean.java
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import com.baidu.disconf.client.store.aspect.DisconfAspectJ;
import com.baidu.disconf.client.store.inner.DisconfCenterHostFilesStore;
import com.baidu.disconf.client.support.utils.StringUtil;
DisconfCenterHostFilesStore.getInstance().addJustHostFileSet(fileList);
List<String> scanPackList = StringUtil.parseStringToStringList(scanPackage, SCAN_SPLIT_TOKEN);
// unique
Set<String> hs = new HashSet<String>();
hs.addAll(scanPackList);
scanPackList.clear();
scanPackList.addAll(hs);
// 进行扫描
DisconfMgr.getInstance().setApplicationContext(applicationContext);
DisconfMgr.getInstance().firstScan(scanPackList);
// register java bean
registerAspect(registry);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* register aspectJ for disconf get request
*
* @param registry
*/
private void registerAspect(BeanDefinitionRegistry registry) {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); | beanDefinition.setBeanClass(DisconfAspectJ.class); |
knightliao/disconf | disconf-web/src/main/java/com/baidu/disconf/web/web/config/controller/ConfigFetcherController.java | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
//
// Path: disconf-web/src/main/java/com/baidu/dsp/common/exception/DocumentNotFoundException.java
// public class DocumentNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = 545280194497047918L;
//
// public DocumentNotFoundException(String fileName) {
// super(fileName + " file does not exist!");
// }
//
// }
| import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.core.common.json.ValueVo;
import com.baidu.disconf.web.service.config.bo.Config;
import com.baidu.disconf.web.service.config.form.ConfForm;
import com.baidu.disconf.web.service.config.service.ConfigFetchMgr;
import com.baidu.disconf.web.service.config.utils.ConfigUtils;
import com.baidu.disconf.web.web.config.dto.ConfigFullModel;
import com.baidu.disconf.web.web.config.validator.ConfigValidator;
import com.baidu.disconf.web.web.config.validator.ConfigValidator4Fetch;
import com.baidu.dsp.common.annotation.NoAuth;
import com.baidu.dsp.common.constant.WebConstants;
import com.baidu.dsp.common.controller.BaseController;
import com.baidu.dsp.common.exception.DocumentNotFoundException;
import com.baidu.dsp.common.vo.JsonObjectBase; |
/**
* 获取配置文件
*
* @return
*/
@NoAuth
@RequestMapping(value = "/file", method = RequestMethod.GET)
@ResponseBody
public HttpEntity<byte[]> getFile(ConfForm confForm) {
boolean hasError = false;
//
// 校验
//
ConfigFullModel configModel = null;
try {
configModel = configValidator4Fetch.verifyConfForm(confForm, false);
} catch (Exception e) {
LOG.error(e.toString());
hasError = true;
}
if (hasError == false) {
try {
//
Config config = configFetchMgr
.getConfByParameter(configModel.getApp().getId(), configModel.getEnv().getId(),
configModel.getVersion(), configModel.getKey(), | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
//
// Path: disconf-web/src/main/java/com/baidu/dsp/common/exception/DocumentNotFoundException.java
// public class DocumentNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = 545280194497047918L;
//
// public DocumentNotFoundException(String fileName) {
// super(fileName + " file does not exist!");
// }
//
// }
// Path: disconf-web/src/main/java/com/baidu/disconf/web/web/config/controller/ConfigFetcherController.java
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.core.common.json.ValueVo;
import com.baidu.disconf.web.service.config.bo.Config;
import com.baidu.disconf.web.service.config.form.ConfForm;
import com.baidu.disconf.web.service.config.service.ConfigFetchMgr;
import com.baidu.disconf.web.service.config.utils.ConfigUtils;
import com.baidu.disconf.web.web.config.dto.ConfigFullModel;
import com.baidu.disconf.web.web.config.validator.ConfigValidator;
import com.baidu.disconf.web.web.config.validator.ConfigValidator4Fetch;
import com.baidu.dsp.common.annotation.NoAuth;
import com.baidu.dsp.common.constant.WebConstants;
import com.baidu.dsp.common.controller.BaseController;
import com.baidu.dsp.common.exception.DocumentNotFoundException;
import com.baidu.dsp.common.vo.JsonObjectBase;
/**
* 获取配置文件
*
* @return
*/
@NoAuth
@RequestMapping(value = "/file", method = RequestMethod.GET)
@ResponseBody
public HttpEntity<byte[]> getFile(ConfForm confForm) {
boolean hasError = false;
//
// 校验
//
ConfigFullModel configModel = null;
try {
configModel = configValidator4Fetch.verifyConfForm(confForm, false);
} catch (Exception e) {
LOG.error(e.toString());
hasError = true;
}
if (hasError == false) {
try {
//
Config config = configFetchMgr
.getConfByParameter(configModel.getApp().getId(), configModel.getEnv().getId(),
configModel.getVersion(), configModel.getKey(), | DisConfigTypeEnum.FILE); |
knightliao/disconf | disconf-web/src/main/java/com/baidu/disconf/web/web/config/controller/ConfigFetcherController.java | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
//
// Path: disconf-web/src/main/java/com/baidu/dsp/common/exception/DocumentNotFoundException.java
// public class DocumentNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = 545280194497047918L;
//
// public DocumentNotFoundException(String fileName) {
// super(fileName + " file does not exist!");
// }
//
// }
| import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.core.common.json.ValueVo;
import com.baidu.disconf.web.service.config.bo.Config;
import com.baidu.disconf.web.service.config.form.ConfForm;
import com.baidu.disconf.web.service.config.service.ConfigFetchMgr;
import com.baidu.disconf.web.service.config.utils.ConfigUtils;
import com.baidu.disconf.web.web.config.dto.ConfigFullModel;
import com.baidu.disconf.web.web.config.validator.ConfigValidator;
import com.baidu.disconf.web.web.config.validator.ConfigValidator4Fetch;
import com.baidu.dsp.common.annotation.NoAuth;
import com.baidu.dsp.common.constant.WebConstants;
import com.baidu.dsp.common.controller.BaseController;
import com.baidu.dsp.common.exception.DocumentNotFoundException;
import com.baidu.dsp.common.vo.JsonObjectBase; | *
* @return
*/
@NoAuth
@RequestMapping(value = "/file", method = RequestMethod.GET)
@ResponseBody
public HttpEntity<byte[]> getFile(ConfForm confForm) {
boolean hasError = false;
//
// 校验
//
ConfigFullModel configModel = null;
try {
configModel = configValidator4Fetch.verifyConfForm(confForm, false);
} catch (Exception e) {
LOG.error(e.toString());
hasError = true;
}
if (hasError == false) {
try {
//
Config config = configFetchMgr
.getConfByParameter(configModel.getApp().getId(), configModel.getEnv().getId(),
configModel.getVersion(), configModel.getKey(),
DisConfigTypeEnum.FILE);
if (config == null) {
hasError = true; | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
//
// Path: disconf-web/src/main/java/com/baidu/dsp/common/exception/DocumentNotFoundException.java
// public class DocumentNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = 545280194497047918L;
//
// public DocumentNotFoundException(String fileName) {
// super(fileName + " file does not exist!");
// }
//
// }
// Path: disconf-web/src/main/java/com/baidu/disconf/web/web/config/controller/ConfigFetcherController.java
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
import com.baidu.disconf.core.common.json.ValueVo;
import com.baidu.disconf.web.service.config.bo.Config;
import com.baidu.disconf.web.service.config.form.ConfForm;
import com.baidu.disconf.web.service.config.service.ConfigFetchMgr;
import com.baidu.disconf.web.service.config.utils.ConfigUtils;
import com.baidu.disconf.web.web.config.dto.ConfigFullModel;
import com.baidu.disconf.web.web.config.validator.ConfigValidator;
import com.baidu.disconf.web.web.config.validator.ConfigValidator4Fetch;
import com.baidu.dsp.common.annotation.NoAuth;
import com.baidu.dsp.common.constant.WebConstants;
import com.baidu.dsp.common.controller.BaseController;
import com.baidu.dsp.common.exception.DocumentNotFoundException;
import com.baidu.dsp.common.vo.JsonObjectBase;
*
* @return
*/
@NoAuth
@RequestMapping(value = "/file", method = RequestMethod.GET)
@ResponseBody
public HttpEntity<byte[]> getFile(ConfForm confForm) {
boolean hasError = false;
//
// 校验
//
ConfigFullModel configModel = null;
try {
configModel = configValidator4Fetch.verifyConfForm(confForm, false);
} catch (Exception e) {
LOG.error(e.toString());
hasError = true;
}
if (hasError == false) {
try {
//
Config config = configFetchMgr
.getConfByParameter(configModel.getApp().getId(), configModel.getEnv().getId(),
configModel.getVersion(), configModel.getKey(),
DisConfigTypeEnum.FILE);
if (config == null) {
hasError = true; | throw new DocumentNotFoundException(configModel.getKey()); |
knightliao/disconf | disconf-client/src/main/java/com/baidu/disconf/client/store/aspect/DisconfAspectJ.java | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
| import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.disconf.client.common.annotations.DisconfFile;
import com.baidu.disconf.client.common.annotations.DisconfFileItem;
import com.baidu.disconf.client.common.annotations.DisconfItem;
import com.baidu.disconf.client.config.DisClientConfig;
import com.baidu.disconf.client.store.DisconfStoreProcessor;
import com.baidu.disconf.client.store.DisconfStoreProcessorFactory;
import com.baidu.disconf.client.support.utils.MethodUtils;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum; | package com.baidu.disconf.client.store.aspect;
/**
* 配置拦截
*
* @author liaoqiqi
* @version 2014-6-11
*/
@Aspect
public class DisconfAspectJ {
protected static final Logger LOGGER = LoggerFactory.getLogger(DisconfAspectJ.class);
@Pointcut(value = "execution(public * *(..))")
public void anyPublicMethod() {
}
/**
* 获取配置文件数据, 只有开启disconf远程才会进行切面
*
* @throws Throwable
*/
@Around("anyPublicMethod() && @annotation(disconfFileItem)")
public Object decideAccess(ProceedingJoinPoint pjp, DisconfFileItem disconfFileItem) throws Throwable {
if (DisClientConfig.getInstance().ENABLE_DISCONF) {
MethodSignature ms = (MethodSignature) pjp.getSignature();
Method method = ms.getMethod();
//
// 文件名
//
Class<?> cls = method.getDeclaringClass();
DisconfFile disconfFile = cls.getAnnotation(DisconfFile.class);
//
// Field名
// | // Path: disconf-core/src/main/java/com/baidu/disconf/core/common/constants/DisConfigTypeEnum.java
// public enum DisConfigTypeEnum {
//
// FILE(0, "配置文件"), ITEM(1, "配置项");
//
// private int type = 0;
// private String modelName = null;
//
// private DisConfigTypeEnum(int type, String modelName) {
// this.type = type;
// this.modelName = modelName;
// }
//
// public static DisConfigTypeEnum getByType(int type) {
//
// int index = 0;
// for (DisConfigTypeEnum disConfigTypeEnum : DisConfigTypeEnum.values()) {
//
// if (type == index) {
// return disConfigTypeEnum;
// }
//
// index++;
// }
//
// return null;
// }
//
// public int getType() {
// return type;
// }
//
// public void setType(int type) {
// this.type = type;
// }
//
// public String getModelName() {
// return modelName;
// }
//
// public void setModelName(String modelName) {
// this.modelName = modelName;
// }
//
// }
// Path: disconf-client/src/main/java/com/baidu/disconf/client/store/aspect/DisconfAspectJ.java
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.disconf.client.common.annotations.DisconfFile;
import com.baidu.disconf.client.common.annotations.DisconfFileItem;
import com.baidu.disconf.client.common.annotations.DisconfItem;
import com.baidu.disconf.client.config.DisClientConfig;
import com.baidu.disconf.client.store.DisconfStoreProcessor;
import com.baidu.disconf.client.store.DisconfStoreProcessorFactory;
import com.baidu.disconf.client.support.utils.MethodUtils;
import com.baidu.disconf.core.common.constants.DisConfigTypeEnum;
package com.baidu.disconf.client.store.aspect;
/**
* 配置拦截
*
* @author liaoqiqi
* @version 2014-6-11
*/
@Aspect
public class DisconfAspectJ {
protected static final Logger LOGGER = LoggerFactory.getLogger(DisconfAspectJ.class);
@Pointcut(value = "execution(public * *(..))")
public void anyPublicMethod() {
}
/**
* 获取配置文件数据, 只有开启disconf远程才会进行切面
*
* @throws Throwable
*/
@Around("anyPublicMethod() && @annotation(disconfFileItem)")
public Object decideAccess(ProceedingJoinPoint pjp, DisconfFileItem disconfFileItem) throws Throwable {
if (DisClientConfig.getInstance().ENABLE_DISCONF) {
MethodSignature ms = (MethodSignature) pjp.getSignature();
Method method = ms.getMethod();
//
// 文件名
//
Class<?> cls = method.getDeclaringClass();
DisconfFile disconfFile = cls.getAnnotation(DisconfFile.class);
//
// Field名
// | Field field = MethodUtils.getFieldFromMethod(method, cls.getDeclaredFields(), DisConfigTypeEnum.FILE); |
DTHeaven/AutoLayout-Android | AutoLayout/autolayout/src/main/java/im/quar/autolayout/config/AutoLayoutConfig.java | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/ScaleAdapter.java
// public interface ScaleAdapter {
// float adapt(float scale, int screenWidth, int screenHeight);
// }
//
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/ScreenUtils.java
// public class ScreenUtils {
// public static int[] getRealScreenSize(Context context) {
//
// int[] size = new int[2];
//
// WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display d = w.getDefaultDisplay();
// DisplayMetrics metrics = new DisplayMetrics();
// d.getMetrics(metrics);
//
// // since SDK_INT = 1;
// int widthPixels = metrics.widthPixels;
// int heightPixels = metrics.heightPixels;
// // includes window decorations (statusbar bar/menu bar)
// if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
// try {
// widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
// heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
// } catch (Exception ignored) {
// }
// } else if (Build.VERSION.SDK_INT >= 17) {// includes window decorations (statusbar bar/menu bar)
// Point realSize = new Point();
// d.getRealSize(realSize);
// widthPixels = realSize.x;
// heightPixels = realSize.y;
// }
//
// size[0] = widthPixels;
// size[1] = heightPixels;
// return size;
// }
//
//
// public static double getDevicePhysicalSize(Context context) {
// int[] size = getRealScreenSize(context);
// DisplayMetrics dm = context.getResources().getDisplayMetrics();
// double x = Math.pow(size[0] / dm.xdpi, 2);
// double y = Math.pow(size[1] / dm.ydpi, 2);
//
// return Math.sqrt(x + y);
// }
// }
| import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import im.quar.autolayout.ScaleAdapter;
import im.quar.autolayout.utils.ScreenUtils; | package im.quar.autolayout.config;
/**
* Created by DTHeaven on 15/11/18.
*/
public class AutoLayoutConfig {
private static AutoLayoutConfig sInstance;
private static final String KEY_DESIGN_WIDTH = "design_width";
private static final String KEY_DESIGN_HEIGHT = "design_height";
private int mScreenWidth;
private int mScreenHeight;
private int mDesignWidth;
private int mDesignHeight;
private float mScale;
private AutoLayoutConfig() {
}
public static void init(Context context) {
init(context, new DefaultScaleAdapter(context));
}
| // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/ScaleAdapter.java
// public interface ScaleAdapter {
// float adapt(float scale, int screenWidth, int screenHeight);
// }
//
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/ScreenUtils.java
// public class ScreenUtils {
// public static int[] getRealScreenSize(Context context) {
//
// int[] size = new int[2];
//
// WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display d = w.getDefaultDisplay();
// DisplayMetrics metrics = new DisplayMetrics();
// d.getMetrics(metrics);
//
// // since SDK_INT = 1;
// int widthPixels = metrics.widthPixels;
// int heightPixels = metrics.heightPixels;
// // includes window decorations (statusbar bar/menu bar)
// if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
// try {
// widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
// heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
// } catch (Exception ignored) {
// }
// } else if (Build.VERSION.SDK_INT >= 17) {// includes window decorations (statusbar bar/menu bar)
// Point realSize = new Point();
// d.getRealSize(realSize);
// widthPixels = realSize.x;
// heightPixels = realSize.y;
// }
//
// size[0] = widthPixels;
// size[1] = heightPixels;
// return size;
// }
//
//
// public static double getDevicePhysicalSize(Context context) {
// int[] size = getRealScreenSize(context);
// DisplayMetrics dm = context.getResources().getDisplayMetrics();
// double x = Math.pow(size[0] / dm.xdpi, 2);
// double y = Math.pow(size[1] / dm.ydpi, 2);
//
// return Math.sqrt(x + y);
// }
// }
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/config/AutoLayoutConfig.java
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import im.quar.autolayout.ScaleAdapter;
import im.quar.autolayout.utils.ScreenUtils;
package im.quar.autolayout.config;
/**
* Created by DTHeaven on 15/11/18.
*/
public class AutoLayoutConfig {
private static AutoLayoutConfig sInstance;
private static final String KEY_DESIGN_WIDTH = "design_width";
private static final String KEY_DESIGN_HEIGHT = "design_height";
private int mScreenWidth;
private int mScreenHeight;
private int mDesignWidth;
private int mDesignHeight;
private float mScale;
private AutoLayoutConfig() {
}
public static void init(Context context) {
init(context, new DefaultScaleAdapter(context));
}
| public static void init(Context context, ScaleAdapter scaleAdapter) { |
DTHeaven/AutoLayout-Android | AutoLayout/autolayout/src/main/java/im/quar/autolayout/config/AutoLayoutConfig.java | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/ScaleAdapter.java
// public interface ScaleAdapter {
// float adapt(float scale, int screenWidth, int screenHeight);
// }
//
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/ScreenUtils.java
// public class ScreenUtils {
// public static int[] getRealScreenSize(Context context) {
//
// int[] size = new int[2];
//
// WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display d = w.getDefaultDisplay();
// DisplayMetrics metrics = new DisplayMetrics();
// d.getMetrics(metrics);
//
// // since SDK_INT = 1;
// int widthPixels = metrics.widthPixels;
// int heightPixels = metrics.heightPixels;
// // includes window decorations (statusbar bar/menu bar)
// if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
// try {
// widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
// heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
// } catch (Exception ignored) {
// }
// } else if (Build.VERSION.SDK_INT >= 17) {// includes window decorations (statusbar bar/menu bar)
// Point realSize = new Point();
// d.getRealSize(realSize);
// widthPixels = realSize.x;
// heightPixels = realSize.y;
// }
//
// size[0] = widthPixels;
// size[1] = heightPixels;
// return size;
// }
//
//
// public static double getDevicePhysicalSize(Context context) {
// int[] size = getRealScreenSize(context);
// DisplayMetrics dm = context.getResources().getDisplayMetrics();
// double x = Math.pow(size[0] / dm.xdpi, 2);
// double y = Math.pow(size[1] / dm.ydpi, 2);
//
// return Math.sqrt(x + y);
// }
// }
| import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import im.quar.autolayout.ScaleAdapter;
import im.quar.autolayout.utils.ScreenUtils; | package im.quar.autolayout.config;
/**
* Created by DTHeaven on 15/11/18.
*/
public class AutoLayoutConfig {
private static AutoLayoutConfig sInstance;
private static final String KEY_DESIGN_WIDTH = "design_width";
private static final String KEY_DESIGN_HEIGHT = "design_height";
private int mScreenWidth;
private int mScreenHeight;
private int mDesignWidth;
private int mDesignHeight;
private float mScale;
private AutoLayoutConfig() {
}
public static void init(Context context) {
init(context, new DefaultScaleAdapter(context));
}
public static void init(Context context, ScaleAdapter scaleAdapter) {
if (sInstance == null) {
sInstance = new AutoLayoutConfig();
sInstance.initInternal(context, scaleAdapter);
}
}
public static AutoLayoutConfig getInstance() {
if (sInstance == null) {
throw new IllegalStateException("Must init before using.");
}
return sInstance;
}
private void initInternal(Context context, ScaleAdapter scaleAdapter) {
getMetaData(context);
checkParams();
| // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/ScaleAdapter.java
// public interface ScaleAdapter {
// float adapt(float scale, int screenWidth, int screenHeight);
// }
//
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/ScreenUtils.java
// public class ScreenUtils {
// public static int[] getRealScreenSize(Context context) {
//
// int[] size = new int[2];
//
// WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display d = w.getDefaultDisplay();
// DisplayMetrics metrics = new DisplayMetrics();
// d.getMetrics(metrics);
//
// // since SDK_INT = 1;
// int widthPixels = metrics.widthPixels;
// int heightPixels = metrics.heightPixels;
// // includes window decorations (statusbar bar/menu bar)
// if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
// try {
// widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
// heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
// } catch (Exception ignored) {
// }
// } else if (Build.VERSION.SDK_INT >= 17) {// includes window decorations (statusbar bar/menu bar)
// Point realSize = new Point();
// d.getRealSize(realSize);
// widthPixels = realSize.x;
// heightPixels = realSize.y;
// }
//
// size[0] = widthPixels;
// size[1] = heightPixels;
// return size;
// }
//
//
// public static double getDevicePhysicalSize(Context context) {
// int[] size = getRealScreenSize(context);
// DisplayMetrics dm = context.getResources().getDisplayMetrics();
// double x = Math.pow(size[0] / dm.xdpi, 2);
// double y = Math.pow(size[1] / dm.ydpi, 2);
//
// return Math.sqrt(x + y);
// }
// }
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/config/AutoLayoutConfig.java
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import im.quar.autolayout.ScaleAdapter;
import im.quar.autolayout.utils.ScreenUtils;
package im.quar.autolayout.config;
/**
* Created by DTHeaven on 15/11/18.
*/
public class AutoLayoutConfig {
private static AutoLayoutConfig sInstance;
private static final String KEY_DESIGN_WIDTH = "design_width";
private static final String KEY_DESIGN_HEIGHT = "design_height";
private int mScreenWidth;
private int mScreenHeight;
private int mDesignWidth;
private int mDesignHeight;
private float mScale;
private AutoLayoutConfig() {
}
public static void init(Context context) {
init(context, new DefaultScaleAdapter(context));
}
public static void init(Context context, ScaleAdapter scaleAdapter) {
if (sInstance == null) {
sInstance = new AutoLayoutConfig();
sInstance.initInternal(context, scaleAdapter);
}
}
public static AutoLayoutConfig getInstance() {
if (sInstance == null) {
throw new IllegalStateException("Must init before using.");
}
return sInstance;
}
private void initInternal(Context context, ScaleAdapter scaleAdapter) {
getMetaData(context);
checkParams();
| int[] size = ScreenUtils.getRealScreenSize(context); |
DTHeaven/AutoLayout-Android | AutoLayout/autolayout/src/main/java/im/quar/autolayout/attr/AutoAttr.java | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/AutoUtils.java
// public class AutoUtils {
//
// /**
// * 会直接将view的LayoutParams上设置的width,height直接进行百分比处理
// *
// * @param view
// */
// public static void auto(View view) {
// autoSize(view);
// autoPadding(view);
// autoMargin(view);
// }
//
// public static void autoMargin(View view) {
// if (!(view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams))
// return;
//
// ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
// if (lp == null) return;
//
// lp.leftMargin = scaleValue(lp.leftMargin);
// lp.topMargin = scaleValue(lp.topMargin);
// lp.rightMargin = scaleValue(lp.rightMargin);
// lp.bottomMargin = scaleValue(lp.bottomMargin);
//
// }
//
// public static void autoPadding(View view) {
// int l = view.getPaddingLeft();
// int t = view.getPaddingTop();
// int r = view.getPaddingRight();
// int b = view.getPaddingBottom();
//
// l = scaleValue(l);
// t = scaleValue(t);
// r = scaleValue(r);
// b = scaleValue(b);
//
// view.setPadding(l, t, r, b);
// }
//
// public static void autoSize(View view) {
// ViewGroup.LayoutParams lp = view.getLayoutParams();
//
// if (lp == null) return;
//
// if (lp.width > 0) {
// lp.width = scaleValue(lp.width);
// }
//
// if (lp.height > 0) {
// lp.height = scaleValue(lp.height);
// }
// }
//
// public static int scaleValue(int val) {
// return (int) (val * AutoLayoutConfig.getInstance().getScale());
// }
// }
| import im.quar.autolayout.utils.AutoUtils; | package im.quar.autolayout.attr;
/**
* Created by DTHeaven on 15/12/4.
*/
public abstract class AutoAttr<T> {
private int pxVal;
public AutoAttr(int pxVal) {
this.pxVal = pxVal;
}
public void apply(T t) { | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/AutoUtils.java
// public class AutoUtils {
//
// /**
// * 会直接将view的LayoutParams上设置的width,height直接进行百分比处理
// *
// * @param view
// */
// public static void auto(View view) {
// autoSize(view);
// autoPadding(view);
// autoMargin(view);
// }
//
// public static void autoMargin(View view) {
// if (!(view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams))
// return;
//
// ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
// if (lp == null) return;
//
// lp.leftMargin = scaleValue(lp.leftMargin);
// lp.topMargin = scaleValue(lp.topMargin);
// lp.rightMargin = scaleValue(lp.rightMargin);
// lp.bottomMargin = scaleValue(lp.bottomMargin);
//
// }
//
// public static void autoPadding(View view) {
// int l = view.getPaddingLeft();
// int t = view.getPaddingTop();
// int r = view.getPaddingRight();
// int b = view.getPaddingBottom();
//
// l = scaleValue(l);
// t = scaleValue(t);
// r = scaleValue(r);
// b = scaleValue(b);
//
// view.setPadding(l, t, r, b);
// }
//
// public static void autoSize(View view) {
// ViewGroup.LayoutParams lp = view.getLayoutParams();
//
// if (lp == null) return;
//
// if (lp.width > 0) {
// lp.width = scaleValue(lp.width);
// }
//
// if (lp.height > 0) {
// lp.height = scaleValue(lp.height);
// }
// }
//
// public static int scaleValue(int val) {
// return (int) (val * AutoLayoutConfig.getInstance().getScale());
// }
// }
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/attr/AutoAttr.java
import im.quar.autolayout.utils.AutoUtils;
package im.quar.autolayout.attr;
/**
* Created by DTHeaven on 15/12/4.
*/
public abstract class AutoAttr<T> {
private int pxVal;
public AutoAttr(int pxVal) {
this.pxVal = pxVal;
}
public void apply(T t) { | int val = AutoUtils.scaleValue(pxVal); |
DTHeaven/AutoLayout-Android | AutoLayout/autolayout/src/main/java/im/quar/autolayout/AutoLayoutInfo.java | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/attr/AutoAttr.java
// public abstract class AutoAttr<T> {
// private int pxVal;
//
// public AutoAttr(int pxVal) {
// this.pxVal = pxVal;
// }
//
// public void apply(T t) {
// int val = AutoUtils.scaleValue(pxVal);
// if (val == 0 && pxVal > 0) {//for very thin divider
// val = 1;
// }
// execute(t, val);
// }
//
// protected abstract int attrVal();
//
// protected abstract void execute(T t, int val);
//
// @Override
// public String toString() {
// return "AutoAttr{" +
// "pxVal=" + pxVal +
// '}';
// }
// }
| import android.view.View;
import android.view.ViewGroup;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import im.quar.autolayout.attr.AutoAttr; | package im.quar.autolayout;
public class AutoLayoutInfo {
public float aspectRatio; | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/attr/AutoAttr.java
// public abstract class AutoAttr<T> {
// private int pxVal;
//
// public AutoAttr(int pxVal) {
// this.pxVal = pxVal;
// }
//
// public void apply(T t) {
// int val = AutoUtils.scaleValue(pxVal);
// if (val == 0 && pxVal > 0) {//for very thin divider
// val = 1;
// }
// execute(t, val);
// }
//
// protected abstract int attrVal();
//
// protected abstract void execute(T t, int val);
//
// @Override
// public String toString() {
// return "AutoAttr{" +
// "pxVal=" + pxVal +
// '}';
// }
// }
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/AutoLayoutInfo.java
import android.view.View;
import android.view.ViewGroup;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import im.quar.autolayout.attr.AutoAttr;
package im.quar.autolayout;
public class AutoLayoutInfo {
public float aspectRatio; | private List<AutoAttr> autoAttrs = new ArrayList<>(); |
DTHeaven/AutoLayout-Android | AutoLayout/autolayout/src/main/java/im/quar/autolayout/config/DefaultScaleAdapter.java | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/ScaleAdapter.java
// public interface ScaleAdapter {
// float adapt(float scale, int screenWidth, int screenHeight);
// }
//
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/ScreenUtils.java
// public class ScreenUtils {
// public static int[] getRealScreenSize(Context context) {
//
// int[] size = new int[2];
//
// WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display d = w.getDefaultDisplay();
// DisplayMetrics metrics = new DisplayMetrics();
// d.getMetrics(metrics);
//
// // since SDK_INT = 1;
// int widthPixels = metrics.widthPixels;
// int heightPixels = metrics.heightPixels;
// // includes window decorations (statusbar bar/menu bar)
// if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
// try {
// widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
// heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
// } catch (Exception ignored) {
// }
// } else if (Build.VERSION.SDK_INT >= 17) {// includes window decorations (statusbar bar/menu bar)
// Point realSize = new Point();
// d.getRealSize(realSize);
// widthPixels = realSize.x;
// heightPixels = realSize.y;
// }
//
// size[0] = widthPixels;
// size[1] = heightPixels;
// return size;
// }
//
//
// public static double getDevicePhysicalSize(Context context) {
// int[] size = getRealScreenSize(context);
// DisplayMetrics dm = context.getResources().getDisplayMetrics();
// double x = Math.pow(size[0] / dm.xdpi, 2);
// double y = Math.pow(size[1] / dm.ydpi, 2);
//
// return Math.sqrt(x + y);
// }
// }
| import android.content.Context;
import im.quar.autolayout.ScaleAdapter;
import im.quar.autolayout.utils.ScreenUtils; | package im.quar.autolayout.config;
/**
* Created by DTHeaven on 15/12/16.
*/
public class DefaultScaleAdapter implements ScaleAdapter {
private Context mContext;
public DefaultScaleAdapter(Context context) {
mContext = context;
}
@Override
public float adapt(float scale, int screenWidth, int screenHeight) {
if (screenWidth < 720 || screenHeight < 720) {//针对小屏(小分辨率)设备做调整
if (screenWidth <= 480 || screenHeight <= 480) {//普通480设备
scale *= 1.2f;
} else { | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/ScaleAdapter.java
// public interface ScaleAdapter {
// float adapt(float scale, int screenWidth, int screenHeight);
// }
//
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/ScreenUtils.java
// public class ScreenUtils {
// public static int[] getRealScreenSize(Context context) {
//
// int[] size = new int[2];
//
// WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
// Display d = w.getDefaultDisplay();
// DisplayMetrics metrics = new DisplayMetrics();
// d.getMetrics(metrics);
//
// // since SDK_INT = 1;
// int widthPixels = metrics.widthPixels;
// int heightPixels = metrics.heightPixels;
// // includes window decorations (statusbar bar/menu bar)
// if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
// try {
// widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
// heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
// } catch (Exception ignored) {
// }
// } else if (Build.VERSION.SDK_INT >= 17) {// includes window decorations (statusbar bar/menu bar)
// Point realSize = new Point();
// d.getRealSize(realSize);
// widthPixels = realSize.x;
// heightPixels = realSize.y;
// }
//
// size[0] = widthPixels;
// size[1] = heightPixels;
// return size;
// }
//
//
// public static double getDevicePhysicalSize(Context context) {
// int[] size = getRealScreenSize(context);
// DisplayMetrics dm = context.getResources().getDisplayMetrics();
// double x = Math.pow(size[0] / dm.xdpi, 2);
// double y = Math.pow(size[1] / dm.ydpi, 2);
//
// return Math.sqrt(x + y);
// }
// }
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/config/DefaultScaleAdapter.java
import android.content.Context;
import im.quar.autolayout.ScaleAdapter;
import im.quar.autolayout.utils.ScreenUtils;
package im.quar.autolayout.config;
/**
* Created by DTHeaven on 15/12/16.
*/
public class DefaultScaleAdapter implements ScaleAdapter {
private Context mContext;
public DefaultScaleAdapter(Context context) {
mContext = context;
}
@Override
public float adapt(float scale, int screenWidth, int screenHeight) {
if (screenWidth < 720 || screenHeight < 720) {//针对小屏(小分辨率)设备做调整
if (screenWidth <= 480 || screenHeight <= 480) {//普通480设备
scale *= 1.2f;
} else { | if (ScreenUtils.getDevicePhysicalSize(mContext) < 4.0) {//小屏手机,较高分辨率(如 mx) |
DTHeaven/AutoLayout-Android | AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/AutoUtils.java | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/config/AutoLayoutConfig.java
// public class AutoLayoutConfig {
//
// private static AutoLayoutConfig sInstance;
//
// private static final String KEY_DESIGN_WIDTH = "design_width";
// private static final String KEY_DESIGN_HEIGHT = "design_height";
//
// private int mScreenWidth;
// private int mScreenHeight;
//
// private int mDesignWidth;
// private int mDesignHeight;
//
// private float mScale;
//
// private AutoLayoutConfig() {
// }
//
// public static void init(Context context) {
// init(context, new DefaultScaleAdapter(context));
// }
//
// public static void init(Context context, ScaleAdapter scaleAdapter) {
// if (sInstance == null) {
// sInstance = new AutoLayoutConfig();
// sInstance.initInternal(context, scaleAdapter);
// }
// }
//
// public static AutoLayoutConfig getInstance() {
// if (sInstance == null) {
// throw new IllegalStateException("Must init before using.");
// }
// return sInstance;
// }
//
// private void initInternal(Context context, ScaleAdapter scaleAdapter) {
// getMetaData(context);
// checkParams();
//
// int[] size = ScreenUtils.getRealScreenSize(context);
// mScreenWidth = size[0];
// mScreenHeight = size[1];
//
// if (mScreenWidth > mScreenHeight) {//横屏状态下,宽高互换,按竖屏模式计算scale
// mScreenWidth = mScreenWidth + mScreenHeight;
// mScreenHeight = mScreenWidth - mScreenHeight;
// mScreenWidth = mScreenWidth - mScreenHeight;
// }
//
// float deviceScale = (float) mScreenHeight / mScreenWidth;
// float designScale = (float) mDesignHeight / mDesignWidth;
// if (deviceScale <= designScale) {//高宽比小于等于标准比(较标准屏宽一些),以高为基准计算scale(以短边计算),否则以宽为基准计算scale
// mScale = (float) mScreenHeight / mDesignHeight;
// } else {
// mScale = (float) mScreenWidth / mDesignWidth;
// }
//
// if (scaleAdapter != null) {
// mScale = scaleAdapter.adapt(mScale, mScreenWidth, mScreenHeight);
// }
// }
//
// private void getMetaData(Context context) {
// PackageManager packageManager = context.getPackageManager();
// ApplicationInfo applicationInfo;
// try {
// applicationInfo = packageManager.getApplicationInfo(context
// .getPackageName(), PackageManager.GET_META_DATA);
// if (applicationInfo != null && applicationInfo.metaData != null) {
// mDesignWidth = (int) applicationInfo.metaData.get(KEY_DESIGN_WIDTH);
// mDesignHeight = (int) applicationInfo.metaData.get(KEY_DESIGN_HEIGHT);
// }
// } catch (PackageManager.NameNotFoundException e) {
// throw new RuntimeException(
// "you must set " + KEY_DESIGN_WIDTH + " and " + KEY_DESIGN_HEIGHT + " in your manifest file.", e);
// }
// }
//
// private void checkParams() {
// if (mDesignHeight <= 0 || mDesignWidth <= 0) {
// throw new RuntimeException(
// "you must set " + KEY_DESIGN_WIDTH + " and " + KEY_DESIGN_HEIGHT + " in your manifest file.");
// }
// }
//
// public int getScreenWidth() {
// return mScreenWidth;
// }
//
// public int getScreenHeight() {
// return mScreenHeight;
// }
//
// public int getDesignWidth() {
// return mDesignWidth;
// }
//
// public int getDesignHeight() {
// return mDesignHeight;
// }
//
// public float getScale() {
// return mScale;
// }
// }
| import android.view.View;
import android.view.ViewGroup;
import im.quar.autolayout.config.AutoLayoutConfig; |
public static void autoPadding(View view) {
int l = view.getPaddingLeft();
int t = view.getPaddingTop();
int r = view.getPaddingRight();
int b = view.getPaddingBottom();
l = scaleValue(l);
t = scaleValue(t);
r = scaleValue(r);
b = scaleValue(b);
view.setPadding(l, t, r, b);
}
public static void autoSize(View view) {
ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp == null) return;
if (lp.width > 0) {
lp.width = scaleValue(lp.width);
}
if (lp.height > 0) {
lp.height = scaleValue(lp.height);
}
}
public static int scaleValue(int val) { | // Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/config/AutoLayoutConfig.java
// public class AutoLayoutConfig {
//
// private static AutoLayoutConfig sInstance;
//
// private static final String KEY_DESIGN_WIDTH = "design_width";
// private static final String KEY_DESIGN_HEIGHT = "design_height";
//
// private int mScreenWidth;
// private int mScreenHeight;
//
// private int mDesignWidth;
// private int mDesignHeight;
//
// private float mScale;
//
// private AutoLayoutConfig() {
// }
//
// public static void init(Context context) {
// init(context, new DefaultScaleAdapter(context));
// }
//
// public static void init(Context context, ScaleAdapter scaleAdapter) {
// if (sInstance == null) {
// sInstance = new AutoLayoutConfig();
// sInstance.initInternal(context, scaleAdapter);
// }
// }
//
// public static AutoLayoutConfig getInstance() {
// if (sInstance == null) {
// throw new IllegalStateException("Must init before using.");
// }
// return sInstance;
// }
//
// private void initInternal(Context context, ScaleAdapter scaleAdapter) {
// getMetaData(context);
// checkParams();
//
// int[] size = ScreenUtils.getRealScreenSize(context);
// mScreenWidth = size[0];
// mScreenHeight = size[1];
//
// if (mScreenWidth > mScreenHeight) {//横屏状态下,宽高互换,按竖屏模式计算scale
// mScreenWidth = mScreenWidth + mScreenHeight;
// mScreenHeight = mScreenWidth - mScreenHeight;
// mScreenWidth = mScreenWidth - mScreenHeight;
// }
//
// float deviceScale = (float) mScreenHeight / mScreenWidth;
// float designScale = (float) mDesignHeight / mDesignWidth;
// if (deviceScale <= designScale) {//高宽比小于等于标准比(较标准屏宽一些),以高为基准计算scale(以短边计算),否则以宽为基准计算scale
// mScale = (float) mScreenHeight / mDesignHeight;
// } else {
// mScale = (float) mScreenWidth / mDesignWidth;
// }
//
// if (scaleAdapter != null) {
// mScale = scaleAdapter.adapt(mScale, mScreenWidth, mScreenHeight);
// }
// }
//
// private void getMetaData(Context context) {
// PackageManager packageManager = context.getPackageManager();
// ApplicationInfo applicationInfo;
// try {
// applicationInfo = packageManager.getApplicationInfo(context
// .getPackageName(), PackageManager.GET_META_DATA);
// if (applicationInfo != null && applicationInfo.metaData != null) {
// mDesignWidth = (int) applicationInfo.metaData.get(KEY_DESIGN_WIDTH);
// mDesignHeight = (int) applicationInfo.metaData.get(KEY_DESIGN_HEIGHT);
// }
// } catch (PackageManager.NameNotFoundException e) {
// throw new RuntimeException(
// "you must set " + KEY_DESIGN_WIDTH + " and " + KEY_DESIGN_HEIGHT + " in your manifest file.", e);
// }
// }
//
// private void checkParams() {
// if (mDesignHeight <= 0 || mDesignWidth <= 0) {
// throw new RuntimeException(
// "you must set " + KEY_DESIGN_WIDTH + " and " + KEY_DESIGN_HEIGHT + " in your manifest file.");
// }
// }
//
// public int getScreenWidth() {
// return mScreenWidth;
// }
//
// public int getScreenHeight() {
// return mScreenHeight;
// }
//
// public int getDesignWidth() {
// return mDesignWidth;
// }
//
// public int getDesignHeight() {
// return mDesignHeight;
// }
//
// public float getScale() {
// return mScale;
// }
// }
// Path: AutoLayout/autolayout/src/main/java/im/quar/autolayout/utils/AutoUtils.java
import android.view.View;
import android.view.ViewGroup;
import im.quar.autolayout.config.AutoLayoutConfig;
public static void autoPadding(View view) {
int l = view.getPaddingLeft();
int t = view.getPaddingTop();
int r = view.getPaddingRight();
int b = view.getPaddingBottom();
l = scaleValue(l);
t = scaleValue(t);
r = scaleValue(r);
b = scaleValue(b);
view.setPadding(l, t, r, b);
}
public static void autoSize(View view) {
ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp == null) return;
if (lp.width > 0) {
lp.width = scaleValue(lp.width);
}
if (lp.height > 0) {
lp.height = scaleValue(lp.height);
}
}
public static int scaleValue(int val) { | return (int) (val * AutoLayoutConfig.getInstance().getScale()); |
gresrun/jesque | src/main/java/net/greghaines/jesque/json/ObjectMapperFactory.java | // Path: src/main/java/net/greghaines/jesque/utils/CompositeDateFormat.java
// public class CompositeDateFormat extends DateFormat {
//
// private static final long serialVersionUID = -4079876635509458541L;
// private static final List<DateFormatFactory> DATE_FORMAT_FACTORIES = Arrays.asList(
// new DateFormatFactory() {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public DateFormat create() {
// return ResqueDateFormatThreadLocal.getInstance();
// }
// },
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_RUBY_V1),
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_RUBY_V2),
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_RUBY_V3),
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_RUBY_V4),
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_PHP)
// );
//
// public CompositeDateFormat() {
// super();
// setCalendar(new GregorianCalendar());
// setNumberFormat(new DecimalFormat());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public StringBuffer format(final Date date, final StringBuffer toAppendTo, final FieldPosition fieldPosition) {
// return ResqueDateFormatThreadLocal.getInstance().format(date, toAppendTo, fieldPosition);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Date parse(final String dateStr, final ParsePosition pos) {
// final ParsePosition posCopy = new ParsePosition(pos.getIndex());
// Date date = null;
// boolean success = false;
// for (final DateFormatFactory dfFactory : DATE_FORMAT_FACTORIES) {
// posCopy.setIndex(pos.getIndex());
// posCopy.setErrorIndex(pos.getErrorIndex());
// date = dfFactory.create().parse(dateStr, posCopy);
// if (date != null) {
// success = true;
// break;
// }
// }
// if (success) {
// pos.setIndex(posCopy.getIndex());
// pos.setErrorIndex(posCopy.getErrorIndex());
// }
// return date;
// }
//
// private interface DateFormatFactory {
// DateFormat create();
// }
//
// private static class PatternDateFormatFactory implements DateFormatFactory, Serializable {
//
// private static final long serialVersionUID = 3382491374377384377L;
//
// private final String pattern;
//
// /**
// * Constructor.
// *
// * @param pattern
// * the date format pattern
// */
// public PatternDateFormatFactory(final String pattern) {
// this.pattern = pattern;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public DateFormat create() {
// final SimpleDateFormat dateFormat = new SimpleDateFormat(this.pattern, Locale.US);
// dateFormat.setLenient(false);
// return dateFormat;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString() {
// return "PatternDateFormatFactory [pattern=" + this.pattern + "]";
// }
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import net.greghaines.jesque.utils.CompositeDateFormat;
import java.text.DateFormat; | /*
* Copyright 2011 Greg Haines
*
* 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 net.greghaines.jesque.json;
/**
* A helper that creates a fully-configured singleton ObjectMapper.
*
* @author Greg Haines
*/
public final class ObjectMapperFactory {
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); | // Path: src/main/java/net/greghaines/jesque/utils/CompositeDateFormat.java
// public class CompositeDateFormat extends DateFormat {
//
// private static final long serialVersionUID = -4079876635509458541L;
// private static final List<DateFormatFactory> DATE_FORMAT_FACTORIES = Arrays.asList(
// new DateFormatFactory() {
//
// /**
// * {@inheritDoc}
// */
// @Override
// public DateFormat create() {
// return ResqueDateFormatThreadLocal.getInstance();
// }
// },
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_RUBY_V1),
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_RUBY_V2),
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_RUBY_V3),
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_RUBY_V4),
// new PatternDateFormatFactory(ResqueConstants.DATE_FORMAT_PHP)
// );
//
// public CompositeDateFormat() {
// super();
// setCalendar(new GregorianCalendar());
// setNumberFormat(new DecimalFormat());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public StringBuffer format(final Date date, final StringBuffer toAppendTo, final FieldPosition fieldPosition) {
// return ResqueDateFormatThreadLocal.getInstance().format(date, toAppendTo, fieldPosition);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Date parse(final String dateStr, final ParsePosition pos) {
// final ParsePosition posCopy = new ParsePosition(pos.getIndex());
// Date date = null;
// boolean success = false;
// for (final DateFormatFactory dfFactory : DATE_FORMAT_FACTORIES) {
// posCopy.setIndex(pos.getIndex());
// posCopy.setErrorIndex(pos.getErrorIndex());
// date = dfFactory.create().parse(dateStr, posCopy);
// if (date != null) {
// success = true;
// break;
// }
// }
// if (success) {
// pos.setIndex(posCopy.getIndex());
// pos.setErrorIndex(posCopy.getErrorIndex());
// }
// return date;
// }
//
// private interface DateFormatFactory {
// DateFormat create();
// }
//
// private static class PatternDateFormatFactory implements DateFormatFactory, Serializable {
//
// private static final long serialVersionUID = 3382491374377384377L;
//
// private final String pattern;
//
// /**
// * Constructor.
// *
// * @param pattern
// * the date format pattern
// */
// public PatternDateFormatFactory(final String pattern) {
// this.pattern = pattern;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public DateFormat create() {
// final SimpleDateFormat dateFormat = new SimpleDateFormat(this.pattern, Locale.US);
// dateFormat.setLenient(false);
// return dateFormat;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public String toString() {
// return "PatternDateFormatFactory [pattern=" + this.pattern + "]";
// }
// }
// }
// Path: src/main/java/net/greghaines/jesque/json/ObjectMapperFactory.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import net.greghaines.jesque.utils.CompositeDateFormat;
import java.text.DateFormat;
/*
* Copyright 2011 Greg Haines
*
* 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 net.greghaines.jesque.json;
/**
* A helper that creates a fully-configured singleton ObjectMapper.
*
* @author Greg Haines
*/
public final class ObjectMapperFactory {
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); | final DateFormat jsonDateFormat = new CompositeDateFormat(); |
circonus-labs/fq | java/src/main/java/com/circonus/FqMessage.java | // Path: java/src/main/java/com/circonus/FqDataProtocolError.java
// public class FqDataProtocolError extends Exception {
// public FqDataProtocolError(String a) {
// super(a);
// }
// }
| import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import com.circonus.FqDataProtocolError; | public void setSender(byte[] _r) { sender = _r; sender_len = _r.length; }
public void setExchange(byte[] _r) { exchange = _r; exchange_len = _r.length; }
public void setMsgId() {
UUID uuid = UUID.randomUUID();
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
sender_msgid = new MsgId(bb.array());
}
public void setPayload(byte[] _r) { payload = _r; payload_len = _r.length; }
public String getRoute() { return new String(route, StandardCharsets.UTF_8); }
public String getExchange() { return new String(exchange, StandardCharsets.UTF_8); }
public String getSender() { return new String(sender, StandardCharsets.UTF_8); }
public MsgId getMsgId() { return sender_msgid; }
public byte[] getPayload() { return payload; }
public InetAddress[] getPath() { return hops; }
public boolean isComplete(boolean peermode) {
if(peermode) {
if(nhops < 0 || hops == null || sender_len < 0 || sender == null)
return false;
}
if(route_len <= 0 || route == null ||
exchange_len <= 0 || exchange == null ||
payload_len < 0 || payload == null || sender_msgid == null)
return false;
return true;
}
public boolean isComplete() { return _complete; } | // Path: java/src/main/java/com/circonus/FqDataProtocolError.java
// public class FqDataProtocolError extends Exception {
// public FqDataProtocolError(String a) {
// super(a);
// }
// }
// Path: java/src/main/java/com/circonus/FqMessage.java
import java.io.IOException;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import com.circonus.FqDataProtocolError;
public void setSender(byte[] _r) { sender = _r; sender_len = _r.length; }
public void setExchange(byte[] _r) { exchange = _r; exchange_len = _r.length; }
public void setMsgId() {
UUID uuid = UUID.randomUUID();
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
sender_msgid = new MsgId(bb.array());
}
public void setPayload(byte[] _r) { payload = _r; payload_len = _r.length; }
public String getRoute() { return new String(route, StandardCharsets.UTF_8); }
public String getExchange() { return new String(exchange, StandardCharsets.UTF_8); }
public String getSender() { return new String(sender, StandardCharsets.UTF_8); }
public MsgId getMsgId() { return sender_msgid; }
public byte[] getPayload() { return payload; }
public InetAddress[] getPath() { return hops; }
public boolean isComplete(boolean peermode) {
if(peermode) {
if(nhops < 0 || hops == null || sender_len < 0 || sender == null)
return false;
}
if(route_len <= 0 || route == null ||
exchange_len <= 0 || exchange == null ||
payload_len < 0 || payload == null || sender_msgid == null)
return false;
return true;
}
public boolean isComplete() { return _complete; } | public boolean read(FqClient c) throws IOException, FqDataProtocolError { |
holmari/gerritstats | GerritStats/src/main/java/com/holmsted/gerrit/Commit.java | // Path: GerritStats/src/main/java/com/holmsted/gerrit/GerritStatParser.java
// public static class ParserContext {
// final GerritVersion version;
//
// ParserContext(@Nonnull GerritVersion version) {
// this.version = version;
// }
// }
//
// Path: GerritCommon/src/main/java/com/holmsted/json/JsonUtils.java
// public final class JsonUtils {
//
// @Nonnull
// public static JSONObject readJsonString(String jsonString) {
// return new JSONObject(new JSONTokener(jsonString));
// }
//
// @Nonnull
// public static List<String> readStringArray(JSONArray array) {
// List<String> list = new ArrayList<>();
// for (int i = 0; i < array.length(); ++i) {
// list.add(array.getString(i));
// }
// return list;
// }
//
// private JsonUtils() {
// }
// }
| import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.holmsted.gerrit.GerritStatParser.ParserContext;
import com.holmsted.json.JsonUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable; |
@SuppressWarnings("PMD")
public PatchSet(int number,
@Nullable String revision,
@Nonnull List<String> parents,
@Nullable String ref,
@Nullable Identity uploader,
long createdOnDate,
@Nullable Identity author,
boolean isDraft,
@Nonnull PatchSetKind kind,
@Nonnull List<Approval> approvals,
@Nonnull List<PatchSetComment> comments,
int sizeInsertions,
int sizeDeletions) {
this.number = number;
this.revision = revision;
this.parents = parents;
this.ref = ref;
this.uploader = uploader;
this.createdOnDate = createdOnDate;
this.author = author;
this.isDraft = isDraft;
this.kind = kind;
this.approvals = ImmutableList.copyOf(approvals);
this.comments = ImmutableList.copyOf(comments);
this.sizeInsertions = sizeInsertions;
this.sizeDeletions = sizeDeletions;
}
| // Path: GerritStats/src/main/java/com/holmsted/gerrit/GerritStatParser.java
// public static class ParserContext {
// final GerritVersion version;
//
// ParserContext(@Nonnull GerritVersion version) {
// this.version = version;
// }
// }
//
// Path: GerritCommon/src/main/java/com/holmsted/json/JsonUtils.java
// public final class JsonUtils {
//
// @Nonnull
// public static JSONObject readJsonString(String jsonString) {
// return new JSONObject(new JSONTokener(jsonString));
// }
//
// @Nonnull
// public static List<String> readStringArray(JSONArray array) {
// List<String> list = new ArrayList<>();
// for (int i = 0; i < array.length(); ++i) {
// list.add(array.getString(i));
// }
// return list;
// }
//
// private JsonUtils() {
// }
// }
// Path: GerritStats/src/main/java/com/holmsted/gerrit/Commit.java
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.holmsted.gerrit.GerritStatParser.ParserContext;
import com.holmsted.json.JsonUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@SuppressWarnings("PMD")
public PatchSet(int number,
@Nullable String revision,
@Nonnull List<String> parents,
@Nullable String ref,
@Nullable Identity uploader,
long createdOnDate,
@Nullable Identity author,
boolean isDraft,
@Nonnull PatchSetKind kind,
@Nonnull List<Approval> approvals,
@Nonnull List<PatchSetComment> comments,
int sizeInsertions,
int sizeDeletions) {
this.number = number;
this.revision = revision;
this.parents = parents;
this.ref = ref;
this.uploader = uploader;
this.createdOnDate = createdOnDate;
this.author = author;
this.isDraft = isDraft;
this.kind = kind;
this.approvals = ImmutableList.copyOf(approvals);
this.comments = ImmutableList.copyOf(comments);
this.sizeInsertions = sizeInsertions;
this.sizeDeletions = sizeDeletions;
}
| static List<PatchSet> fromJsonArray(@Nullable JSONArray patchSetsJson, @Nonnull ParserContext context) { |
holmari/gerritstats | GerritStats/src/main/java/com/holmsted/gerrit/Commit.java | // Path: GerritStats/src/main/java/com/holmsted/gerrit/GerritStatParser.java
// public static class ParserContext {
// final GerritVersion version;
//
// ParserContext(@Nonnull GerritVersion version) {
// this.version = version;
// }
// }
//
// Path: GerritCommon/src/main/java/com/holmsted/json/JsonUtils.java
// public final class JsonUtils {
//
// @Nonnull
// public static JSONObject readJsonString(String jsonString) {
// return new JSONObject(new JSONTokener(jsonString));
// }
//
// @Nonnull
// public static List<String> readStringArray(JSONArray array) {
// List<String> list = new ArrayList<>();
// for (int i = 0; i < array.length(); ++i) {
// list.add(array.getString(i));
// }
// return list;
// }
//
// private JsonUtils() {
// }
// }
| import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.holmsted.gerrit.GerritStatParser.ParserContext;
import com.holmsted.json.JsonUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable; |
static PatchSet fromJson(@Nonnull JSONObject patchSetJson, @Nonnull ParserContext context) {
Identity uploader = Identity.fromJson(patchSetJson.optJSONObject("uploader"));
JSONObject authorJson = patchSetJson.optJSONObject("author");
Identity author;
if (authorJson != null) {
author = Identity.fromJson(authorJson);
} else {
author = uploader;
}
String kindString = patchSetJson.optString("kind");
PatchSetKind patchSetKind = PatchSetKind.REWORK;
try {
patchSetKind = PatchSetKind.valueOf(kindString);
} catch (IllegalArgumentException e) {
if (context.version.isAtLeast(2, 9)) {
System.err.println("Unknown patch set kind '" + kindString + "'");
} else {
// the 'kind' field does not exist before Gerrit 2.9 or so.
patchSetKind = PatchSetKind.REWORK;
}
}
long createdOnDate = patchSetJson.optLong("createdOn") * SEC_TO_MSEC;
return new PatchSet(
patchSetJson.optInt("number"),
patchSetJson.optString("revision"), | // Path: GerritStats/src/main/java/com/holmsted/gerrit/GerritStatParser.java
// public static class ParserContext {
// final GerritVersion version;
//
// ParserContext(@Nonnull GerritVersion version) {
// this.version = version;
// }
// }
//
// Path: GerritCommon/src/main/java/com/holmsted/json/JsonUtils.java
// public final class JsonUtils {
//
// @Nonnull
// public static JSONObject readJsonString(String jsonString) {
// return new JSONObject(new JSONTokener(jsonString));
// }
//
// @Nonnull
// public static List<String> readStringArray(JSONArray array) {
// List<String> list = new ArrayList<>();
// for (int i = 0; i < array.length(); ++i) {
// list.add(array.getString(i));
// }
// return list;
// }
//
// private JsonUtils() {
// }
// }
// Path: GerritStats/src/main/java/com/holmsted/gerrit/Commit.java
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.holmsted.gerrit.GerritStatParser.ParserContext;
import com.holmsted.json.JsonUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
static PatchSet fromJson(@Nonnull JSONObject patchSetJson, @Nonnull ParserContext context) {
Identity uploader = Identity.fromJson(patchSetJson.optJSONObject("uploader"));
JSONObject authorJson = patchSetJson.optJSONObject("author");
Identity author;
if (authorJson != null) {
author = Identity.fromJson(authorJson);
} else {
author = uploader;
}
String kindString = patchSetJson.optString("kind");
PatchSetKind patchSetKind = PatchSetKind.REWORK;
try {
patchSetKind = PatchSetKind.valueOf(kindString);
} catch (IllegalArgumentException e) {
if (context.version.isAtLeast(2, 9)) {
System.err.println("Unknown patch set kind '" + kindString + "'");
} else {
// the 'kind' field does not exist before Gerrit 2.9 or so.
patchSetKind = PatchSetKind.REWORK;
}
}
long createdOnDate = patchSetJson.optLong("createdOn") * SEC_TO_MSEC;
return new PatchSet(
patchSetJson.optInt("number"),
patchSetJson.optString("revision"), | JsonUtils.readStringArray(patchSetJson.optJSONArray("parents")), |
holmari/gerritstats | GerritStats/src/main/java/com/holmsted/gerrit/GerritStatParser.java | // Path: GerritCommon/src/main/java/com/holmsted/json/JsonUtils.java
// public final class JsonUtils {
//
// @Nonnull
// public static JSONObject readJsonString(String jsonString) {
// return new JSONObject(new JSONTokener(jsonString));
// }
//
// @Nonnull
// public static List<String> readStringArray(JSONArray array) {
// List<String> list = new ArrayList<>();
// for (int i = 0; i < array.length(); ++i) {
// list.add(array.getString(i));
// }
// return list;
// }
//
// private JsonUtils() {
// }
// }
| import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import com.holmsted.json.JsonUtils;
import javax.annotation.Nonnull; | package com.holmsted.gerrit;
public class GerritStatParser {
public static class ParserContext {
final GerritVersion version;
ParserContext(@Nonnull GerritVersion version) {
this.version = version;
}
}
public static class GerritData {
@Nonnull
final GerritVersion version;
@Nonnull
final List<Commit> commits = new ArrayList<>();
GerritData(@Nonnull GerritVersion version) {
this.version = version;
}
}
@Nonnull
public GerritData parseJsonData(@Nonnull String jsonFileData) {
GerritData data;
try { | // Path: GerritCommon/src/main/java/com/holmsted/json/JsonUtils.java
// public final class JsonUtils {
//
// @Nonnull
// public static JSONObject readJsonString(String jsonString) {
// return new JSONObject(new JSONTokener(jsonString));
// }
//
// @Nonnull
// public static List<String> readStringArray(JSONArray array) {
// List<String> list = new ArrayList<>();
// for (int i = 0; i < array.length(); ++i) {
// list.add(array.getString(i));
// }
// return list;
// }
//
// private JsonUtils() {
// }
// }
// Path: GerritStats/src/main/java/com/holmsted/gerrit/GerritStatParser.java
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import com.holmsted.json.JsonUtils;
import javax.annotation.Nonnull;
package com.holmsted.gerrit;
public class GerritStatParser {
public static class ParserContext {
final GerritVersion version;
ParserContext(@Nonnull GerritVersion version) {
this.version = version;
}
}
public static class GerritData {
@Nonnull
final GerritVersion version;
@Nonnull
final List<Commit> commits = new ArrayList<>();
GerritData(@Nonnull GerritVersion version) {
this.version = version;
}
}
@Nonnull
public GerritData parseJsonData(@Nonnull String jsonFileData) {
GerritData data;
try { | JSONObject object = JsonUtils.readJsonString(jsonFileData); |
holmari/gerritstats | GerritStats/src/main/java/com/holmsted/gerrit/anonymizer/FakeFilenameGenerator.java | // Path: GerritCommon/src/main/java/com/holmsted/RandomLists.java
// public final class RandomLists {
//
// private static final Random RANDOM_GENERATOR = new Random();
//
// public static int randomInt(int maxValue) {
// return RANDOM_GENERATOR.nextInt(maxValue);
// }
//
// public static <T> T randomItemFrom(@Nonnull List<T> items) {
// return items.get(randomInt(items.size()));
// }
//
// public static <T> T randomItemFrom(@Nonnull T[] list) {
// return list[randomInt(list.length)];
// }
//
// private RandomLists() {
// }
// }
| import com.holmsted.RandomLists;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull; | "Generator",
"Data",
"Formatter",
"Main",
"Connections",
"Mapper",
"List",
"HashMap",
"Set",
"Deque",
"Bus",
"Attributes",
"Signal",
"Cache",
"Cause",
"Exception",
"Listener",
"Singleton",
"Multiton",
"Document",
"Support",
"Library",
"Reference",
"Predicate"
};
private final Set<String> usedProjectNames = new HashSet<>();
private String generateFileBasename() {
StringBuilder builder = new StringBuilder(); | // Path: GerritCommon/src/main/java/com/holmsted/RandomLists.java
// public final class RandomLists {
//
// private static final Random RANDOM_GENERATOR = new Random();
//
// public static int randomInt(int maxValue) {
// return RANDOM_GENERATOR.nextInt(maxValue);
// }
//
// public static <T> T randomItemFrom(@Nonnull List<T> items) {
// return items.get(randomInt(items.size()));
// }
//
// public static <T> T randomItemFrom(@Nonnull T[] list) {
// return list[randomInt(list.length)];
// }
//
// private RandomLists() {
// }
// }
// Path: GerritStats/src/main/java/com/holmsted/gerrit/anonymizer/FakeFilenameGenerator.java
import com.holmsted.RandomLists;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
"Generator",
"Data",
"Formatter",
"Main",
"Connections",
"Mapper",
"List",
"HashMap",
"Set",
"Deque",
"Bus",
"Attributes",
"Signal",
"Cache",
"Cause",
"Exception",
"Listener",
"Singleton",
"Multiton",
"Document",
"Support",
"Library",
"Reference",
"Predicate"
};
private final Set<String> usedProjectNames = new HashSet<>();
private String generateFileBasename() {
StringBuilder builder = new StringBuilder(); | builder.append(RandomLists.randomItemFrom(FILENAME_BEGIN_PARTS)) |
holmari/gerritstats | GerritDownloader/src/main/java/com/holmsted/gerrit/GerritStatsDownloaderMain.java | // Path: GerritDownloader/src/main/java/com/holmsted/gerrit/downloaders/Downloader.java
// public class Downloader {
//
// private static final int FILE_FORMAT_VERSION = 1;
//
// @Nonnull
// private final CommandLineParser commandLine;
// @Nonnull
// private final GerritServer gerritServer;
//
// private GerritVersion gerritVersion;
//
// public Downloader(@Nonnull CommandLineParser commandLine) {
// this.commandLine = commandLine;
// gerritServer = new GerritServer(
// commandLine.getServerName(),
// commandLine.getServerPort(),
// commandLine.getPrivateKey());
// }
//
// public void download() {
// List<String> projectNames = commandLine.getProjectNames();
// if (projectNames == null || projectNames.isEmpty()) {
// projectNames = createProjectLister().getProjectListing();
// }
//
// gerritVersion = GerritSsh.version(gerritServer);
// if (gerritVersion == null) {
// System.out.println("Could not query for Gerrit version, aborting.");
// System.out.println("Are you sure the server name is correct, and that you are connected to it?");
// return;
// }
//
// for (String projectName : projectNames) {
// AbstractGerritStatsDownloader downloader = createDownloader();
// downloader.setOverallCommitLimit(commandLine.getCommitLimit());
// downloader.setAfterDate(commandLine.getAfterDate());
// downloader.setBeforeDate(commandLine.getBeforeDate());
// downloader.setProjectName(projectName);
// List<JSONObject> data = downloader.readData();
// if (data.isEmpty()) {
// System.out.println(String.format("No output was generated for project '%s'", projectName));
// } else {
// String outputDir = checkNotNull(commandLine.getOutputDir());
// String outputFilename = outputDir + File.separator + projectNameToFilename(projectName);
// writeJsonFile(outputFilename, data);
// System.out.println("Wrote output to " + outputFilename);
// }
// }
// }
//
// private void writeJsonFile(@Nonnull String outputFilename, @Nonnull List<JSONObject> data) {
// JSONObject root = new JSONObject();
// root.put("gerritStatsVersion", FILE_FORMAT_VERSION);
// root.put("gerritVersion", gerritVersion.toString());
// root.put("commits", data);
//
// FileWriter.writeFile(outputFilename, root.toString());
// }
//
// private ProjectLister createProjectLister() {
// return new SshProjectLister(gerritServer);
// }
//
// private AbstractGerritStatsDownloader createDownloader() {
// return new SshDownloader(gerritServer, checkNotNull(gerritVersion));
// }
//
// @Nonnull
// private static String projectNameToFilename(@Nonnull String projectName) {
// return sanitizeFilename(projectName) + ".json";
// }
//
// @Nonnull
// private static String sanitizeFilename(@Nonnull String filename) {
// return filename.replaceAll("[^a-zA-Z0-9.-]", "_");
// }
// }
| import com.holmsted.gerrit.downloaders.Downloader; | package com.holmsted.gerrit;
public final class GerritStatsDownloaderMain {
public static void main(String[] args) {
CommandLineParser commandLine = new CommandLineParser();
if (!commandLine.parse(args)) {
System.out.println("Reads Gerrit statistics from a server and writes them to a file.");
commandLine.printUsage();
System.exit(1);
return;
}
| // Path: GerritDownloader/src/main/java/com/holmsted/gerrit/downloaders/Downloader.java
// public class Downloader {
//
// private static final int FILE_FORMAT_VERSION = 1;
//
// @Nonnull
// private final CommandLineParser commandLine;
// @Nonnull
// private final GerritServer gerritServer;
//
// private GerritVersion gerritVersion;
//
// public Downloader(@Nonnull CommandLineParser commandLine) {
// this.commandLine = commandLine;
// gerritServer = new GerritServer(
// commandLine.getServerName(),
// commandLine.getServerPort(),
// commandLine.getPrivateKey());
// }
//
// public void download() {
// List<String> projectNames = commandLine.getProjectNames();
// if (projectNames == null || projectNames.isEmpty()) {
// projectNames = createProjectLister().getProjectListing();
// }
//
// gerritVersion = GerritSsh.version(gerritServer);
// if (gerritVersion == null) {
// System.out.println("Could not query for Gerrit version, aborting.");
// System.out.println("Are you sure the server name is correct, and that you are connected to it?");
// return;
// }
//
// for (String projectName : projectNames) {
// AbstractGerritStatsDownloader downloader = createDownloader();
// downloader.setOverallCommitLimit(commandLine.getCommitLimit());
// downloader.setAfterDate(commandLine.getAfterDate());
// downloader.setBeforeDate(commandLine.getBeforeDate());
// downloader.setProjectName(projectName);
// List<JSONObject> data = downloader.readData();
// if (data.isEmpty()) {
// System.out.println(String.format("No output was generated for project '%s'", projectName));
// } else {
// String outputDir = checkNotNull(commandLine.getOutputDir());
// String outputFilename = outputDir + File.separator + projectNameToFilename(projectName);
// writeJsonFile(outputFilename, data);
// System.out.println("Wrote output to " + outputFilename);
// }
// }
// }
//
// private void writeJsonFile(@Nonnull String outputFilename, @Nonnull List<JSONObject> data) {
// JSONObject root = new JSONObject();
// root.put("gerritStatsVersion", FILE_FORMAT_VERSION);
// root.put("gerritVersion", gerritVersion.toString());
// root.put("commits", data);
//
// FileWriter.writeFile(outputFilename, root.toString());
// }
//
// private ProjectLister createProjectLister() {
// return new SshProjectLister(gerritServer);
// }
//
// private AbstractGerritStatsDownloader createDownloader() {
// return new SshDownloader(gerritServer, checkNotNull(gerritVersion));
// }
//
// @Nonnull
// private static String projectNameToFilename(@Nonnull String projectName) {
// return sanitizeFilename(projectName) + ".json";
// }
//
// @Nonnull
// private static String sanitizeFilename(@Nonnull String filename) {
// return filename.replaceAll("[^a-zA-Z0-9.-]", "_");
// }
// }
// Path: GerritDownloader/src/main/java/com/holmsted/gerrit/GerritStatsDownloaderMain.java
import com.holmsted.gerrit.downloaders.Downloader;
package com.holmsted.gerrit;
public final class GerritStatsDownloaderMain {
public static void main(String[] args) {
CommandLineParser commandLine = new CommandLineParser();
if (!commandLine.parse(args)) {
System.out.println("Reads Gerrit statistics from a server and writes them to a file.");
commandLine.printUsage();
System.exit(1);
return;
}
| Downloader downloader = new Downloader(commandLine); |
holmari/gerritstats | GerritStats/src/main/java/com/holmsted/gerrit/anonymizer/FakeCommitTitleGenerator.java | // Path: GerritCommon/src/main/java/com/holmsted/RandomLists.java
// public final class RandomLists {
//
// private static final Random RANDOM_GENERATOR = new Random();
//
// public static int randomInt(int maxValue) {
// return RANDOM_GENERATOR.nextInt(maxValue);
// }
//
// public static <T> T randomItemFrom(@Nonnull List<T> items) {
// return items.get(randomInt(items.size()));
// }
//
// public static <T> T randomItemFrom(@Nonnull T[] list) {
// return list[randomInt(list.length)];
// }
//
// private RandomLists() {
// }
// }
| import com.holmsted.RandomLists; | "memory model",
"output parser",
"parser",
"frontend",
"component",
"UI widgets",
"aggregator",
"widget",
"reverse domain resolver",
"resolver",
"utility",
"command-line tools",
"tools",
"utilities",
"documentation",
"StackOverflow copypaster",
"hack",
"incubator",
"social network",
"3d moustache modeler",
"video sharing protocol",
"flight information sharing",
"supply chain aggregator",
"game theory planner",
"big data pipeline"
};
public static String generate() {
StringBuilder builder = new StringBuilder();
| // Path: GerritCommon/src/main/java/com/holmsted/RandomLists.java
// public final class RandomLists {
//
// private static final Random RANDOM_GENERATOR = new Random();
//
// public static int randomInt(int maxValue) {
// return RANDOM_GENERATOR.nextInt(maxValue);
// }
//
// public static <T> T randomItemFrom(@Nonnull List<T> items) {
// return items.get(randomInt(items.size()));
// }
//
// public static <T> T randomItemFrom(@Nonnull T[] list) {
// return list[randomInt(list.length)];
// }
//
// private RandomLists() {
// }
// }
// Path: GerritStats/src/main/java/com/holmsted/gerrit/anonymizer/FakeCommitTitleGenerator.java
import com.holmsted.RandomLists;
"memory model",
"output parser",
"parser",
"frontend",
"component",
"UI widgets",
"aggregator",
"widget",
"reverse domain resolver",
"resolver",
"utility",
"command-line tools",
"tools",
"utilities",
"documentation",
"StackOverflow copypaster",
"hack",
"incubator",
"social network",
"3d moustache modeler",
"video sharing protocol",
"flight information sharing",
"supply chain aggregator",
"game theory planner",
"big data pipeline"
};
public static String generate() {
StringBuilder builder = new StringBuilder();
| builder.append(RandomLists.randomItemFrom(ACTIONS)).append(' '); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.