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 |
|---|---|---|---|---|---|---|
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/AnnotationsCheckerTest.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/support/BaseProxyClass.java
// public abstract class BaseProxyClass {
//
// }
| import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.support.BaseProxyClass;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue; | package com.github.ggeorgovassilis.springjsonmapper.tests;
/**
* Verifies that annotations are correctly preserved on proxies
*
* @author george georgovassilis
*
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:test-context-annotations.xml")
public class AnnotationsCheckerTest {
@Resource(name = "BookService_DynamicProxy") | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/support/BaseProxyClass.java
// public abstract class BaseProxyClass {
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/AnnotationsCheckerTest.java
import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.support.BaseProxyClass;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
package com.github.ggeorgovassilis.springjsonmapper.tests;
/**
* Verifies that annotations are correctly preserved on proxies
*
* @author george georgovassilis
*
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:test-context-annotations.xml")
public class AnnotationsCheckerTest {
@Resource(name = "BookService_DynamicProxy") | protected BookService dynamicProxy; |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/AnnotationsCheckerTest.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/support/BaseProxyClass.java
// public abstract class BaseProxyClass {
//
// }
| import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.support.BaseProxyClass;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue; | if (method != null)
break;
}
}
return method;
}
/**
* Determines whether on a given method of a dynamic proxy whether there is
* somewhere (= class hierarchy, interfaces) annotations preserved.
*
* @throws Exception
*/
@Test
public void testAnnotationsOnDynamicProxy() throws Exception {
Method method = findMethodOnDynamicProxy("findBooksByTitle", dynamicProxy.getClass(),
new Class[] { String.class });
assertNotNull(method);
RequestMapping annotation = AnnotationUtils.findAnnotation(method, RequestMapping.class);
assertNotNull(annotation);
}
/**
* Determines whether a given method of an opaque proxy declares directly an
* annotation
*
* @throws Exception
*/
@Test
public void testAnnotationsOnOpaqueProxy() throws Exception { | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/support/BaseProxyClass.java
// public abstract class BaseProxyClass {
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/AnnotationsCheckerTest.java
import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.support.BaseProxyClass;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
if (method != null)
break;
}
}
return method;
}
/**
* Determines whether on a given method of a dynamic proxy whether there is
* somewhere (= class hierarchy, interfaces) annotations preserved.
*
* @throws Exception
*/
@Test
public void testAnnotationsOnDynamicProxy() throws Exception {
Method method = findMethodOnDynamicProxy("findBooksByTitle", dynamicProxy.getClass(),
new Class[] { String.class });
assertNotNull(method);
RequestMapping annotation = AnnotationUtils.findAnnotation(method, RequestMapping.class);
assertNotNull(annotation);
}
/**
* Determines whether a given method of an opaque proxy declares directly an
* annotation
*
* @throws Exception
*/
@Test
public void testAnnotationsOnOpaqueProxy() throws Exception { | assertTrue(opaqueProxy instanceof BaseProxyClass); |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/BankServiceShortcutSpringAnnotationTest.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BankServiceShortcutSpring.java
// public interface BankServiceShortcutSpring extends BankService {
//
// @Override
// @PostMapping("/transfer")
// Account transfer(@RequestBody @RequestParam("fromAccount") Account fromAccount,
// @RequestBody @RequestParam("actor") Customer actor,
// @RequestBody @RequestParam("toAccount") Account toAccount, @RequestBody @RequestParam("amount") int amount,
// @RequestParam("sendConfirmationSms") boolean sendConfirmationSms);
//
// @Override
// @PostMapping("/verify")
// Boolean checkAccount(@RequestBody Account account);
//
// @Override
// @PostMapping(value = "/photo", consumes = {"image/gif", "image/jpeg", "image/png"}, produces = {"image/jpeg"})
// byte[] updatePhoto(@RequestParam("name") String name, @RequestBody byte[] photo);
//
// @Override
// @PostMapping("/join-accounts")
// Account joinAccounts(@RequestPart @RequestParam("account1") Account account1,
// @RequestPart @RequestParam("account2") Account account2);
//
// @Override
// @PostMapping("/authenticate")
// Customer authenticate(@RequestPart @RequestParam("name") String name,
// @RequestPart @RequestParam("password") String password, @CookieValue("sid") String sessionId);
//
// @Override
// @GetMapping("/accounts/{id}")
// Account getAccount(@PathVariable("id") int id);
//
// @Override
// @GetMapping("/session/check")
// boolean isSessionAlive(@Header("X-SessionId") String sid);
//
// @Override
// @GetMapping("/${domain}/customer/{name}")
// boolean doesCustomerExist(@PathVariable("name") String name);
//
// @Override
// @GetMapping(value = "/${domain}/customer/{name}", headers = {"X-header-1=value1", "X-header-2=value2"})
// boolean doesCustomerExist2(@PathVariable("name") String name);
//
// @Override
// @GetMapping("/accounts")
// List<Account> getAllAccounts();
//
// }
//
// Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/SpringRestInvokerProxyFactoryBean.java
// public class SpringRestInvokerProxyFactoryBean extends BaseRestInvokerProxyFactoryBean {
//
// @Override
// protected MethodInspector constructDefaultMethodInspector() {
// List<MappingAnnotationResolver<? extends Annotation>> mappings = Arrays.asList(new RequestMappingAnnotationResolver(),
// new PutMappingAnnotationResolver(),
// new PostMappingAnnotationResolver(),
// new PatchMappingAnnotationResolver(),
// new GetMappingAnnotationResolver(),
// new DeleteMappingAnnotationResolver());
//
// MappingAnnotationsInspector mappingAnnotationsInspector = new MappingAnnotationsInspector(mappings);
// SpringAnnotationMethodInspector inspector = new SpringAnnotationMethodInspector(mappingAnnotationsInspector);
// inspector.setEmbeddedValueResolver(expressionResolver);
// return inspector;
// }
//
// }
| import com.github.ggeorgovassilis.springjsonmapper.services.spring.BankServiceShortcutSpring;
import com.github.ggeorgovassilis.springjsonmapper.spring.SpringRestInvokerProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.ContextConfiguration; | package com.github.ggeorgovassilis.springjsonmapper.tests;
@ContextConfiguration(classes = BankServiceShortcutSpringAnnotationTest.class)
@Configuration
@PropertySource("classpath:config.properties")
public class BankServiceShortcutSpringAnnotationTest extends AbstractBankServiceTest {
@Bean | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BankServiceShortcutSpring.java
// public interface BankServiceShortcutSpring extends BankService {
//
// @Override
// @PostMapping("/transfer")
// Account transfer(@RequestBody @RequestParam("fromAccount") Account fromAccount,
// @RequestBody @RequestParam("actor") Customer actor,
// @RequestBody @RequestParam("toAccount") Account toAccount, @RequestBody @RequestParam("amount") int amount,
// @RequestParam("sendConfirmationSms") boolean sendConfirmationSms);
//
// @Override
// @PostMapping("/verify")
// Boolean checkAccount(@RequestBody Account account);
//
// @Override
// @PostMapping(value = "/photo", consumes = {"image/gif", "image/jpeg", "image/png"}, produces = {"image/jpeg"})
// byte[] updatePhoto(@RequestParam("name") String name, @RequestBody byte[] photo);
//
// @Override
// @PostMapping("/join-accounts")
// Account joinAccounts(@RequestPart @RequestParam("account1") Account account1,
// @RequestPart @RequestParam("account2") Account account2);
//
// @Override
// @PostMapping("/authenticate")
// Customer authenticate(@RequestPart @RequestParam("name") String name,
// @RequestPart @RequestParam("password") String password, @CookieValue("sid") String sessionId);
//
// @Override
// @GetMapping("/accounts/{id}")
// Account getAccount(@PathVariable("id") int id);
//
// @Override
// @GetMapping("/session/check")
// boolean isSessionAlive(@Header("X-SessionId") String sid);
//
// @Override
// @GetMapping("/${domain}/customer/{name}")
// boolean doesCustomerExist(@PathVariable("name") String name);
//
// @Override
// @GetMapping(value = "/${domain}/customer/{name}", headers = {"X-header-1=value1", "X-header-2=value2"})
// boolean doesCustomerExist2(@PathVariable("name") String name);
//
// @Override
// @GetMapping("/accounts")
// List<Account> getAllAccounts();
//
// }
//
// Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/SpringRestInvokerProxyFactoryBean.java
// public class SpringRestInvokerProxyFactoryBean extends BaseRestInvokerProxyFactoryBean {
//
// @Override
// protected MethodInspector constructDefaultMethodInspector() {
// List<MappingAnnotationResolver<? extends Annotation>> mappings = Arrays.asList(new RequestMappingAnnotationResolver(),
// new PutMappingAnnotationResolver(),
// new PostMappingAnnotationResolver(),
// new PatchMappingAnnotationResolver(),
// new GetMappingAnnotationResolver(),
// new DeleteMappingAnnotationResolver());
//
// MappingAnnotationsInspector mappingAnnotationsInspector = new MappingAnnotationsInspector(mappings);
// SpringAnnotationMethodInspector inspector = new SpringAnnotationMethodInspector(mappingAnnotationsInspector);
// inspector.setEmbeddedValueResolver(expressionResolver);
// return inspector;
// }
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/BankServiceShortcutSpringAnnotationTest.java
import com.github.ggeorgovassilis.springjsonmapper.services.spring.BankServiceShortcutSpring;
import com.github.ggeorgovassilis.springjsonmapper.spring.SpringRestInvokerProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.ContextConfiguration;
package com.github.ggeorgovassilis.springjsonmapper.tests;
@ContextConfiguration(classes = BankServiceShortcutSpringAnnotationTest.class)
@Configuration
@PropertySource("classpath:config.properties")
public class BankServiceShortcutSpringAnnotationTest extends AbstractBankServiceTest {
@Bean | SpringRestInvokerProxyFactoryBean BankService() { |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/BankServiceShortcutSpringAnnotationTest.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BankServiceShortcutSpring.java
// public interface BankServiceShortcutSpring extends BankService {
//
// @Override
// @PostMapping("/transfer")
// Account transfer(@RequestBody @RequestParam("fromAccount") Account fromAccount,
// @RequestBody @RequestParam("actor") Customer actor,
// @RequestBody @RequestParam("toAccount") Account toAccount, @RequestBody @RequestParam("amount") int amount,
// @RequestParam("sendConfirmationSms") boolean sendConfirmationSms);
//
// @Override
// @PostMapping("/verify")
// Boolean checkAccount(@RequestBody Account account);
//
// @Override
// @PostMapping(value = "/photo", consumes = {"image/gif", "image/jpeg", "image/png"}, produces = {"image/jpeg"})
// byte[] updatePhoto(@RequestParam("name") String name, @RequestBody byte[] photo);
//
// @Override
// @PostMapping("/join-accounts")
// Account joinAccounts(@RequestPart @RequestParam("account1") Account account1,
// @RequestPart @RequestParam("account2") Account account2);
//
// @Override
// @PostMapping("/authenticate")
// Customer authenticate(@RequestPart @RequestParam("name") String name,
// @RequestPart @RequestParam("password") String password, @CookieValue("sid") String sessionId);
//
// @Override
// @GetMapping("/accounts/{id}")
// Account getAccount(@PathVariable("id") int id);
//
// @Override
// @GetMapping("/session/check")
// boolean isSessionAlive(@Header("X-SessionId") String sid);
//
// @Override
// @GetMapping("/${domain}/customer/{name}")
// boolean doesCustomerExist(@PathVariable("name") String name);
//
// @Override
// @GetMapping(value = "/${domain}/customer/{name}", headers = {"X-header-1=value1", "X-header-2=value2"})
// boolean doesCustomerExist2(@PathVariable("name") String name);
//
// @Override
// @GetMapping("/accounts")
// List<Account> getAllAccounts();
//
// }
//
// Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/SpringRestInvokerProxyFactoryBean.java
// public class SpringRestInvokerProxyFactoryBean extends BaseRestInvokerProxyFactoryBean {
//
// @Override
// protected MethodInspector constructDefaultMethodInspector() {
// List<MappingAnnotationResolver<? extends Annotation>> mappings = Arrays.asList(new RequestMappingAnnotationResolver(),
// new PutMappingAnnotationResolver(),
// new PostMappingAnnotationResolver(),
// new PatchMappingAnnotationResolver(),
// new GetMappingAnnotationResolver(),
// new DeleteMappingAnnotationResolver());
//
// MappingAnnotationsInspector mappingAnnotationsInspector = new MappingAnnotationsInspector(mappings);
// SpringAnnotationMethodInspector inspector = new SpringAnnotationMethodInspector(mappingAnnotationsInspector);
// inspector.setEmbeddedValueResolver(expressionResolver);
// return inspector;
// }
//
// }
| import com.github.ggeorgovassilis.springjsonmapper.services.spring.BankServiceShortcutSpring;
import com.github.ggeorgovassilis.springjsonmapper.spring.SpringRestInvokerProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.ContextConfiguration; | package com.github.ggeorgovassilis.springjsonmapper.tests;
@ContextConfiguration(classes = BankServiceShortcutSpringAnnotationTest.class)
@Configuration
@PropertySource("classpath:config.properties")
public class BankServiceShortcutSpringAnnotationTest extends AbstractBankServiceTest {
@Bean
SpringRestInvokerProxyFactoryBean BankService() {
SpringRestInvokerProxyFactoryBean proxyFactory = new SpringRestInvokerProxyFactoryBean();
proxyFactory.setBaseUrl("http://localhost/bankservice"); | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BankServiceShortcutSpring.java
// public interface BankServiceShortcutSpring extends BankService {
//
// @Override
// @PostMapping("/transfer")
// Account transfer(@RequestBody @RequestParam("fromAccount") Account fromAccount,
// @RequestBody @RequestParam("actor") Customer actor,
// @RequestBody @RequestParam("toAccount") Account toAccount, @RequestBody @RequestParam("amount") int amount,
// @RequestParam("sendConfirmationSms") boolean sendConfirmationSms);
//
// @Override
// @PostMapping("/verify")
// Boolean checkAccount(@RequestBody Account account);
//
// @Override
// @PostMapping(value = "/photo", consumes = {"image/gif", "image/jpeg", "image/png"}, produces = {"image/jpeg"})
// byte[] updatePhoto(@RequestParam("name") String name, @RequestBody byte[] photo);
//
// @Override
// @PostMapping("/join-accounts")
// Account joinAccounts(@RequestPart @RequestParam("account1") Account account1,
// @RequestPart @RequestParam("account2") Account account2);
//
// @Override
// @PostMapping("/authenticate")
// Customer authenticate(@RequestPart @RequestParam("name") String name,
// @RequestPart @RequestParam("password") String password, @CookieValue("sid") String sessionId);
//
// @Override
// @GetMapping("/accounts/{id}")
// Account getAccount(@PathVariable("id") int id);
//
// @Override
// @GetMapping("/session/check")
// boolean isSessionAlive(@Header("X-SessionId") String sid);
//
// @Override
// @GetMapping("/${domain}/customer/{name}")
// boolean doesCustomerExist(@PathVariable("name") String name);
//
// @Override
// @GetMapping(value = "/${domain}/customer/{name}", headers = {"X-header-1=value1", "X-header-2=value2"})
// boolean doesCustomerExist2(@PathVariable("name") String name);
//
// @Override
// @GetMapping("/accounts")
// List<Account> getAllAccounts();
//
// }
//
// Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/SpringRestInvokerProxyFactoryBean.java
// public class SpringRestInvokerProxyFactoryBean extends BaseRestInvokerProxyFactoryBean {
//
// @Override
// protected MethodInspector constructDefaultMethodInspector() {
// List<MappingAnnotationResolver<? extends Annotation>> mappings = Arrays.asList(new RequestMappingAnnotationResolver(),
// new PutMappingAnnotationResolver(),
// new PostMappingAnnotationResolver(),
// new PatchMappingAnnotationResolver(),
// new GetMappingAnnotationResolver(),
// new DeleteMappingAnnotationResolver());
//
// MappingAnnotationsInspector mappingAnnotationsInspector = new MappingAnnotationsInspector(mappings);
// SpringAnnotationMethodInspector inspector = new SpringAnnotationMethodInspector(mappingAnnotationsInspector);
// inspector.setEmbeddedValueResolver(expressionResolver);
// return inspector;
// }
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/BankServiceShortcutSpringAnnotationTest.java
import com.github.ggeorgovassilis.springjsonmapper.services.spring.BankServiceShortcutSpring;
import com.github.ggeorgovassilis.springjsonmapper.spring.SpringRestInvokerProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.ContextConfiguration;
package com.github.ggeorgovassilis.springjsonmapper.tests;
@ContextConfiguration(classes = BankServiceShortcutSpringAnnotationTest.class)
@Configuration
@PropertySource("classpath:config.properties")
public class BankServiceShortcutSpringAnnotationTest extends AbstractBankServiceTest {
@Bean
SpringRestInvokerProxyFactoryBean BankService() {
SpringRestInvokerProxyFactoryBean proxyFactory = new SpringRestInvokerProxyFactoryBean();
proxyFactory.setBaseUrl("http://localhost/bankservice"); | proxyFactory.setRemoteServiceInterfaceClass(BankServiceShortcutSpring.class); |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BankServiceSpring.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Account.java
// @JsonPropertyOrder({ "accountNumber", "balance", "owner" })
// public class Account implements Serializable {
//
// private static final long serialVersionUID = 3338920622026973343L;
// private String accountNumber;
// private int balance;
// private Customer owner;
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public int getBalance() {
// return balance;
// }
//
// public void setBalance(int balance) {
// this.balance = balance;
// }
//
// public Customer getOwner() {
// return owner;
// }
//
// public void setOwner(Customer owner) {
// this.owner = owner;
// }
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BankService.java
// public interface BankService {
//
// Account transfer(Account fromAccount, Customer actor, Account toAccount, int amount, boolean sendConfirmationSms);
//
// Boolean checkAccount(Account account);
//
// byte[] updatePhoto(String name, byte[] photo);
//
// Account joinAccounts(Account account1, Account account2);
//
// Customer authenticate(String name, String password, String sessionId);
//
// Account getAccount(int id);
//
// boolean isSessionAlive(String sid);
//
// boolean doesCustomerExist(String name);
//
// boolean doesCustomerExist2(String name);
//
// List<Account> getAllAccounts();
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Customer.java
// public class Customer implements Serializable {
//
// private static final long serialVersionUID = 5450750236224806988L;
// private String name;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// }
| import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import com.github.ggeorgovassilis.springjsonmapper.model.Header;
import com.github.ggeorgovassilis.springjsonmapper.services.Account;
import com.github.ggeorgovassilis.springjsonmapper.services.BankService;
import com.github.ggeorgovassilis.springjsonmapper.services.Customer;
import java.util.List; | package com.github.ggeorgovassilis.springjsonmapper.services.spring;
/**
* Mapping to a hypothetical bank service REST API using Spring annotations
*
* @author george georgovassilis
*
*/
public interface BankServiceSpring extends BankService {
@Override
@RequestMapping(value = "/transfer", method = RequestMethod.POST) | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Account.java
// @JsonPropertyOrder({ "accountNumber", "balance", "owner" })
// public class Account implements Serializable {
//
// private static final long serialVersionUID = 3338920622026973343L;
// private String accountNumber;
// private int balance;
// private Customer owner;
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public int getBalance() {
// return balance;
// }
//
// public void setBalance(int balance) {
// this.balance = balance;
// }
//
// public Customer getOwner() {
// return owner;
// }
//
// public void setOwner(Customer owner) {
// this.owner = owner;
// }
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BankService.java
// public interface BankService {
//
// Account transfer(Account fromAccount, Customer actor, Account toAccount, int amount, boolean sendConfirmationSms);
//
// Boolean checkAccount(Account account);
//
// byte[] updatePhoto(String name, byte[] photo);
//
// Account joinAccounts(Account account1, Account account2);
//
// Customer authenticate(String name, String password, String sessionId);
//
// Account getAccount(int id);
//
// boolean isSessionAlive(String sid);
//
// boolean doesCustomerExist(String name);
//
// boolean doesCustomerExist2(String name);
//
// List<Account> getAllAccounts();
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Customer.java
// public class Customer implements Serializable {
//
// private static final long serialVersionUID = 5450750236224806988L;
// private String name;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BankServiceSpring.java
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import com.github.ggeorgovassilis.springjsonmapper.model.Header;
import com.github.ggeorgovassilis.springjsonmapper.services.Account;
import com.github.ggeorgovassilis.springjsonmapper.services.BankService;
import com.github.ggeorgovassilis.springjsonmapper.services.Customer;
import java.util.List;
package com.github.ggeorgovassilis.springjsonmapper.services.spring;
/**
* Mapping to a hypothetical bank service REST API using Spring annotations
*
* @author george georgovassilis
*
*/
public interface BankServiceSpring extends BankService {
@Override
@RequestMapping(value = "/transfer", method = RequestMethod.POST) | Account transfer(@RequestBody @RequestParam("fromAccount") Account fromAccount, |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BankServiceSpring.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Account.java
// @JsonPropertyOrder({ "accountNumber", "balance", "owner" })
// public class Account implements Serializable {
//
// private static final long serialVersionUID = 3338920622026973343L;
// private String accountNumber;
// private int balance;
// private Customer owner;
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public int getBalance() {
// return balance;
// }
//
// public void setBalance(int balance) {
// this.balance = balance;
// }
//
// public Customer getOwner() {
// return owner;
// }
//
// public void setOwner(Customer owner) {
// this.owner = owner;
// }
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BankService.java
// public interface BankService {
//
// Account transfer(Account fromAccount, Customer actor, Account toAccount, int amount, boolean sendConfirmationSms);
//
// Boolean checkAccount(Account account);
//
// byte[] updatePhoto(String name, byte[] photo);
//
// Account joinAccounts(Account account1, Account account2);
//
// Customer authenticate(String name, String password, String sessionId);
//
// Account getAccount(int id);
//
// boolean isSessionAlive(String sid);
//
// boolean doesCustomerExist(String name);
//
// boolean doesCustomerExist2(String name);
//
// List<Account> getAllAccounts();
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Customer.java
// public class Customer implements Serializable {
//
// private static final long serialVersionUID = 5450750236224806988L;
// private String name;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// }
| import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import com.github.ggeorgovassilis.springjsonmapper.model.Header;
import com.github.ggeorgovassilis.springjsonmapper.services.Account;
import com.github.ggeorgovassilis.springjsonmapper.services.BankService;
import com.github.ggeorgovassilis.springjsonmapper.services.Customer;
import java.util.List; | package com.github.ggeorgovassilis.springjsonmapper.services.spring;
/**
* Mapping to a hypothetical bank service REST API using Spring annotations
*
* @author george georgovassilis
*
*/
public interface BankServiceSpring extends BankService {
@Override
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
Account transfer(@RequestBody @RequestParam("fromAccount") Account fromAccount, | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Account.java
// @JsonPropertyOrder({ "accountNumber", "balance", "owner" })
// public class Account implements Serializable {
//
// private static final long serialVersionUID = 3338920622026973343L;
// private String accountNumber;
// private int balance;
// private Customer owner;
//
// public String getAccountNumber() {
// return accountNumber;
// }
//
// public void setAccountNumber(String accountNumber) {
// this.accountNumber = accountNumber;
// }
//
// public int getBalance() {
// return balance;
// }
//
// public void setBalance(int balance) {
// this.balance = balance;
// }
//
// public Customer getOwner() {
// return owner;
// }
//
// public void setOwner(Customer owner) {
// this.owner = owner;
// }
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BankService.java
// public interface BankService {
//
// Account transfer(Account fromAccount, Customer actor, Account toAccount, int amount, boolean sendConfirmationSms);
//
// Boolean checkAccount(Account account);
//
// byte[] updatePhoto(String name, byte[] photo);
//
// Account joinAccounts(Account account1, Account account2);
//
// Customer authenticate(String name, String password, String sessionId);
//
// Account getAccount(int id);
//
// boolean isSessionAlive(String sid);
//
// boolean doesCustomerExist(String name);
//
// boolean doesCustomerExist2(String name);
//
// List<Account> getAllAccounts();
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Customer.java
// public class Customer implements Serializable {
//
// private static final long serialVersionUID = 5450750236224806988L;
// private String name;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BankServiceSpring.java
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import com.github.ggeorgovassilis.springjsonmapper.model.Header;
import com.github.ggeorgovassilis.springjsonmapper.services.Account;
import com.github.ggeorgovassilis.springjsonmapper.services.BankService;
import com.github.ggeorgovassilis.springjsonmapper.services.Customer;
import java.util.List;
package com.github.ggeorgovassilis.springjsonmapper.services.spring;
/**
* Mapping to a hypothetical bank service REST API using Spring annotations
*
* @author george georgovassilis
*
*/
public interface BankServiceSpring extends BankService {
@Override
@RequestMapping(value = "/transfer", method = RequestMethod.POST)
Account transfer(@RequestBody @RequestParam("fromAccount") Account fromAccount, | @RequestBody @RequestParam("actor") Customer actor, |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BookServiceSpring.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Item.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -6854695261165137027L;
// String id;
// String selfLink;
// VolumeInfo volumeInfo;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSelfLink() {
// return selfLink;
// }
//
// public void setSelfLink(String selfLink) {
// this.selfLink = selfLink;
// }
//
// public VolumeInfo getVolumeInfo() {
// return volumeInfo;
// }
//
// public void setVolumeInfo(VolumeInfo volumeInfo) {
// this.volumeInfo = volumeInfo;
// }
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/QueryResult.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class QueryResult implements Serializable {
//
// private static final long serialVersionUID = 8453337880965373284L;
// private int totalItems;
// List<Item> items;
//
// public int getTotalItems() {
// return totalItems;
// }
//
// public void setTotalItems(int totalItems) {
// this.totalItems = totalItems;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// }
| import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.services.Item;
import com.github.ggeorgovassilis.springjsonmapper.services.QueryResult; | package com.github.ggeorgovassilis.springjsonmapper.services.spring;
/**
* Mapping to the google books API by using spring annotations
* https://developers.google.com/books/
*
* @author george georgovassilis
*
*/
public interface BookServiceSpring extends BookService {
@Override
@RequestMapping("/volumes") | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Item.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -6854695261165137027L;
// String id;
// String selfLink;
// VolumeInfo volumeInfo;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSelfLink() {
// return selfLink;
// }
//
// public void setSelfLink(String selfLink) {
// this.selfLink = selfLink;
// }
//
// public VolumeInfo getVolumeInfo() {
// return volumeInfo;
// }
//
// public void setVolumeInfo(VolumeInfo volumeInfo) {
// this.volumeInfo = volumeInfo;
// }
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/QueryResult.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class QueryResult implements Serializable {
//
// private static final long serialVersionUID = 8453337880965373284L;
// private int totalItems;
// List<Item> items;
//
// public int getTotalItems() {
// return totalItems;
// }
//
// public void setTotalItems(int totalItems) {
// this.totalItems = totalItems;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BookServiceSpring.java
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.services.Item;
import com.github.ggeorgovassilis.springjsonmapper.services.QueryResult;
package com.github.ggeorgovassilis.springjsonmapper.services.spring;
/**
* Mapping to the google books API by using spring annotations
* https://developers.google.com/books/
*
* @author george georgovassilis
*
*/
public interface BookServiceSpring extends BookService {
@Override
@RequestMapping("/volumes") | QueryResult findBooksByTitle(@RequestParam("q") String q); |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BookServiceSpring.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Item.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -6854695261165137027L;
// String id;
// String selfLink;
// VolumeInfo volumeInfo;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSelfLink() {
// return selfLink;
// }
//
// public void setSelfLink(String selfLink) {
// this.selfLink = selfLink;
// }
//
// public VolumeInfo getVolumeInfo() {
// return volumeInfo;
// }
//
// public void setVolumeInfo(VolumeInfo volumeInfo) {
// this.volumeInfo = volumeInfo;
// }
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/QueryResult.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class QueryResult implements Serializable {
//
// private static final long serialVersionUID = 8453337880965373284L;
// private int totalItems;
// List<Item> items;
//
// public int getTotalItems() {
// return totalItems;
// }
//
// public void setTotalItems(int totalItems) {
// this.totalItems = totalItems;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// }
| import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.services.Item;
import com.github.ggeorgovassilis.springjsonmapper.services.QueryResult; | package com.github.ggeorgovassilis.springjsonmapper.services.spring;
/**
* Mapping to the google books API by using spring annotations
* https://developers.google.com/books/
*
* @author george georgovassilis
*
*/
public interface BookServiceSpring extends BookService {
@Override
@RequestMapping("/volumes")
QueryResult findBooksByTitle(@RequestParam("q") String q);
@Override
@RequestMapping("/volumes/{id}") | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Item.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -6854695261165137027L;
// String id;
// String selfLink;
// VolumeInfo volumeInfo;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSelfLink() {
// return selfLink;
// }
//
// public void setSelfLink(String selfLink) {
// this.selfLink = selfLink;
// }
//
// public VolumeInfo getVolumeInfo() {
// return volumeInfo;
// }
//
// public void setVolumeInfo(VolumeInfo volumeInfo) {
// this.volumeInfo = volumeInfo;
// }
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/QueryResult.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class QueryResult implements Serializable {
//
// private static final long serialVersionUID = 8453337880965373284L;
// private int totalItems;
// List<Item> items;
//
// public int getTotalItems() {
// return totalItems;
// }
//
// public void setTotalItems(int totalItems) {
// this.totalItems = totalItems;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/spring/BookServiceSpring.java
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.services.Item;
import com.github.ggeorgovassilis.springjsonmapper.services.QueryResult;
package com.github.ggeorgovassilis.springjsonmapper.services.spring;
/**
* Mapping to the google books API by using spring annotations
* https://developers.google.com/books/
*
* @author george georgovassilis
*
*/
public interface BookServiceSpring extends BookService {
@Override
@RequestMapping("/volumes")
QueryResult findBooksByTitle(@RequestParam("q") String q);
@Override
@RequestMapping("/volumes/{id}") | Item findBookById(@PathVariable("id") String id); |
ggeorgovassilis/spring-rest-invoker | src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/mapping/PostMappingAnnotationResolver.java | // Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/model/UrlMapping.java
// public class UrlMapping {
//
// protected HttpMethod httpMethod = HttpMethod.GET;
// protected String url = "/";
// protected List<MethodParameterDescriptor> parameters = new ArrayList<MethodParameterDescriptor>();
// protected String[] headers = new String[0];
// protected String[] consumes = new String[0];
// protected String[] produces = new String[0];
// protected String[] cookies = new String[0];
//
// public String[] getCookies() {
// return cookies;
// }
//
// public void setCookies(String[] cookies) {
// this.cookies = cookies;
// }
//
// public String[] getConsumes() {
// return consumes;
// }
//
// public void setConsumes(String[] consumes) {
// this.consumes = consumes;
// }
//
// public String[] getProduces() {
// return produces;
// }
//
// public void setProduces(String[] produces) {
// this.produces = produces;
// }
//
// public String[] getHeaders() {
// return headers;
// }
//
// public void setHeaders(String[] headers) {
// this.headers = headers;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public HttpMethod getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public List<MethodParameterDescriptor> getParameters() {
// return parameters;
// }
//
// public void setParameters(List<MethodParameterDescriptor> parameters) {
// this.parameters = parameters;
// }
//
// public void addDescriptor(MethodParameterDescriptor descriptor) {
// parameters.add(descriptor);
// }
//
// public boolean hasRequestBody(String parameter) {
// for (MethodParameterDescriptor descriptor : parameters)
// if (parameter.equals(descriptor.getName())
// && (descriptor.getType().equals(Type.requestBody) || descriptor.getType().equals(Type.requestPart)))
// return true;
// return false;
// }
// }
| import com.github.ggeorgovassilis.springjsonmapper.model.UrlMapping;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.PostMapping; | package com.github.ggeorgovassilis.springjsonmapper.spring.mapping;
/**
* Looks at class and method and extract mapping annotations such as
* {@link PostMapping}
*
* @author minasgull
*/
public class PostMappingAnnotationResolver extends BaseAnnotationResolver<PostMapping> {
@Override | // Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/model/UrlMapping.java
// public class UrlMapping {
//
// protected HttpMethod httpMethod = HttpMethod.GET;
// protected String url = "/";
// protected List<MethodParameterDescriptor> parameters = new ArrayList<MethodParameterDescriptor>();
// protected String[] headers = new String[0];
// protected String[] consumes = new String[0];
// protected String[] produces = new String[0];
// protected String[] cookies = new String[0];
//
// public String[] getCookies() {
// return cookies;
// }
//
// public void setCookies(String[] cookies) {
// this.cookies = cookies;
// }
//
// public String[] getConsumes() {
// return consumes;
// }
//
// public void setConsumes(String[] consumes) {
// this.consumes = consumes;
// }
//
// public String[] getProduces() {
// return produces;
// }
//
// public void setProduces(String[] produces) {
// this.produces = produces;
// }
//
// public String[] getHeaders() {
// return headers;
// }
//
// public void setHeaders(String[] headers) {
// this.headers = headers;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public HttpMethod getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public List<MethodParameterDescriptor> getParameters() {
// return parameters;
// }
//
// public void setParameters(List<MethodParameterDescriptor> parameters) {
// this.parameters = parameters;
// }
//
// public void addDescriptor(MethodParameterDescriptor descriptor) {
// parameters.add(descriptor);
// }
//
// public boolean hasRequestBody(String parameter) {
// for (MethodParameterDescriptor descriptor : parameters)
// if (parameter.equals(descriptor.getName())
// && (descriptor.getType().equals(Type.requestBody) || descriptor.getType().equals(Type.requestPart)))
// return true;
// return false;
// }
// }
// Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/mapping/PostMappingAnnotationResolver.java
import com.github.ggeorgovassilis.springjsonmapper.model.UrlMapping;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.PostMapping;
package com.github.ggeorgovassilis.springjsonmapper.spring.mapping;
/**
* Looks at class and method and extract mapping annotations such as
* {@link PostMapping}
*
* @author minasgull
*/
public class PostMappingAnnotationResolver extends BaseAnnotationResolver<PostMapping> {
@Override | public UrlMapping resolve(PostMapping ann) { |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/spring/mapping/GetMappingAnnotationResolverTest.java | // Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/model/UrlMapping.java
// public class UrlMapping {
//
// protected HttpMethod httpMethod = HttpMethod.GET;
// protected String url = "/";
// protected List<MethodParameterDescriptor> parameters = new ArrayList<MethodParameterDescriptor>();
// protected String[] headers = new String[0];
// protected String[] consumes = new String[0];
// protected String[] produces = new String[0];
// protected String[] cookies = new String[0];
//
// public String[] getCookies() {
// return cookies;
// }
//
// public void setCookies(String[] cookies) {
// this.cookies = cookies;
// }
//
// public String[] getConsumes() {
// return consumes;
// }
//
// public void setConsumes(String[] consumes) {
// this.consumes = consumes;
// }
//
// public String[] getProduces() {
// return produces;
// }
//
// public void setProduces(String[] produces) {
// this.produces = produces;
// }
//
// public String[] getHeaders() {
// return headers;
// }
//
// public void setHeaders(String[] headers) {
// this.headers = headers;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public HttpMethod getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public List<MethodParameterDescriptor> getParameters() {
// return parameters;
// }
//
// public void setParameters(List<MethodParameterDescriptor> parameters) {
// this.parameters = parameters;
// }
//
// public void addDescriptor(MethodParameterDescriptor descriptor) {
// parameters.add(descriptor);
// }
//
// public boolean hasRequestBody(String parameter) {
// for (MethodParameterDescriptor descriptor : parameters)
// if (parameter.equals(descriptor.getName())
// && (descriptor.getType().equals(Type.requestBody) || descriptor.getType().equals(Type.requestPart)))
// return true;
// return false;
// }
// }
| import com.github.ggeorgovassilis.springjsonmapper.model.UrlMapping;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows; | package com.github.ggeorgovassilis.springjsonmapper.spring.mapping;
class GetMappingAnnotationResolverTest {
private GetMappingAnnotationResolver resolver;
@BeforeEach
void setUp() {
resolver = new GetMappingAnnotationResolver();
}
@Test
void testAmbiguousPath() {
assertThrows(AmbiguousMappingException.class, () -> {
resolver.resolve(getAnnotation(AmbiguousPath.class, "method"));
});
}
@Test
void testNoPath() { | // Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/model/UrlMapping.java
// public class UrlMapping {
//
// protected HttpMethod httpMethod = HttpMethod.GET;
// protected String url = "/";
// protected List<MethodParameterDescriptor> parameters = new ArrayList<MethodParameterDescriptor>();
// protected String[] headers = new String[0];
// protected String[] consumes = new String[0];
// protected String[] produces = new String[0];
// protected String[] cookies = new String[0];
//
// public String[] getCookies() {
// return cookies;
// }
//
// public void setCookies(String[] cookies) {
// this.cookies = cookies;
// }
//
// public String[] getConsumes() {
// return consumes;
// }
//
// public void setConsumes(String[] consumes) {
// this.consumes = consumes;
// }
//
// public String[] getProduces() {
// return produces;
// }
//
// public void setProduces(String[] produces) {
// this.produces = produces;
// }
//
// public String[] getHeaders() {
// return headers;
// }
//
// public void setHeaders(String[] headers) {
// this.headers = headers;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public HttpMethod getHttpMethod() {
// return httpMethod;
// }
//
// public void setHttpMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public List<MethodParameterDescriptor> getParameters() {
// return parameters;
// }
//
// public void setParameters(List<MethodParameterDescriptor> parameters) {
// this.parameters = parameters;
// }
//
// public void addDescriptor(MethodParameterDescriptor descriptor) {
// parameters.add(descriptor);
// }
//
// public boolean hasRequestBody(String parameter) {
// for (MethodParameterDescriptor descriptor : parameters)
// if (parameter.equals(descriptor.getName())
// && (descriptor.getType().equals(Type.requestBody) || descriptor.getType().equals(Type.requestPart)))
// return true;
// return false;
// }
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/spring/mapping/GetMappingAnnotationResolverTest.java
import com.github.ggeorgovassilis.springjsonmapper.model.UrlMapping;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
package com.github.ggeorgovassilis.springjsonmapper.spring.mapping;
class GetMappingAnnotationResolverTest {
private GetMappingAnnotationResolver resolver;
@BeforeEach
void setUp() {
resolver = new GetMappingAnnotationResolver();
}
@Test
void testAmbiguousPath() {
assertThrows(AmbiguousMappingException.class, () -> {
resolver.resolve(getAnnotation(AmbiguousPath.class, "method"));
});
}
@Test
void testNoPath() { | UrlMapping actual = resolver.resolve(getAnnotation(NoPath.class, "method")); |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/BankServiceJaxRsTest.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/jaxrs/BankServiceJaxRs.java
// public interface BankServiceJaxRs extends BankService {
//
// @Override
// @POST
// @Path("/transfer")
// Account transfer(@BeanParam @QueryParam("fromAccount") Account fromAccount,
// @BeanParam @QueryParam("actor") Customer actor, @BeanParam @QueryParam("toAccount") Account toAccount,
// @BeanParam @QueryParam("amount") int amount,
// @QueryParam("sendConfirmationSms") boolean sendConfirmationSms);
//
// @Override
// @POST
// @Path("/verify")
// Boolean checkAccount(@BeanParam Account account);
//
// @Override
// @POST
// @Path("/photo")
// @Consumes({ "image/gif", "image/jpeg", "image/png" })
// @Produces({ "image/jpeg" })
// byte[] updatePhoto(@QueryParam("name") String name, @BeanParam byte[] photo);
//
// @Override
// @POST
// @Path("/join-accounts")
// Account joinAccounts(@FormParam("") @QueryParam("account1") Account account1,
// @FormParam("") @QueryParam("account2") Account account2);
//
// @Override
// @POST
// @Path("/authenticate")
// Customer authenticate(@FormParam("") @QueryParam("name") String name,
// @FormParam("") @QueryParam("password") String password, @CookieParam("sid") String sessionId);
//
// @Override
// @Path("/accounts/{id}")
// Account getAccount(@PathParam("id") int id);
//
// @Override
// @Path("/session/check")
// boolean isSessionAlive(@HeaderParam("X-SessionId") String sid);
//
// @Override
// @Path("/${domain}/customer/{name}")
// boolean doesCustomerExist(@PathParam("name") String name);
//
// @Override
// @Path("/${domain}/customer/{name}")
// @Headers({"X-header-1=value1","X-header-2=value2"})
// boolean doesCustomerExist2(@PathParam("name") String name);
//
// @Override
// @Path(value = "/accounts")
// List<Account> getAllAccounts();
// }
| import org.springframework.test.context.ContextConfiguration;
import com.github.ggeorgovassilis.springjsonmapper.services.jaxrs.BankServiceJaxRs; | package com.github.ggeorgovassilis.springjsonmapper.tests;
/**
* Tests a more complex scenario with recorded HTTP requests and responses using
* the {@link JaxRsInvokerProxyFactoryBean}
*
* @author george georgovassilis
*
*/
@ContextConfiguration("classpath:test-context-bank-jaxrs.xml")
public class BankServiceJaxRsTest extends AbstractBankServiceTest {
@Override
protected String getExpectedServiceName() { | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/jaxrs/BankServiceJaxRs.java
// public interface BankServiceJaxRs extends BankService {
//
// @Override
// @POST
// @Path("/transfer")
// Account transfer(@BeanParam @QueryParam("fromAccount") Account fromAccount,
// @BeanParam @QueryParam("actor") Customer actor, @BeanParam @QueryParam("toAccount") Account toAccount,
// @BeanParam @QueryParam("amount") int amount,
// @QueryParam("sendConfirmationSms") boolean sendConfirmationSms);
//
// @Override
// @POST
// @Path("/verify")
// Boolean checkAccount(@BeanParam Account account);
//
// @Override
// @POST
// @Path("/photo")
// @Consumes({ "image/gif", "image/jpeg", "image/png" })
// @Produces({ "image/jpeg" })
// byte[] updatePhoto(@QueryParam("name") String name, @BeanParam byte[] photo);
//
// @Override
// @POST
// @Path("/join-accounts")
// Account joinAccounts(@FormParam("") @QueryParam("account1") Account account1,
// @FormParam("") @QueryParam("account2") Account account2);
//
// @Override
// @POST
// @Path("/authenticate")
// Customer authenticate(@FormParam("") @QueryParam("name") String name,
// @FormParam("") @QueryParam("password") String password, @CookieParam("sid") String sessionId);
//
// @Override
// @Path("/accounts/{id}")
// Account getAccount(@PathParam("id") int id);
//
// @Override
// @Path("/session/check")
// boolean isSessionAlive(@HeaderParam("X-SessionId") String sid);
//
// @Override
// @Path("/${domain}/customer/{name}")
// boolean doesCustomerExist(@PathParam("name") String name);
//
// @Override
// @Path("/${domain}/customer/{name}")
// @Headers({"X-header-1=value1","X-header-2=value2"})
// boolean doesCustomerExist2(@PathParam("name") String name);
//
// @Override
// @Path(value = "/accounts")
// List<Account> getAllAccounts();
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/tests/BankServiceJaxRsTest.java
import org.springframework.test.context.ContextConfiguration;
import com.github.ggeorgovassilis.springjsonmapper.services.jaxrs.BankServiceJaxRs;
package com.github.ggeorgovassilis.springjsonmapper.tests;
/**
* Tests a more complex scenario with recorded HTTP requests and responses using
* the {@link JaxRsInvokerProxyFactoryBean}
*
* @author george georgovassilis
*
*/
@ContextConfiguration("classpath:test-context-bank-jaxrs.xml")
public class BankServiceJaxRsTest extends AbstractBankServiceTest {
@Override
protected String getExpectedServiceName() { | return BankServiceJaxRs.class.getName(); |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/integrationtests/AbstractGoogleBooksApiTest.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Item.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -6854695261165137027L;
// String id;
// String selfLink;
// VolumeInfo volumeInfo;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSelfLink() {
// return selfLink;
// }
//
// public void setSelfLink(String selfLink) {
// this.selfLink = selfLink;
// }
//
// public VolumeInfo getVolumeInfo() {
// return volumeInfo;
// }
//
// public void setVolumeInfo(VolumeInfo volumeInfo) {
// this.volumeInfo = volumeInfo;
// }
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/QueryResult.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class QueryResult implements Serializable {
//
// private static final long serialVersionUID = 8453337880965373284L;
// private int totalItems;
// List<Item> items;
//
// public int getTotalItems() {
// return totalItems;
// }
//
// public void setTotalItems(int totalItems) {
// this.totalItems = totalItems;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/VolumeInfo.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class VolumeInfo implements Serializable {
// private static final long serialVersionUID = 3162880556852067979L;
// String title;
// List<String> authors;
// String publisher;
// String publishedDate;
// String description;
// List<String> categories;
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<String> getAuthors() {
// return authors;
// }
//
// public void setAuthors(List<String> authors) {
// this.authors = authors;
// }
//
// public String getPublisher() {
// return publisher;
// }
//
// public void setPublisher(String publisher) {
// this.publisher = publisher;
// }
//
// public String getPublishedDate() {
// return publishedDate;
// }
//
// public void setPublishedDate(String publishedDate) {
// this.publishedDate = publishedDate;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<String> getCategories() {
// return categories;
// }
//
// public void setCategories(List<String> categories) {
// this.categories = categories;
// }
// }
//
// Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/SpringRestInvokerProxyFactoryBean.java
// public class SpringRestInvokerProxyFactoryBean extends BaseRestInvokerProxyFactoryBean {
//
// @Override
// protected MethodInspector constructDefaultMethodInspector() {
// List<MappingAnnotationResolver<? extends Annotation>> mappings = Arrays.asList(new RequestMappingAnnotationResolver(),
// new PutMappingAnnotationResolver(),
// new PostMappingAnnotationResolver(),
// new PatchMappingAnnotationResolver(),
// new GetMappingAnnotationResolver(),
// new DeleteMappingAnnotationResolver());
//
// MappingAnnotationsInspector mappingAnnotationsInspector = new MappingAnnotationsInspector(mappings);
// SpringAnnotationMethodInspector inspector = new SpringAnnotationMethodInspector(mappingAnnotationsInspector);
// inspector.setEmbeddedValueResolver(expressionResolver);
// return inspector;
// }
//
// }
| import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.services.Item;
import com.github.ggeorgovassilis.springjsonmapper.services.QueryResult;
import com.github.ggeorgovassilis.springjsonmapper.services.VolumeInfo;
import com.github.ggeorgovassilis.springjsonmapper.spring.SpringRestInvokerProxyFactoryBean;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; | package com.github.ggeorgovassilis.springjsonmapper.integrationtests;
/**
* Integration test with the google books API using the
* {@link SpringRestInvokerProxyFactoryBean}
*
* @author george georgovassilis
*/
@ExtendWith(SpringExtension.class)
public abstract class AbstractGoogleBooksApiTest {
@Autowired | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Item.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -6854695261165137027L;
// String id;
// String selfLink;
// VolumeInfo volumeInfo;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSelfLink() {
// return selfLink;
// }
//
// public void setSelfLink(String selfLink) {
// this.selfLink = selfLink;
// }
//
// public VolumeInfo getVolumeInfo() {
// return volumeInfo;
// }
//
// public void setVolumeInfo(VolumeInfo volumeInfo) {
// this.volumeInfo = volumeInfo;
// }
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/QueryResult.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class QueryResult implements Serializable {
//
// private static final long serialVersionUID = 8453337880965373284L;
// private int totalItems;
// List<Item> items;
//
// public int getTotalItems() {
// return totalItems;
// }
//
// public void setTotalItems(int totalItems) {
// this.totalItems = totalItems;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/VolumeInfo.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class VolumeInfo implements Serializable {
// private static final long serialVersionUID = 3162880556852067979L;
// String title;
// List<String> authors;
// String publisher;
// String publishedDate;
// String description;
// List<String> categories;
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<String> getAuthors() {
// return authors;
// }
//
// public void setAuthors(List<String> authors) {
// this.authors = authors;
// }
//
// public String getPublisher() {
// return publisher;
// }
//
// public void setPublisher(String publisher) {
// this.publisher = publisher;
// }
//
// public String getPublishedDate() {
// return publishedDate;
// }
//
// public void setPublishedDate(String publishedDate) {
// this.publishedDate = publishedDate;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<String> getCategories() {
// return categories;
// }
//
// public void setCategories(List<String> categories) {
// this.categories = categories;
// }
// }
//
// Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/SpringRestInvokerProxyFactoryBean.java
// public class SpringRestInvokerProxyFactoryBean extends BaseRestInvokerProxyFactoryBean {
//
// @Override
// protected MethodInspector constructDefaultMethodInspector() {
// List<MappingAnnotationResolver<? extends Annotation>> mappings = Arrays.asList(new RequestMappingAnnotationResolver(),
// new PutMappingAnnotationResolver(),
// new PostMappingAnnotationResolver(),
// new PatchMappingAnnotationResolver(),
// new GetMappingAnnotationResolver(),
// new DeleteMappingAnnotationResolver());
//
// MappingAnnotationsInspector mappingAnnotationsInspector = new MappingAnnotationsInspector(mappings);
// SpringAnnotationMethodInspector inspector = new SpringAnnotationMethodInspector(mappingAnnotationsInspector);
// inspector.setEmbeddedValueResolver(expressionResolver);
// return inspector;
// }
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/integrationtests/AbstractGoogleBooksApiTest.java
import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.services.Item;
import com.github.ggeorgovassilis.springjsonmapper.services.QueryResult;
import com.github.ggeorgovassilis.springjsonmapper.services.VolumeInfo;
import com.github.ggeorgovassilis.springjsonmapper.spring.SpringRestInvokerProxyFactoryBean;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
package com.github.ggeorgovassilis.springjsonmapper.integrationtests;
/**
* Integration test with the google books API using the
* {@link SpringRestInvokerProxyFactoryBean}
*
* @author george georgovassilis
*/
@ExtendWith(SpringExtension.class)
public abstract class AbstractGoogleBooksApiTest {
@Autowired | protected BookService bookService; |
ggeorgovassilis/spring-rest-invoker | src/test/java/com/github/ggeorgovassilis/springjsonmapper/integrationtests/AbstractGoogleBooksApiTest.java | // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Item.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -6854695261165137027L;
// String id;
// String selfLink;
// VolumeInfo volumeInfo;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSelfLink() {
// return selfLink;
// }
//
// public void setSelfLink(String selfLink) {
// this.selfLink = selfLink;
// }
//
// public VolumeInfo getVolumeInfo() {
// return volumeInfo;
// }
//
// public void setVolumeInfo(VolumeInfo volumeInfo) {
// this.volumeInfo = volumeInfo;
// }
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/QueryResult.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class QueryResult implements Serializable {
//
// private static final long serialVersionUID = 8453337880965373284L;
// private int totalItems;
// List<Item> items;
//
// public int getTotalItems() {
// return totalItems;
// }
//
// public void setTotalItems(int totalItems) {
// this.totalItems = totalItems;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/VolumeInfo.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class VolumeInfo implements Serializable {
// private static final long serialVersionUID = 3162880556852067979L;
// String title;
// List<String> authors;
// String publisher;
// String publishedDate;
// String description;
// List<String> categories;
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<String> getAuthors() {
// return authors;
// }
//
// public void setAuthors(List<String> authors) {
// this.authors = authors;
// }
//
// public String getPublisher() {
// return publisher;
// }
//
// public void setPublisher(String publisher) {
// this.publisher = publisher;
// }
//
// public String getPublishedDate() {
// return publishedDate;
// }
//
// public void setPublishedDate(String publishedDate) {
// this.publishedDate = publishedDate;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<String> getCategories() {
// return categories;
// }
//
// public void setCategories(List<String> categories) {
// this.categories = categories;
// }
// }
//
// Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/SpringRestInvokerProxyFactoryBean.java
// public class SpringRestInvokerProxyFactoryBean extends BaseRestInvokerProxyFactoryBean {
//
// @Override
// protected MethodInspector constructDefaultMethodInspector() {
// List<MappingAnnotationResolver<? extends Annotation>> mappings = Arrays.asList(new RequestMappingAnnotationResolver(),
// new PutMappingAnnotationResolver(),
// new PostMappingAnnotationResolver(),
// new PatchMappingAnnotationResolver(),
// new GetMappingAnnotationResolver(),
// new DeleteMappingAnnotationResolver());
//
// MappingAnnotationsInspector mappingAnnotationsInspector = new MappingAnnotationsInspector(mappings);
// SpringAnnotationMethodInspector inspector = new SpringAnnotationMethodInspector(mappingAnnotationsInspector);
// inspector.setEmbeddedValueResolver(expressionResolver);
// return inspector;
// }
//
// }
| import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.services.Item;
import com.github.ggeorgovassilis.springjsonmapper.services.QueryResult;
import com.github.ggeorgovassilis.springjsonmapper.services.VolumeInfo;
import com.github.ggeorgovassilis.springjsonmapper.spring.SpringRestInvokerProxyFactoryBean;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; | package com.github.ggeorgovassilis.springjsonmapper.integrationtests;
/**
* Integration test with the google books API using the
* {@link SpringRestInvokerProxyFactoryBean}
*
* @author george georgovassilis
*/
@ExtendWith(SpringExtension.class)
public abstract class AbstractGoogleBooksApiTest {
@Autowired
protected BookService bookService;
@Test
public void testFindBooksByTitle() throws Exception {
| // Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/BookService.java
// public interface BookService {
//
// QueryResult findBooksByTitle(String q);
//
// Item findBookById(String id);
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/Item.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -6854695261165137027L;
// String id;
// String selfLink;
// VolumeInfo volumeInfo;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getSelfLink() {
// return selfLink;
// }
//
// public void setSelfLink(String selfLink) {
// this.selfLink = selfLink;
// }
//
// public VolumeInfo getVolumeInfo() {
// return volumeInfo;
// }
//
// public void setVolumeInfo(VolumeInfo volumeInfo) {
// this.volumeInfo = volumeInfo;
// }
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/QueryResult.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class QueryResult implements Serializable {
//
// private static final long serialVersionUID = 8453337880965373284L;
// private int totalItems;
// List<Item> items;
//
// public int getTotalItems() {
// return totalItems;
// }
//
// public void setTotalItems(int totalItems) {
// this.totalItems = totalItems;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// }
//
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/services/VolumeInfo.java
// @JsonIgnoreProperties(ignoreUnknown = true)
// public class VolumeInfo implements Serializable {
// private static final long serialVersionUID = 3162880556852067979L;
// String title;
// List<String> authors;
// String publisher;
// String publishedDate;
// String description;
// List<String> categories;
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public List<String> getAuthors() {
// return authors;
// }
//
// public void setAuthors(List<String> authors) {
// this.authors = authors;
// }
//
// public String getPublisher() {
// return publisher;
// }
//
// public void setPublisher(String publisher) {
// this.publisher = publisher;
// }
//
// public String getPublishedDate() {
// return publishedDate;
// }
//
// public void setPublishedDate(String publishedDate) {
// this.publishedDate = publishedDate;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public List<String> getCategories() {
// return categories;
// }
//
// public void setCategories(List<String> categories) {
// this.categories = categories;
// }
// }
//
// Path: src/main/java/com/github/ggeorgovassilis/springjsonmapper/spring/SpringRestInvokerProxyFactoryBean.java
// public class SpringRestInvokerProxyFactoryBean extends BaseRestInvokerProxyFactoryBean {
//
// @Override
// protected MethodInspector constructDefaultMethodInspector() {
// List<MappingAnnotationResolver<? extends Annotation>> mappings = Arrays.asList(new RequestMappingAnnotationResolver(),
// new PutMappingAnnotationResolver(),
// new PostMappingAnnotationResolver(),
// new PatchMappingAnnotationResolver(),
// new GetMappingAnnotationResolver(),
// new DeleteMappingAnnotationResolver());
//
// MappingAnnotationsInspector mappingAnnotationsInspector = new MappingAnnotationsInspector(mappings);
// SpringAnnotationMethodInspector inspector = new SpringAnnotationMethodInspector(mappingAnnotationsInspector);
// inspector.setEmbeddedValueResolver(expressionResolver);
// return inspector;
// }
//
// }
// Path: src/test/java/com/github/ggeorgovassilis/springjsonmapper/integrationtests/AbstractGoogleBooksApiTest.java
import com.github.ggeorgovassilis.springjsonmapper.services.BookService;
import com.github.ggeorgovassilis.springjsonmapper.services.Item;
import com.github.ggeorgovassilis.springjsonmapper.services.QueryResult;
import com.github.ggeorgovassilis.springjsonmapper.services.VolumeInfo;
import com.github.ggeorgovassilis.springjsonmapper.spring.SpringRestInvokerProxyFactoryBean;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
package com.github.ggeorgovassilis.springjsonmapper.integrationtests;
/**
* Integration test with the google books API using the
* {@link SpringRestInvokerProxyFactoryBean}
*
* @author george georgovassilis
*/
@ExtendWith(SpringExtension.class)
public abstract class AbstractGoogleBooksApiTest {
@Autowired
protected BookService bookService;
@Test
public void testFindBooksByTitle() throws Exception {
| QueryResult result = bookService.findBooksByTitle("\"Philosophiae naturalis principia mathematica\""); |
k-tamura/easybuggy | src/main/java/org/t246osslab/easybuggy/core/servlets/PingServlet.java | // Path: src/main/java/org/t246osslab/easybuggy/core/utils/Closer.java
// public final class Closer {
//
// private static final Logger log = LoggerFactory.getLogger(Closer.class);
//
// // squid:S1118: Utility classes should not have public constructors
// private Closer() {
// throw new IllegalAccessError("Utility class");
// }
//
// /**
// * Close a Connection object.
// *
// * @param conn Connection object.
// */
// public static void close(Connection conn) {
// if (conn != null) {
// try {
// conn.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a Statement object.
// *
// * @param stmt Statement object.
// */
// public static void close(Statement stmt) {
// if (stmt != null) {
// try {
// stmt.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a ResultSet object.
// *
// * @param rs ResultSet object.
// */
// public static void close(ResultSet rs) {
// if (rs != null) {
// try {
// rs.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close all Closeable objects.
// *
// * @param closeables Closeable objects.
// */
// public static void close(Closeable... closeables) {
// if (closeables != null) {
// for (Closeable closeable : closeables) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
// }
//
// // for jdk 7 or later
// // /**
// // * Close all Closeable objects.
// // *
// // * @param closeables Closeable objects.
// // */
// // public static void close(AutoCloseable... closeables) {
// // if (closeables != null) {
// // for (AutoCloseable closeable : closeables) {
// // try {
// // if(closeable != null){
// // closeable.close();
// // }
// // } catch (IOException e) {
// // log.error("IOException occurs: ", e);
// // } catch (Exception e) {
// // log.error("Exception occurs: ", e);
// // }
// // }
// // }
// // }
// }
| import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.t246osslab.easybuggy.core.utils.Closer; | package org.t246osslab.easybuggy.core.servlets;
@SuppressWarnings("serial")
@WebServlet(urlPatterns = { "/ping" })
public class PingServlet extends AbstractServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter writer = null;
try {
res.setContentType("text/plain");
writer = res.getWriter();
writer.write("It works!");
} catch (Exception e) {
log.error("Exception occurs: ", e);
} finally { | // Path: src/main/java/org/t246osslab/easybuggy/core/utils/Closer.java
// public final class Closer {
//
// private static final Logger log = LoggerFactory.getLogger(Closer.class);
//
// // squid:S1118: Utility classes should not have public constructors
// private Closer() {
// throw new IllegalAccessError("Utility class");
// }
//
// /**
// * Close a Connection object.
// *
// * @param conn Connection object.
// */
// public static void close(Connection conn) {
// if (conn != null) {
// try {
// conn.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a Statement object.
// *
// * @param stmt Statement object.
// */
// public static void close(Statement stmt) {
// if (stmt != null) {
// try {
// stmt.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a ResultSet object.
// *
// * @param rs ResultSet object.
// */
// public static void close(ResultSet rs) {
// if (rs != null) {
// try {
// rs.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close all Closeable objects.
// *
// * @param closeables Closeable objects.
// */
// public static void close(Closeable... closeables) {
// if (closeables != null) {
// for (Closeable closeable : closeables) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
// }
//
// // for jdk 7 or later
// // /**
// // * Close all Closeable objects.
// // *
// // * @param closeables Closeable objects.
// // */
// // public static void close(AutoCloseable... closeables) {
// // if (closeables != null) {
// // for (AutoCloseable closeable : closeables) {
// // try {
// // if(closeable != null){
// // closeable.close();
// // }
// // } catch (IOException e) {
// // log.error("IOException occurs: ", e);
// // } catch (Exception e) {
// // log.error("Exception occurs: ", e);
// // }
// // }
// // }
// // }
// }
// Path: src/main/java/org/t246osslab/easybuggy/core/servlets/PingServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.t246osslab.easybuggy.core.utils.Closer;
package org.t246osslab.easybuggy.core.servlets;
@SuppressWarnings("serial")
@WebServlet(urlPatterns = { "/ping" })
public class PingServlet extends AbstractServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter writer = null;
try {
res.setContentType("text/plain");
writer = res.getWriter();
writer.write("It works!");
} catch (Exception e) {
log.error("Exception occurs: ", e);
} finally { | Closer.close(writer); |
k-tamura/easybuggy | src/main/java/org/t246osslab/easybuggy/core/listeners/InitializationListener.java | // Path: src/main/java/org/t246osslab/easybuggy/core/utils/Closer.java
// public final class Closer {
//
// private static final Logger log = LoggerFactory.getLogger(Closer.class);
//
// // squid:S1118: Utility classes should not have public constructors
// private Closer() {
// throw new IllegalAccessError("Utility class");
// }
//
// /**
// * Close a Connection object.
// *
// * @param conn Connection object.
// */
// public static void close(Connection conn) {
// if (conn != null) {
// try {
// conn.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a Statement object.
// *
// * @param stmt Statement object.
// */
// public static void close(Statement stmt) {
// if (stmt != null) {
// try {
// stmt.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a ResultSet object.
// *
// * @param rs ResultSet object.
// */
// public static void close(ResultSet rs) {
// if (rs != null) {
// try {
// rs.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close all Closeable objects.
// *
// * @param closeables Closeable objects.
// */
// public static void close(Closeable... closeables) {
// if (closeables != null) {
// for (Closeable closeable : closeables) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
// }
//
// // for jdk 7 or later
// // /**
// // * Close all Closeable objects.
// // *
// // * @param closeables Closeable objects.
// // */
// // public static void close(AutoCloseable... closeables) {
// // if (closeables != null) {
// // for (AutoCloseable closeable : closeables) {
// // try {
// // if(closeable != null){
// // closeable.close();
// // }
// // } catch (IOException e) {
// // log.error("IOException occurs: ", e);
// // } catch (Exception e) {
// // log.error("Exception occurs: ", e);
// // }
// // }
// // }
// // }
// }
| import java.io.OutputStream;
import java.io.PrintStream;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.owasp.esapi.ESAPI;
import org.t246osslab.easybuggy.core.utils.Closer;
| package org.t246osslab.easybuggy.core.listeners;
@WebListener
public class InitializationListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
/*
* Suppress noisy messages output by the ESAPI library. For more detail:
* https://stackoverflow.com/questions/45857064/how-to-suppress-messages-output-by-esapi-library
*/
PrintStream printStream = null;
OutputStream outputStream = null;
PrintStream original = System.out;
try {
outputStream = new OutputStream() {
public void write(int b) {
// Do nothing
}
};
printStream = new PrintStream(outputStream);
System.setOut(printStream);
System.setErr(printStream);
ESAPI.encoder();
} catch (Exception e) {
// Do nothing
} finally {
System.setOut(original);
| // Path: src/main/java/org/t246osslab/easybuggy/core/utils/Closer.java
// public final class Closer {
//
// private static final Logger log = LoggerFactory.getLogger(Closer.class);
//
// // squid:S1118: Utility classes should not have public constructors
// private Closer() {
// throw new IllegalAccessError("Utility class");
// }
//
// /**
// * Close a Connection object.
// *
// * @param conn Connection object.
// */
// public static void close(Connection conn) {
// if (conn != null) {
// try {
// conn.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a Statement object.
// *
// * @param stmt Statement object.
// */
// public static void close(Statement stmt) {
// if (stmt != null) {
// try {
// stmt.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a ResultSet object.
// *
// * @param rs ResultSet object.
// */
// public static void close(ResultSet rs) {
// if (rs != null) {
// try {
// rs.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close all Closeable objects.
// *
// * @param closeables Closeable objects.
// */
// public static void close(Closeable... closeables) {
// if (closeables != null) {
// for (Closeable closeable : closeables) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
// }
//
// // for jdk 7 or later
// // /**
// // * Close all Closeable objects.
// // *
// // * @param closeables Closeable objects.
// // */
// // public static void close(AutoCloseable... closeables) {
// // if (closeables != null) {
// // for (AutoCloseable closeable : closeables) {
// // try {
// // if(closeable != null){
// // closeable.close();
// // }
// // } catch (IOException e) {
// // log.error("IOException occurs: ", e);
// // } catch (Exception e) {
// // log.error("Exception occurs: ", e);
// // }
// // }
// // }
// // }
// }
// Path: src/main/java/org/t246osslab/easybuggy/core/listeners/InitializationListener.java
import java.io.OutputStream;
import java.io.PrintStream;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.owasp.esapi.ESAPI;
import org.t246osslab.easybuggy.core.utils.Closer;
package org.t246osslab.easybuggy.core.listeners;
@WebListener
public class InitializationListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
/*
* Suppress noisy messages output by the ESAPI library. For more detail:
* https://stackoverflow.com/questions/45857064/how-to-suppress-messages-output-by-esapi-library
*/
PrintStream printStream = null;
OutputStream outputStream = null;
PrintStream original = System.out;
try {
outputStream = new OutputStream() {
public void write(int b) {
// Do nothing
}
};
printStream = new PrintStream(outputStream);
System.setOut(printStream);
System.setErr(printStream);
ESAPI.encoder();
} catch (Exception e) {
// Do nothing
} finally {
System.setOut(original);
| Closer.close(printStream, outputStream);
|
k-tamura/easybuggy | src/main/java/org/t246osslab/easybuggy/core/servlets/AbstractServlet.java | // Path: src/main/java/org/t246osslab/easybuggy/core/utils/Closer.java
// public final class Closer {
//
// private static final Logger log = LoggerFactory.getLogger(Closer.class);
//
// // squid:S1118: Utility classes should not have public constructors
// private Closer() {
// throw new IllegalAccessError("Utility class");
// }
//
// /**
// * Close a Connection object.
// *
// * @param conn Connection object.
// */
// public static void close(Connection conn) {
// if (conn != null) {
// try {
// conn.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a Statement object.
// *
// * @param stmt Statement object.
// */
// public static void close(Statement stmt) {
// if (stmt != null) {
// try {
// stmt.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a ResultSet object.
// *
// * @param rs ResultSet object.
// */
// public static void close(ResultSet rs) {
// if (rs != null) {
// try {
// rs.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close all Closeable objects.
// *
// * @param closeables Closeable objects.
// */
// public static void close(Closeable... closeables) {
// if (closeables != null) {
// for (Closeable closeable : closeables) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
// }
//
// // for jdk 7 or later
// // /**
// // * Close all Closeable objects.
// // *
// // * @param closeables Closeable objects.
// // */
// // public static void close(AutoCloseable... closeables) {
// // if (closeables != null) {
// // for (AutoCloseable closeable : closeables) {
// // try {
// // if(closeable != null){
// // closeable.close();
// // }
// // } catch (IOException e) {
// // log.error("IOException occurs: ", e);
// // } catch (Exception e) {
// // log.error("Exception occurs: ", e);
// // }
// // }
// // }
// // }
// }
| import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.owasp.esapi.ESAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.t246osslab.easybuggy.core.utils.Closer;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
| writer.write("<table style=\"width:100%;\">");
writer.write("<tr><td>");
writer.write("<h2>");
writer.write("<span class=\"glyphicon glyphicon-globe\"></span> ");
if (htmlTitle != null) {
writer.write(htmlTitle);
}
writer.write("</h2>");
writer.write("</td>");
if (userid != null && req.getServletPath().startsWith("/admins")) {
writer.write("<td align=\"right\">");
writer.write(getMsg("label.login.user.id", locale) + ": " + userid);
writer.write("<br>");
writer.write("<a href=\"/logout\">" + getMsg("label.logout", locale) + "</a>");
writer.write("</td>");
} else {
writer.write("<td align=\"right\">");
writer.write("<a href=\"/\">" + getMsg("label.go.to.main", locale) + "</a>");
writer.write("</td>");
}
writer.write("</tr>");
writer.write("</table>");
writer.write("<hr style=\"margin-top:0px\">");
writer.write(htmlBody);
writer.write("</BODY>");
writer.write("</HTML>");
} catch (Exception e) {
log.error("Exception occurs: ", e);
} finally {
| // Path: src/main/java/org/t246osslab/easybuggy/core/utils/Closer.java
// public final class Closer {
//
// private static final Logger log = LoggerFactory.getLogger(Closer.class);
//
// // squid:S1118: Utility classes should not have public constructors
// private Closer() {
// throw new IllegalAccessError("Utility class");
// }
//
// /**
// * Close a Connection object.
// *
// * @param conn Connection object.
// */
// public static void close(Connection conn) {
// if (conn != null) {
// try {
// conn.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a Statement object.
// *
// * @param stmt Statement object.
// */
// public static void close(Statement stmt) {
// if (stmt != null) {
// try {
// stmt.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close a ResultSet object.
// *
// * @param rs ResultSet object.
// */
// public static void close(ResultSet rs) {
// if (rs != null) {
// try {
// rs.close();
// } catch (SQLException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
//
// /**
// * Close all Closeable objects.
// *
// * @param closeables Closeable objects.
// */
// public static void close(Closeable... closeables) {
// if (closeables != null) {
// for (Closeable closeable : closeables) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException e) {
// log.error("IOException occurs: ", e);
// }
// }
// }
// }
//
// // for jdk 7 or later
// // /**
// // * Close all Closeable objects.
// // *
// // * @param closeables Closeable objects.
// // */
// // public static void close(AutoCloseable... closeables) {
// // if (closeables != null) {
// // for (AutoCloseable closeable : closeables) {
// // try {
// // if(closeable != null){
// // closeable.close();
// // }
// // } catch (IOException e) {
// // log.error("IOException occurs: ", e);
// // } catch (Exception e) {
// // log.error("Exception occurs: ", e);
// // }
// // }
// // }
// // }
// }
// Path: src/main/java/org/t246osslab/easybuggy/core/servlets/AbstractServlet.java
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.owasp.esapi.ESAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.t246osslab.easybuggy.core.utils.Closer;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
writer.write("<table style=\"width:100%;\">");
writer.write("<tr><td>");
writer.write("<h2>");
writer.write("<span class=\"glyphicon glyphicon-globe\"></span> ");
if (htmlTitle != null) {
writer.write(htmlTitle);
}
writer.write("</h2>");
writer.write("</td>");
if (userid != null && req.getServletPath().startsWith("/admins")) {
writer.write("<td align=\"right\">");
writer.write(getMsg("label.login.user.id", locale) + ": " + userid);
writer.write("<br>");
writer.write("<a href=\"/logout\">" + getMsg("label.logout", locale) + "</a>");
writer.write("</td>");
} else {
writer.write("<td align=\"right\">");
writer.write("<a href=\"/\">" + getMsg("label.go.to.main", locale) + "</a>");
writer.write("</td>");
}
writer.write("</tr>");
writer.write("</table>");
writer.write("<hr style=\"margin-top:0px\">");
writer.write(htmlBody);
writer.write("</BODY>");
writer.write("</HTML>");
} catch (Exception e) {
log.error("Exception occurs: ", e);
} finally {
| Closer.close(writer);
|
republique-et-canton-de-geneve/chvote-1-0 | commons-base/commons-crypto/src/test/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtilsST.java | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java
// public static String generateStrongPasswordHash(char[] password) {
// int iterations = config.getIterations();
// byte[] salt = SaltUtils.generateSalt(SALT_SIZE_BYTES * 8);
//
// try {
// SecretKeyFactory skf = SecretKeyFactory.getInstance(config.getPbkdf2Algorithm());
// PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterations, 64 * 8);
// SecretKey secretKey = skf.generateSecret(keySpec);
//
// return String.format("%d:%s:%s", iterations, DatatypeConverter.printHexBinary(salt), DatatypeConverter.printHexBinary(secretKey.getEncoded()));
// } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// throw new CryptoOperationRuntimeException("cannot generate strong password hash", e);
// }
// }
//
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java
// public static boolean validateStrongPasswordHash(char[] passwd, String storedHash) {
// String[] parts = storedHash.split(":");
// if (parts.length != 3) {
// return false;
// }
//
// int iterations = Integer.parseInt(parts[0]);
// byte[] salt = fromHex(parts[1]);
// byte[] hash = fromHex(parts[2]);
//
// try {
// PBEKeySpec keySpec = new PBEKeySpec(passwd, salt, iterations, hash.length * 8);
// SecretKeyFactory skf = SecretKeyFactory.getInstance(config.getPbkdf2Algorithm());
// byte[] testHash = skf.generateSecret(keySpec).getEncoded();
// return constantTimeArrayCompare(hash, testHash);
// } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// throw new CryptoOperationRuntimeException("cannot validate strong password hash", e);
// }
// }
| import java.util.concurrent.TimeUnit;
import static ch.ge.ve.commons.crypto.SensitiveDataCryptoUtils.generateStrongPasswordHash;
import static ch.ge.ve.commons.crypto.SensitiveDataCryptoUtils.validateStrongPasswordHash;
import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.BeforeClass;
import org.junit.Test;
import java.math.BigInteger;
import java.security.Security; | /*
* -
* #%L
* Common crypto utilities
* %%
* Copyright (C) 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package ch.ge.ve.commons.crypto;
/**
* This test suit aims at stress testing the {@link SensitiveDataCryptoUtils} utility class.
*/
public class SensitiveDataCryptoUtilsST {
@BeforeClass
public static void init() {
Security.addProvider(new BouncyCastleProvider());
SensitiveDataCryptoUtils.configure(new TestSensitiveDataCryptoUtilsConfiguration());
}
/**
* Runs several times the {@link SensitiveDataCryptoUtils#validateStrongPasswordHash} method and logs the
* average execution time to identify a potential timing attack. This verification is manual, nothing is checked in
* this test case.
*/
@Test
public void analyzePotentialTimingAttacksOnPasswordHashVerification() {
char[] passwd = "A random te$ting p#s$w0rd!!!".toCharArray(); | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java
// public static String generateStrongPasswordHash(char[] password) {
// int iterations = config.getIterations();
// byte[] salt = SaltUtils.generateSalt(SALT_SIZE_BYTES * 8);
//
// try {
// SecretKeyFactory skf = SecretKeyFactory.getInstance(config.getPbkdf2Algorithm());
// PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterations, 64 * 8);
// SecretKey secretKey = skf.generateSecret(keySpec);
//
// return String.format("%d:%s:%s", iterations, DatatypeConverter.printHexBinary(salt), DatatypeConverter.printHexBinary(secretKey.getEncoded()));
// } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// throw new CryptoOperationRuntimeException("cannot generate strong password hash", e);
// }
// }
//
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java
// public static boolean validateStrongPasswordHash(char[] passwd, String storedHash) {
// String[] parts = storedHash.split(":");
// if (parts.length != 3) {
// return false;
// }
//
// int iterations = Integer.parseInt(parts[0]);
// byte[] salt = fromHex(parts[1]);
// byte[] hash = fromHex(parts[2]);
//
// try {
// PBEKeySpec keySpec = new PBEKeySpec(passwd, salt, iterations, hash.length * 8);
// SecretKeyFactory skf = SecretKeyFactory.getInstance(config.getPbkdf2Algorithm());
// byte[] testHash = skf.generateSecret(keySpec).getEncoded();
// return constantTimeArrayCompare(hash, testHash);
// } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// throw new CryptoOperationRuntimeException("cannot validate strong password hash", e);
// }
// }
// Path: commons-base/commons-crypto/src/test/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtilsST.java
import java.util.concurrent.TimeUnit;
import static ch.ge.ve.commons.crypto.SensitiveDataCryptoUtils.generateStrongPasswordHash;
import static ch.ge.ve.commons.crypto.SensitiveDataCryptoUtils.validateStrongPasswordHash;
import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.BeforeClass;
import org.junit.Test;
import java.math.BigInteger;
import java.security.Security;
/*
* -
* #%L
* Common crypto utilities
* %%
* Copyright (C) 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package ch.ge.ve.commons.crypto;
/**
* This test suit aims at stress testing the {@link SensitiveDataCryptoUtils} utility class.
*/
public class SensitiveDataCryptoUtilsST {
@BeforeClass
public static void init() {
Security.addProvider(new BouncyCastleProvider());
SensitiveDataCryptoUtils.configure(new TestSensitiveDataCryptoUtilsConfiguration());
}
/**
* Runs several times the {@link SensitiveDataCryptoUtils#validateStrongPasswordHash} method and logs the
* average execution time to identify a potential timing attack. This verification is manual, nothing is checked in
* this test case.
*/
@Test
public void analyzePotentialTimingAttacksOnPasswordHashVerification() {
char[] passwd = "A random te$ting p#s$w0rd!!!".toCharArray(); | String passwordHash = generateStrongPasswordHash(passwd); |
republique-et-canton-de-geneve/chvote-1-0 | commons-base/commons-crypto/src/test/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtilsST.java | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java
// public static String generateStrongPasswordHash(char[] password) {
// int iterations = config.getIterations();
// byte[] salt = SaltUtils.generateSalt(SALT_SIZE_BYTES * 8);
//
// try {
// SecretKeyFactory skf = SecretKeyFactory.getInstance(config.getPbkdf2Algorithm());
// PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterations, 64 * 8);
// SecretKey secretKey = skf.generateSecret(keySpec);
//
// return String.format("%d:%s:%s", iterations, DatatypeConverter.printHexBinary(salt), DatatypeConverter.printHexBinary(secretKey.getEncoded()));
// } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// throw new CryptoOperationRuntimeException("cannot generate strong password hash", e);
// }
// }
//
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java
// public static boolean validateStrongPasswordHash(char[] passwd, String storedHash) {
// String[] parts = storedHash.split(":");
// if (parts.length != 3) {
// return false;
// }
//
// int iterations = Integer.parseInt(parts[0]);
// byte[] salt = fromHex(parts[1]);
// byte[] hash = fromHex(parts[2]);
//
// try {
// PBEKeySpec keySpec = new PBEKeySpec(passwd, salt, iterations, hash.length * 8);
// SecretKeyFactory skf = SecretKeyFactory.getInstance(config.getPbkdf2Algorithm());
// byte[] testHash = skf.generateSecret(keySpec).getEncoded();
// return constantTimeArrayCompare(hash, testHash);
// } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// throw new CryptoOperationRuntimeException("cannot validate strong password hash", e);
// }
// }
| import java.util.concurrent.TimeUnit;
import static ch.ge.ve.commons.crypto.SensitiveDataCryptoUtils.generateStrongPasswordHash;
import static ch.ge.ve.commons.crypto.SensitiveDataCryptoUtils.validateStrongPasswordHash;
import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.BeforeClass;
import org.junit.Test;
import java.math.BigInteger;
import java.security.Security; | /*
* -
* #%L
* Common crypto utilities
* %%
* Copyright (C) 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package ch.ge.ve.commons.crypto;
/**
* This test suit aims at stress testing the {@link SensitiveDataCryptoUtils} utility class.
*/
public class SensitiveDataCryptoUtilsST {
@BeforeClass
public static void init() {
Security.addProvider(new BouncyCastleProvider());
SensitiveDataCryptoUtils.configure(new TestSensitiveDataCryptoUtilsConfiguration());
}
/**
* Runs several times the {@link SensitiveDataCryptoUtils#validateStrongPasswordHash} method and logs the
* average execution time to identify a potential timing attack. This verification is manual, nothing is checked in
* this test case.
*/
@Test
public void analyzePotentialTimingAttacksOnPasswordHashVerification() {
char[] passwd = "A random te$ting p#s$w0rd!!!".toCharArray();
String passwordHash = generateStrongPasswordHash(passwd);
int runs = 100;
System.out.printf("%-25s | %15s | %s (%d runs)%n", "Test", "average (ms)", "total", runs);
Stopwatch validPasswordChecking = Stopwatch.createStarted();
for (int i = 0; i < runs; i++) { | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java
// public static String generateStrongPasswordHash(char[] password) {
// int iterations = config.getIterations();
// byte[] salt = SaltUtils.generateSalt(SALT_SIZE_BYTES * 8);
//
// try {
// SecretKeyFactory skf = SecretKeyFactory.getInstance(config.getPbkdf2Algorithm());
// PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterations, 64 * 8);
// SecretKey secretKey = skf.generateSecret(keySpec);
//
// return String.format("%d:%s:%s", iterations, DatatypeConverter.printHexBinary(salt), DatatypeConverter.printHexBinary(secretKey.getEncoded()));
// } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// throw new CryptoOperationRuntimeException("cannot generate strong password hash", e);
// }
// }
//
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java
// public static boolean validateStrongPasswordHash(char[] passwd, String storedHash) {
// String[] parts = storedHash.split(":");
// if (parts.length != 3) {
// return false;
// }
//
// int iterations = Integer.parseInt(parts[0]);
// byte[] salt = fromHex(parts[1]);
// byte[] hash = fromHex(parts[2]);
//
// try {
// PBEKeySpec keySpec = new PBEKeySpec(passwd, salt, iterations, hash.length * 8);
// SecretKeyFactory skf = SecretKeyFactory.getInstance(config.getPbkdf2Algorithm());
// byte[] testHash = skf.generateSecret(keySpec).getEncoded();
// return constantTimeArrayCompare(hash, testHash);
// } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// throw new CryptoOperationRuntimeException("cannot validate strong password hash", e);
// }
// }
// Path: commons-base/commons-crypto/src/test/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtilsST.java
import java.util.concurrent.TimeUnit;
import static ch.ge.ve.commons.crypto.SensitiveDataCryptoUtils.generateStrongPasswordHash;
import static ch.ge.ve.commons.crypto.SensitiveDataCryptoUtils.validateStrongPasswordHash;
import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.BeforeClass;
import org.junit.Test;
import java.math.BigInteger;
import java.security.Security;
/*
* -
* #%L
* Common crypto utilities
* %%
* Copyright (C) 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package ch.ge.ve.commons.crypto;
/**
* This test suit aims at stress testing the {@link SensitiveDataCryptoUtils} utility class.
*/
public class SensitiveDataCryptoUtilsST {
@BeforeClass
public static void init() {
Security.addProvider(new BouncyCastleProvider());
SensitiveDataCryptoUtils.configure(new TestSensitiveDataCryptoUtilsConfiguration());
}
/**
* Runs several times the {@link SensitiveDataCryptoUtils#validateStrongPasswordHash} method and logs the
* average execution time to identify a potential timing attack. This verification is manual, nothing is checked in
* this test case.
*/
@Test
public void analyzePotentialTimingAttacksOnPasswordHashVerification() {
char[] passwd = "A random te$ting p#s$w0rd!!!".toCharArray();
String passwordHash = generateStrongPasswordHash(passwd);
int runs = 100;
System.out.printf("%-25s | %15s | %s (%d runs)%n", "Test", "average (ms)", "total", runs);
Stopwatch validPasswordChecking = Stopwatch.createStarted();
for (int i = 0; i < runs; i++) { | validateStrongPasswordHash(passwd, passwordHash); |
republique-et-canton-de-geneve/chvote-1-0 | commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/exceptions/CryptoOperationRuntimeException.java
// public class CryptoOperationRuntimeException extends RuntimeException {
// public CryptoOperationRuntimeException(String message) {
// super(message);
// }
//
// public CryptoOperationRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public CryptoOperationRuntimeException(Throwable cause) {
// super(cause);
// }
//
// public CryptoOperationRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/utils/SaltUtils.java
// public class SaltUtils {
// private static final SecureRandom SECURE_RANDOM = SecureRandomFactory.createPRNG();
//
// // Mask default constructor, this class should not be instantiated
// private SaltUtils() {}
//
// /**
// * Generates a salt using Java SecureRandom
// *
// * @param lengthInBits desired length of the salt
// * @return the salt
// */
// public static byte[] generateSalt(int lengthInBits) {
// Preconditions.checkArgument(lengthInBits % 8 == 0, String.format("The salt length must be a multiple of 8, but was %d!", lengthInBits));
// byte[] salt = new byte[lengthInBits / 8];
// SECURE_RANDOM.nextBytes(salt);
// return salt;
// }
// }
//
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/utils/SecureRandomFactory.java
// public class SecureRandomFactory {
// // Mask default constructor, this class shouldn't be instantiated
// private SecureRandomFactory() {}
//
// /**
// * Important notice from the SecureRandom javadoc:
// * <p>The returned SecureRandom object has not been seeded. To seed the
// * returned object, call the <code>setSeed</code> method.
// * If <code>setSeed</code> is not called, the first call to
// * <code>nextBytes</code> will force the SecureRandom object to seed itself.
// * This self-seeding will not occur if <code>setSeed</code> was
// * previously called.</p>
// *
// * @return a new, not already seeded, Pseudo Random Number Generator instance.
// */
// public static SecureRandom createPRNG() {
// try {
// return SecureRandom.getInstance("SHA1PRNG", "SUN");
// } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
// throw new CryptoConfigurationRuntimeException("Error creating PRNG", e);
// }
// }
//
// }
| import ch.ge.ve.commons.crypto.exceptions.CryptoOperationRuntimeException;
import ch.ge.ve.commons.crypto.utils.SaltUtils;
import ch.ge.ve.commons.crypto.utils.SecureRandomFactory;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Bytes;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.Serializable;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Base64; | /**
* Computes a salted MAC of the input
*
* @param input any string
* @param salt the salt to be used by the MAC
* @return the MAC (using algorithm defined in the {@link #config}) of the input string, using the provided salt
*/
public static byte[] buildMAC(String input, byte[] salt) {
return buildMAC(input.getBytes(), salt);
}
/**
* Computes a salted MAC of the input
*
* @param input any byte array
* @param salt the salt to be used by the MAC
* @return the MAC (using algorithm defined in the {@link #config}) of the input byte array, using the provided salt
*/
public static byte[] buildMAC(byte[] input, byte[] salt) {
try {
Mac mac = config.getMac();
mac.init(config.getSecretKey());
if (salt != null) {
mac.update(salt);
final byte[] macText = mac.doFinal(input);
return Bytes.concat(salt, macText);
} else {
return mac.doFinal(input);
}
} catch (GeneralSecurityException e) { | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/exceptions/CryptoOperationRuntimeException.java
// public class CryptoOperationRuntimeException extends RuntimeException {
// public CryptoOperationRuntimeException(String message) {
// super(message);
// }
//
// public CryptoOperationRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public CryptoOperationRuntimeException(Throwable cause) {
// super(cause);
// }
//
// public CryptoOperationRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/utils/SaltUtils.java
// public class SaltUtils {
// private static final SecureRandom SECURE_RANDOM = SecureRandomFactory.createPRNG();
//
// // Mask default constructor, this class should not be instantiated
// private SaltUtils() {}
//
// /**
// * Generates a salt using Java SecureRandom
// *
// * @param lengthInBits desired length of the salt
// * @return the salt
// */
// public static byte[] generateSalt(int lengthInBits) {
// Preconditions.checkArgument(lengthInBits % 8 == 0, String.format("The salt length must be a multiple of 8, but was %d!", lengthInBits));
// byte[] salt = new byte[lengthInBits / 8];
// SECURE_RANDOM.nextBytes(salt);
// return salt;
// }
// }
//
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/utils/SecureRandomFactory.java
// public class SecureRandomFactory {
// // Mask default constructor, this class shouldn't be instantiated
// private SecureRandomFactory() {}
//
// /**
// * Important notice from the SecureRandom javadoc:
// * <p>The returned SecureRandom object has not been seeded. To seed the
// * returned object, call the <code>setSeed</code> method.
// * If <code>setSeed</code> is not called, the first call to
// * <code>nextBytes</code> will force the SecureRandom object to seed itself.
// * This self-seeding will not occur if <code>setSeed</code> was
// * previously called.</p>
// *
// * @return a new, not already seeded, Pseudo Random Number Generator instance.
// */
// public static SecureRandom createPRNG() {
// try {
// return SecureRandom.getInstance("SHA1PRNG", "SUN");
// } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
// throw new CryptoConfigurationRuntimeException("Error creating PRNG", e);
// }
// }
//
// }
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/SensitiveDataCryptoUtils.java
import ch.ge.ve.commons.crypto.exceptions.CryptoOperationRuntimeException;
import ch.ge.ve.commons.crypto.utils.SaltUtils;
import ch.ge.ve.commons.crypto.utils.SecureRandomFactory;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Bytes;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.Serializable;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Base64;
/**
* Computes a salted MAC of the input
*
* @param input any string
* @param salt the salt to be used by the MAC
* @return the MAC (using algorithm defined in the {@link #config}) of the input string, using the provided salt
*/
public static byte[] buildMAC(String input, byte[] salt) {
return buildMAC(input.getBytes(), salt);
}
/**
* Computes a salted MAC of the input
*
* @param input any byte array
* @param salt the salt to be used by the MAC
* @return the MAC (using algorithm defined in the {@link #config}) of the input byte array, using the provided salt
*/
public static byte[] buildMAC(byte[] input, byte[] salt) {
try {
Mac mac = config.getMac();
mac.init(config.getSecretKey());
if (salt != null) {
mac.update(salt);
final byte[] macText = mac.doFinal(input);
return Bytes.concat(salt, macText);
} else {
return mac.doFinal(input);
}
} catch (GeneralSecurityException e) { | throw new CryptoOperationRuntimeException(e); |
republique-et-canton-de-geneve/chvote-1-0 | admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/ConsoleOutputControl.java | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/LogLevel.java
// public enum LogLevel {
// OK("ok-text", FontAwesomeIcon.CHECK.name()),
// WARN("warn-text", FontAwesomeIcon.EXCLAMATION_TRIANGLE.name()),
// ERROR("error-text", FontAwesomeIcon.EXCLAMATION_CIRCLE.name());
//
//
// private final String styleClass;
// private final String glyphName;
//
// /**
// * @param styleClass css style
// * @param glyphName icon name
// */
// LogLevel(String styleClass, String glyphName) {
// this.styleClass = styleClass;
// this.glyphName = glyphName;
// }
//
// /**
// * Getter on the css style
// * @return the css style
// */
// public String getStyleClass() {
// return styleClass;
// }
//
// /**
// * Getter on the icon name
// * @return the icon name
// */
// public String getGlyphName() {
// return glyphName;
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/LogMessage.java
// public class LogMessage {
// private final GlyphIcon glyphIcon;
// private final String message;
//
// public LogMessage(LogLevel logLevel, String message) {
// glyphIcon = new FontAwesomeIconView();
// glyphIcon.setGlyphName(logLevel.getGlyphName());
// glyphIcon.setGlyphSize(18);
// glyphIcon.setStyleClass(logLevel.getStyleClass());
// this.message = message;
// }
//
// public GlyphIcon getGlyphIcon() {
// return glyphIcon;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// LogMessage that = (LogMessage) o;
//
// if (glyphIcon != null ? !glyphIcon.equals(that.glyphIcon) : that.glyphIcon != null) {
// return false;
// }
// return !(message != null ? !message.equals(that.message) : that.message != null);
//
// }
//
// @Override
// public int hashCode() {
// int result = glyphIcon != null ? glyphIcon.hashCode() : 0;
// result = 31 * result + (message != null ? message.hashCode() : 0);
// return result;
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/ProgressTracker.java
// public interface ProgressTracker {
// /**
// * Adds a message with specific log level indicator to the progress tracker
// * @param message
// * @param logLevel
// */
// void progressMessage(String message, LogLevel logLevel);
//
// /**
// * Adds a message to the progress tracker, with level {@link LogLevel#OK}
// * @param message
// */
// void progressMessage(String message);
//
// /**
// * Sets the steps count
// * @param stepCount
// */
// void setStepCount(int stepCount);
//
// /**
// * Increments the steps count
// */
// void incrementStepCount();
// }
| import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import java.io.IOException;
import ch.ge.ve.offlineadmin.util.LogLevel;
import ch.ge.ve.offlineadmin.util.LogMessage;
import ch.ge.ve.offlineadmin.util.ProgressTracker;
import de.jensd.fx.glyphs.GlyphIcon;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event; |
logTable.setItems(logMessages);
ObservableList<TableColumn<LogMessage, ?>> tableColumns = logTable.getColumns();
tableColumns.add(logLevelColumn);
tableColumns.add(messageColumn);
logTable.setEditable(false);
// Prevent cell selection
logTable.addEventFilter(MouseEvent.ANY, Event::consume);
// Do not display a placeholder
logTable.setPlaceholder(new Label(""));
// Hide the header row
logTable.widthProperty().addListener((observable, oldValue, newValue) -> {
Pane header = (Pane) logTable.lookup("TableHeaderRow");
if (header.isVisible()) {
header.setMaxHeight(0);
header.setMinHeight(0);
header.setPrefHeight(0);
header.setVisible(false);
}
});
progressBar.setProgress(0f);
}
/**
* Add a message to the log table, with level {@link LogLevel#OK}
*
* @param message the message to be added
*/
public void logOnScreen(String message) { | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/LogLevel.java
// public enum LogLevel {
// OK("ok-text", FontAwesomeIcon.CHECK.name()),
// WARN("warn-text", FontAwesomeIcon.EXCLAMATION_TRIANGLE.name()),
// ERROR("error-text", FontAwesomeIcon.EXCLAMATION_CIRCLE.name());
//
//
// private final String styleClass;
// private final String glyphName;
//
// /**
// * @param styleClass css style
// * @param glyphName icon name
// */
// LogLevel(String styleClass, String glyphName) {
// this.styleClass = styleClass;
// this.glyphName = glyphName;
// }
//
// /**
// * Getter on the css style
// * @return the css style
// */
// public String getStyleClass() {
// return styleClass;
// }
//
// /**
// * Getter on the icon name
// * @return the icon name
// */
// public String getGlyphName() {
// return glyphName;
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/LogMessage.java
// public class LogMessage {
// private final GlyphIcon glyphIcon;
// private final String message;
//
// public LogMessage(LogLevel logLevel, String message) {
// glyphIcon = new FontAwesomeIconView();
// glyphIcon.setGlyphName(logLevel.getGlyphName());
// glyphIcon.setGlyphSize(18);
// glyphIcon.setStyleClass(logLevel.getStyleClass());
// this.message = message;
// }
//
// public GlyphIcon getGlyphIcon() {
// return glyphIcon;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// LogMessage that = (LogMessage) o;
//
// if (glyphIcon != null ? !glyphIcon.equals(that.glyphIcon) : that.glyphIcon != null) {
// return false;
// }
// return !(message != null ? !message.equals(that.message) : that.message != null);
//
// }
//
// @Override
// public int hashCode() {
// int result = glyphIcon != null ? glyphIcon.hashCode() : 0;
// result = 31 * result + (message != null ? message.hashCode() : 0);
// return result;
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/ProgressTracker.java
// public interface ProgressTracker {
// /**
// * Adds a message with specific log level indicator to the progress tracker
// * @param message
// * @param logLevel
// */
// void progressMessage(String message, LogLevel logLevel);
//
// /**
// * Adds a message to the progress tracker, with level {@link LogLevel#OK}
// * @param message
// */
// void progressMessage(String message);
//
// /**
// * Sets the steps count
// * @param stepCount
// */
// void setStepCount(int stepCount);
//
// /**
// * Increments the steps count
// */
// void incrementStepCount();
// }
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/ConsoleOutputControl.java
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import java.io.IOException;
import ch.ge.ve.offlineadmin.util.LogLevel;
import ch.ge.ve.offlineadmin.util.LogMessage;
import ch.ge.ve.offlineadmin.util.ProgressTracker;
import de.jensd.fx.glyphs.GlyphIcon;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
logTable.setItems(logMessages);
ObservableList<TableColumn<LogMessage, ?>> tableColumns = logTable.getColumns();
tableColumns.add(logLevelColumn);
tableColumns.add(messageColumn);
logTable.setEditable(false);
// Prevent cell selection
logTable.addEventFilter(MouseEvent.ANY, Event::consume);
// Do not display a placeholder
logTable.setPlaceholder(new Label(""));
// Hide the header row
logTable.widthProperty().addListener((observable, oldValue, newValue) -> {
Pane header = (Pane) logTable.lookup("TableHeaderRow");
if (header.isVisible()) {
header.setMaxHeight(0);
header.setMinHeight(0);
header.setPrefHeight(0);
header.setVisible(false);
}
});
progressBar.setProgress(0f);
}
/**
* Add a message to the log table, with level {@link LogLevel#OK}
*
* @param message the message to be added
*/
public void logOnScreen(String message) { | logOnScreen(message, LogLevel.OK); |
republique-et-canton-de-geneve/chvote-1-0 | commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/PropertyConfigurationProviderSecurityImpl.java | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/exceptions/CryptoConfigurationRuntimeException.java
// public class CryptoConfigurationRuntimeException extends RuntimeException {
//
// public CryptoConfigurationRuntimeException(String message) {
// super(message);
// }
//
// public CryptoConfigurationRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: commons-base/commons-properties/src/main/java/ch/ge/ve/commons/properties/PropertyConfigurationProvider.java
// public interface PropertyConfigurationProvider {
// /**
// * The properties of the module
// *
// * @return an non null Properties object
// */
// Properties getProperties();
// }
| import ch.ge.ve.commons.crypto.exceptions.CryptoConfigurationRuntimeException;
import ch.ge.ve.commons.properties.PropertyConfigurationProvider;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; | package ch.ge.ve.commons.crypto;
/*-
* #%L
* Common crypto utilities
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* Publishes the properties of the security/cryptographic configurations.
*/
public class PropertyConfigurationProviderSecurityImpl implements PropertyConfigurationProvider {
private static final String PROPS_FILE = "common-crypto.properties";
private Properties properties;
public PropertyConfigurationProviderSecurityImpl() {
properties = new Properties();
try {
final InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(PROPS_FILE);
if (resourceAsStream == null) { | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/exceptions/CryptoConfigurationRuntimeException.java
// public class CryptoConfigurationRuntimeException extends RuntimeException {
//
// public CryptoConfigurationRuntimeException(String message) {
// super(message);
// }
//
// public CryptoConfigurationRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: commons-base/commons-properties/src/main/java/ch/ge/ve/commons/properties/PropertyConfigurationProvider.java
// public interface PropertyConfigurationProvider {
// /**
// * The properties of the module
// *
// * @return an non null Properties object
// */
// Properties getProperties();
// }
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/PropertyConfigurationProviderSecurityImpl.java
import ch.ge.ve.commons.crypto.exceptions.CryptoConfigurationRuntimeException;
import ch.ge.ve.commons.properties.PropertyConfigurationProvider;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
package ch.ge.ve.commons.crypto;
/*-
* #%L
* Common crypto utilities
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* Publishes the properties of the security/cryptographic configurations.
*/
public class PropertyConfigurationProviderSecurityImpl implements PropertyConfigurationProvider {
private static final String PROPS_FILE = "common-crypto.properties";
private Properties properties;
public PropertyConfigurationProviderSecurityImpl() {
properties = new Properties();
try {
final InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(PROPS_FILE);
if (resourceAsStream == null) { | throw new CryptoConfigurationRuntimeException("Unable to load the configuration file from the classpath: " + PROPS_FILE); |
republique-et-canton-de-geneve/chvote-1-0 | admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/InterruptibleProcessController.java | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ResourceBundle;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority; | package ch.ge.ve.offlineadmin.controller;
/*-
* #%L
* Admin offline
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* This abstract class defines the handling of {@link ProcessInterruptedException}
* <p/>
* When such an error occurs, a dialog is shown with the exception stacktrace
*/
public abstract class InterruptibleProcessController {
public static final String PROCESS_INTERRUPTED_MESSAGE = "Process interrupted";
protected abstract ResourceBundle getResourceBundle();
/**
* Default handling of the exception, displays information in an alert dialog.
*
* @param e the exception
*/ | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/InterruptibleProcessController.java
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ResourceBundle;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
package ch.ge.ve.offlineadmin.controller;
/*-
* #%L
* Admin offline
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* This abstract class defines the handling of {@link ProcessInterruptedException}
* <p/>
* When such an error occurs, a dialog is shown with the exception stacktrace
*/
public abstract class InterruptibleProcessController {
public static final String PROCESS_INTERRUPTED_MESSAGE = "Process interrupted";
protected abstract ResourceBundle getResourceBundle();
/**
* Default handling of the exception, displays information in an alert dialog.
*
* @param e the exception
*/ | public void handleInterruption(ProcessInterruptedException e) { |
republique-et-canton-de-geneve/chvote-1-0 | commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/utils/SecureRandomFactory.java | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/exceptions/CryptoConfigurationRuntimeException.java
// public class CryptoConfigurationRuntimeException extends RuntimeException {
//
// public CryptoConfigurationRuntimeException(String message) {
// super(message);
// }
//
// public CryptoConfigurationRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import ch.ge.ve.commons.crypto.exceptions.CryptoConfigurationRuntimeException; | package ch.ge.ve.commons.crypto.utils;
/*-
* #%L
* Common crypto utilities
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* This class provides the centralized way of creating Secure Random Number Generator instances.
* <p/>
* The goal is to create SecureRandoms that specify their algorithm and implementation provider, so that
* the system behaves consistently whichever is the target operation system and jdk:
* <ul>
* <li>should not the implementation provider be provided, the OS native one could be used, and we do not want it</li>
* <li>should not the algorithm provider be provided, the default one of the jdk could be used, and we do not want it</li>
* </ul>
* <p/>
* As a secure coding rule, the direct creation of Random or SecureRandom is prohibited throughout the application.
*/
public class SecureRandomFactory {
// Mask default constructor, this class shouldn't be instantiated
private SecureRandomFactory() {}
/**
* Important notice from the SecureRandom javadoc:
* <p>The returned SecureRandom object has not been seeded. To seed the
* returned object, call the <code>setSeed</code> method.
* If <code>setSeed</code> is not called, the first call to
* <code>nextBytes</code> will force the SecureRandom object to seed itself.
* This self-seeding will not occur if <code>setSeed</code> was
* previously called.</p>
*
* @return a new, not already seeded, Pseudo Random Number Generator instance.
*/
public static SecureRandom createPRNG() {
try {
return SecureRandom.getInstance("SHA1PRNG", "SUN");
} catch (NoSuchAlgorithmException | NoSuchProviderException e) { | // Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/exceptions/CryptoConfigurationRuntimeException.java
// public class CryptoConfigurationRuntimeException extends RuntimeException {
//
// public CryptoConfigurationRuntimeException(String message) {
// super(message);
// }
//
// public CryptoConfigurationRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: commons-base/commons-crypto/src/main/java/ch/ge/ve/commons/crypto/utils/SecureRandomFactory.java
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import ch.ge.ve.commons.crypto.exceptions.CryptoConfigurationRuntimeException;
package ch.ge.ve.commons.crypto.utils;
/*-
* #%L
* Common crypto utilities
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* This class provides the centralized way of creating Secure Random Number Generator instances.
* <p/>
* The goal is to create SecureRandoms that specify their algorithm and implementation provider, so that
* the system behaves consistently whichever is the target operation system and jdk:
* <ul>
* <li>should not the implementation provider be provided, the OS native one could be used, and we do not want it</li>
* <li>should not the algorithm provider be provided, the default one of the jdk could be used, and we do not want it</li>
* </ul>
* <p/>
* As a secure coding rule, the direct creation of Random or SecureRandom is prohibited throughout the application.
*/
public class SecureRandomFactory {
// Mask default constructor, this class shouldn't be instantiated
private SecureRandomFactory() {}
/**
* Important notice from the SecureRandom javadoc:
* <p>The returned SecureRandom object has not been seeded. To seed the
* returned object, call the <code>setSeed</code> method.
* If <code>setSeed</code> is not called, the first call to
* <code>nextBytes</code> will force the SecureRandom object to seed itself.
* This self-seeding will not occur if <code>setSeed</code> was
* previously called.</p>
*
* @return a new, not already seeded, Pseudo Random Number Generator instance.
*/
public static SecureRandom createPRNG() {
try {
return SecureRandom.getInstance("SHA1PRNG", "SUN");
} catch (NoSuchAlgorithmException | NoSuchProviderException e) { | throw new CryptoConfigurationRuntimeException("Error creating PRNG", e); |
republique-et-canton-de-geneve/chvote-1-0 | admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/PasswordDialogController.java | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import javafx.scene.layout.GridPane;
import java.util.Optional;
import java.util.ResourceBundle;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*; | package ch.ge.ve.offlineadmin.controller;
/*-
* #%L
* Admin offline
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* Dialog to enter password(s)
*/
public class PasswordDialogController {
public static final int LABEL_COL = 0;
public static final int INPUT_COL = 1;
private static final double GRID_GAP = 10.0;
private static final Insets GRID_INSETS = new Insets(20, 150, 10, 10);
private final ResourceBundle resources;
private ConsoleOutputControl consoleOutputController;
public PasswordDialogController(ResourceBundle resources, ConsoleOutputControl consoleOutputController) {
this.resources = resources;
this.consoleOutputController = consoleOutputController;
}
private static boolean isPasswordValid(String newValue) {
// Length should be between 9 and 10 (incl)
boolean validLength = newValue.length() >= 9 && newValue.length() <= 10;
// Password should contain at least one upper, one lower and one digit
boolean validPattern = newValue.matches(".*[A-Z].*") && newValue.matches(".*[a-z].*") && newValue.matches(".*[0-9].*");
return validLength && validPattern;
}
/**
* Display the dialogs to enter the two passwords
* <p/>
* Whenever requested a password confirmation input-box is displayed
*
* @param password1 first password
* @param password2 second password
* @param withConfirmation indicates if password confirmation is needed
* @throws ProcessInterruptedException
*/ | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/PasswordDialogController.java
import javafx.scene.layout.GridPane;
import java.util.Optional;
import java.util.ResourceBundle;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.StringProperty;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
package ch.ge.ve.offlineadmin.controller;
/*-
* #%L
* Admin offline
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* Dialog to enter password(s)
*/
public class PasswordDialogController {
public static final int LABEL_COL = 0;
public static final int INPUT_COL = 1;
private static final double GRID_GAP = 10.0;
private static final Insets GRID_INSETS = new Insets(20, 150, 10, 10);
private final ResourceBundle resources;
private ConsoleOutputControl consoleOutputController;
public PasswordDialogController(ResourceBundle resources, ConsoleOutputControl consoleOutputController) {
this.resources = resources;
this.consoleOutputController = consoleOutputController;
}
private static boolean isPasswordValid(String newValue) {
// Length should be between 9 and 10 (incl)
boolean validLength = newValue.length() >= 9 && newValue.length() <= 10;
// Password should contain at least one upper, one lower and one digit
boolean validPattern = newValue.matches(".*[A-Z].*") && newValue.matches(".*[a-z].*") && newValue.matches(".*[0-9].*");
return validLength && validPattern;
}
/**
* Display the dialogs to enter the two passwords
* <p/>
* Whenever requested a password confirmation input-box is displayed
*
* @param password1 first password
* @param password2 second password
* @param withConfirmation indicates if password confirmation is needed
* @throws ProcessInterruptedException
*/ | public void promptForPasswords(StringProperty password1, StringProperty password2, boolean withConfirmation) throws ProcessInterruptedException { |
republique-et-canton-de-geneve/chvote-1-0 | admin-offline/src/main/java/ch/ge/ve/offlineadmin/OfflineAdminApp.java | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/InterruptibleProcessController.java
// public abstract class InterruptibleProcessController {
// public static final String PROCESS_INTERRUPTED_MESSAGE = "Process interrupted";
//
// protected abstract ResourceBundle getResourceBundle();
//
// /**
// * Default handling of the exception, displays information in an alert dialog.
// *
// * @param e the exception
// */
// public void handleInterruption(ProcessInterruptedException e) {
// if (Platform.isFxApplicationThread()) {
// showAlert(e);
// } else {
// Platform.runLater(() -> showAlert(e));
// }
// }
//
// private void showAlert(ProcessInterruptedException e) {
// Alert alert = new Alert(Alert.AlertType.ERROR);
// ResourceBundle resources = getResourceBundle();
// alert.setTitle(resources.getString("exception_alert.title"));
// alert.setHeaderText(resources.getString("exception_alert.header"));
// alert.setContentText(e.getMessage());
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// String exceptionText = sw.toString();
//
// Label stackTraceLabel = new Label(resources.getString("exception_alert.label"));
// TextArea stackTraceTextArea = new TextArea(exceptionText);
// stackTraceTextArea.setEditable(false);
// stackTraceTextArea.setWrapText(true);
// GridPane.setVgrow(stackTraceTextArea, Priority.ALWAYS);
// GridPane.setHgrow(stackTraceTextArea, Priority.ALWAYS);
//
// GridPane expandableContent = new GridPane();
// expandableContent.setPrefSize(400, 400);
// expandableContent.setMaxWidth(Double.MAX_VALUE);
// expandableContent.add(stackTraceLabel, 0, 0);
// expandableContent.add(stackTraceTextArea, 0, 1);
//
// alert.getDialogPane().setExpandableContent(expandableContent);
// // Dirty Linux only fix...
// // Expandable zones cause the dialog not to resize correctly
// if (System.getProperty("os.name").matches(".*[Ll]inux.*")) {
// alert.getDialogPane().setPrefSize(600, 400);
// alert.setResizable(true);
// alert.getDialogPane().setExpanded(true);
// }
//
// alert.showAndWait();
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/SecurityConstants.java
// public static final String PROPERTIES_LOG4J = "log4j.properties";
| import org.apache.log4j.PropertyConfigurator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Security;
import java.util.ResourceBundle;
import static ch.ge.ve.offlineadmin.util.SecurityConstants.PROPERTIES_LOG4J;
import ch.ge.ve.offlineadmin.controller.InterruptibleProcessController;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage; | package ch.ge.ve.offlineadmin;
/*-
* #%L
* Admin offline
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* Main class
*/
public class OfflineAdminApp extends Application {
/**
* @param args the arguments passed
*/
public static void main(String[] args) {
Security.addProvider(new BouncyCastleProvider());
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
PropertyConfigurator.configure(getLog4jProperties());
ResourceBundle resourceBundle = getBundle();
initializeDefaultExceptionHandler(resourceBundle);
primaryStage.setTitle(resourceBundle.getString("primaryStage.title"));
primaryStage.getIcons().add(new Image(OfflineAdminApp.class.getResourceAsStream("images/icon.gif")));
BorderPane rootLayout = initRootLayout(resourceBundle);
Scene mainScene = new Scene(rootLayout);
mainScene.getStylesheets().add(getStyleSheet().toExternalForm());
primaryStage.setScene(mainScene);
primaryStage.show();
}
private void initializeDefaultExceptionHandler(ResourceBundle resourceBundle) { | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/InterruptibleProcessController.java
// public abstract class InterruptibleProcessController {
// public static final String PROCESS_INTERRUPTED_MESSAGE = "Process interrupted";
//
// protected abstract ResourceBundle getResourceBundle();
//
// /**
// * Default handling of the exception, displays information in an alert dialog.
// *
// * @param e the exception
// */
// public void handleInterruption(ProcessInterruptedException e) {
// if (Platform.isFxApplicationThread()) {
// showAlert(e);
// } else {
// Platform.runLater(() -> showAlert(e));
// }
// }
//
// private void showAlert(ProcessInterruptedException e) {
// Alert alert = new Alert(Alert.AlertType.ERROR);
// ResourceBundle resources = getResourceBundle();
// alert.setTitle(resources.getString("exception_alert.title"));
// alert.setHeaderText(resources.getString("exception_alert.header"));
// alert.setContentText(e.getMessage());
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// String exceptionText = sw.toString();
//
// Label stackTraceLabel = new Label(resources.getString("exception_alert.label"));
// TextArea stackTraceTextArea = new TextArea(exceptionText);
// stackTraceTextArea.setEditable(false);
// stackTraceTextArea.setWrapText(true);
// GridPane.setVgrow(stackTraceTextArea, Priority.ALWAYS);
// GridPane.setHgrow(stackTraceTextArea, Priority.ALWAYS);
//
// GridPane expandableContent = new GridPane();
// expandableContent.setPrefSize(400, 400);
// expandableContent.setMaxWidth(Double.MAX_VALUE);
// expandableContent.add(stackTraceLabel, 0, 0);
// expandableContent.add(stackTraceTextArea, 0, 1);
//
// alert.getDialogPane().setExpandableContent(expandableContent);
// // Dirty Linux only fix...
// // Expandable zones cause the dialog not to resize correctly
// if (System.getProperty("os.name").matches(".*[Ll]inux.*")) {
// alert.getDialogPane().setPrefSize(600, 400);
// alert.setResizable(true);
// alert.getDialogPane().setExpanded(true);
// }
//
// alert.showAndWait();
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/SecurityConstants.java
// public static final String PROPERTIES_LOG4J = "log4j.properties";
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/OfflineAdminApp.java
import org.apache.log4j.PropertyConfigurator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Security;
import java.util.ResourceBundle;
import static ch.ge.ve.offlineadmin.util.SecurityConstants.PROPERTIES_LOG4J;
import ch.ge.ve.offlineadmin.controller.InterruptibleProcessController;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
package ch.ge.ve.offlineadmin;
/*-
* #%L
* Admin offline
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* Main class
*/
public class OfflineAdminApp extends Application {
/**
* @param args the arguments passed
*/
public static void main(String[] args) {
Security.addProvider(new BouncyCastleProvider());
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
PropertyConfigurator.configure(getLog4jProperties());
ResourceBundle resourceBundle = getBundle();
initializeDefaultExceptionHandler(resourceBundle);
primaryStage.setTitle(resourceBundle.getString("primaryStage.title"));
primaryStage.getIcons().add(new Image(OfflineAdminApp.class.getResourceAsStream("images/icon.gif")));
BorderPane rootLayout = initRootLayout(resourceBundle);
Scene mainScene = new Scene(rootLayout);
mainScene.getStylesheets().add(getStyleSheet().toExternalForm());
primaryStage.setScene(mainScene);
primaryStage.show();
}
private void initializeDefaultExceptionHandler(ResourceBundle resourceBundle) { | InterruptibleProcessController interruptibleProcessController = new InterruptibleProcessController() { |
republique-et-canton-de-geneve/chvote-1-0 | admin-offline/src/main/java/ch/ge/ve/offlineadmin/OfflineAdminApp.java | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/InterruptibleProcessController.java
// public abstract class InterruptibleProcessController {
// public static final String PROCESS_INTERRUPTED_MESSAGE = "Process interrupted";
//
// protected abstract ResourceBundle getResourceBundle();
//
// /**
// * Default handling of the exception, displays information in an alert dialog.
// *
// * @param e the exception
// */
// public void handleInterruption(ProcessInterruptedException e) {
// if (Platform.isFxApplicationThread()) {
// showAlert(e);
// } else {
// Platform.runLater(() -> showAlert(e));
// }
// }
//
// private void showAlert(ProcessInterruptedException e) {
// Alert alert = new Alert(Alert.AlertType.ERROR);
// ResourceBundle resources = getResourceBundle();
// alert.setTitle(resources.getString("exception_alert.title"));
// alert.setHeaderText(resources.getString("exception_alert.header"));
// alert.setContentText(e.getMessage());
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// String exceptionText = sw.toString();
//
// Label stackTraceLabel = new Label(resources.getString("exception_alert.label"));
// TextArea stackTraceTextArea = new TextArea(exceptionText);
// stackTraceTextArea.setEditable(false);
// stackTraceTextArea.setWrapText(true);
// GridPane.setVgrow(stackTraceTextArea, Priority.ALWAYS);
// GridPane.setHgrow(stackTraceTextArea, Priority.ALWAYS);
//
// GridPane expandableContent = new GridPane();
// expandableContent.setPrefSize(400, 400);
// expandableContent.setMaxWidth(Double.MAX_VALUE);
// expandableContent.add(stackTraceLabel, 0, 0);
// expandableContent.add(stackTraceTextArea, 0, 1);
//
// alert.getDialogPane().setExpandableContent(expandableContent);
// // Dirty Linux only fix...
// // Expandable zones cause the dialog not to resize correctly
// if (System.getProperty("os.name").matches(".*[Ll]inux.*")) {
// alert.getDialogPane().setPrefSize(600, 400);
// alert.setResizable(true);
// alert.getDialogPane().setExpanded(true);
// }
//
// alert.showAndWait();
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/SecurityConstants.java
// public static final String PROPERTIES_LOG4J = "log4j.properties";
| import org.apache.log4j.PropertyConfigurator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Security;
import java.util.ResourceBundle;
import static ch.ge.ve.offlineadmin.util.SecurityConstants.PROPERTIES_LOG4J;
import ch.ge.ve.offlineadmin.controller.InterruptibleProcessController;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage; | package ch.ge.ve.offlineadmin;
/*-
* #%L
* Admin offline
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* Main class
*/
public class OfflineAdminApp extends Application {
/**
* @param args the arguments passed
*/
public static void main(String[] args) {
Security.addProvider(new BouncyCastleProvider());
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
PropertyConfigurator.configure(getLog4jProperties());
ResourceBundle resourceBundle = getBundle();
initializeDefaultExceptionHandler(resourceBundle);
primaryStage.setTitle(resourceBundle.getString("primaryStage.title"));
primaryStage.getIcons().add(new Image(OfflineAdminApp.class.getResourceAsStream("images/icon.gif")));
BorderPane rootLayout = initRootLayout(resourceBundle);
Scene mainScene = new Scene(rootLayout);
mainScene.getStylesheets().add(getStyleSheet().toExternalForm());
primaryStage.setScene(mainScene);
primaryStage.show();
}
private void initializeDefaultExceptionHandler(ResourceBundle resourceBundle) {
InterruptibleProcessController interruptibleProcessController = new InterruptibleProcessController() {
@Override
protected ResourceBundle getResourceBundle() {
return resourceBundle;
}
};
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> { | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/InterruptibleProcessController.java
// public abstract class InterruptibleProcessController {
// public static final String PROCESS_INTERRUPTED_MESSAGE = "Process interrupted";
//
// protected abstract ResourceBundle getResourceBundle();
//
// /**
// * Default handling of the exception, displays information in an alert dialog.
// *
// * @param e the exception
// */
// public void handleInterruption(ProcessInterruptedException e) {
// if (Platform.isFxApplicationThread()) {
// showAlert(e);
// } else {
// Platform.runLater(() -> showAlert(e));
// }
// }
//
// private void showAlert(ProcessInterruptedException e) {
// Alert alert = new Alert(Alert.AlertType.ERROR);
// ResourceBundle resources = getResourceBundle();
// alert.setTitle(resources.getString("exception_alert.title"));
// alert.setHeaderText(resources.getString("exception_alert.header"));
// alert.setContentText(e.getMessage());
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// String exceptionText = sw.toString();
//
// Label stackTraceLabel = new Label(resources.getString("exception_alert.label"));
// TextArea stackTraceTextArea = new TextArea(exceptionText);
// stackTraceTextArea.setEditable(false);
// stackTraceTextArea.setWrapText(true);
// GridPane.setVgrow(stackTraceTextArea, Priority.ALWAYS);
// GridPane.setHgrow(stackTraceTextArea, Priority.ALWAYS);
//
// GridPane expandableContent = new GridPane();
// expandableContent.setPrefSize(400, 400);
// expandableContent.setMaxWidth(Double.MAX_VALUE);
// expandableContent.add(stackTraceLabel, 0, 0);
// expandableContent.add(stackTraceTextArea, 0, 1);
//
// alert.getDialogPane().setExpandableContent(expandableContent);
// // Dirty Linux only fix...
// // Expandable zones cause the dialog not to resize correctly
// if (System.getProperty("os.name").matches(".*[Ll]inux.*")) {
// alert.getDialogPane().setPrefSize(600, 400);
// alert.setResizable(true);
// alert.getDialogPane().setExpanded(true);
// }
//
// alert.showAndWait();
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/SecurityConstants.java
// public static final String PROPERTIES_LOG4J = "log4j.properties";
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/OfflineAdminApp.java
import org.apache.log4j.PropertyConfigurator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Security;
import java.util.ResourceBundle;
import static ch.ge.ve.offlineadmin.util.SecurityConstants.PROPERTIES_LOG4J;
import ch.ge.ve.offlineadmin.controller.InterruptibleProcessController;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
package ch.ge.ve.offlineadmin;
/*-
* #%L
* Admin offline
* %%
* Copyright (C) 2015 - 2016 République et Canton de Genève
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
/**
* Main class
*/
public class OfflineAdminApp extends Application {
/**
* @param args the arguments passed
*/
public static void main(String[] args) {
Security.addProvider(new BouncyCastleProvider());
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
PropertyConfigurator.configure(getLog4jProperties());
ResourceBundle resourceBundle = getBundle();
initializeDefaultExceptionHandler(resourceBundle);
primaryStage.setTitle(resourceBundle.getString("primaryStage.title"));
primaryStage.getIcons().add(new Image(OfflineAdminApp.class.getResourceAsStream("images/icon.gif")));
BorderPane rootLayout = initRootLayout(resourceBundle);
Scene mainScene = new Scene(rootLayout);
mainScene.getStylesheets().add(getStyleSheet().toExternalForm());
primaryStage.setScene(mainScene);
primaryStage.show();
}
private void initializeDefaultExceptionHandler(ResourceBundle resourceBundle) {
InterruptibleProcessController interruptibleProcessController = new InterruptibleProcessController() {
@Override
protected ResourceBundle getResourceBundle() {
return resourceBundle;
}
};
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> { | final ProcessInterruptedException processInterruptedException = new ProcessInterruptedException(resourceBundle.getString("exception_alert.generic-message"), e); |
republique-et-canton-de-geneve/chvote-1-0 | admin-offline/src/main/java/ch/ge/ve/offlineadmin/OfflineAdminApp.java | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/InterruptibleProcessController.java
// public abstract class InterruptibleProcessController {
// public static final String PROCESS_INTERRUPTED_MESSAGE = "Process interrupted";
//
// protected abstract ResourceBundle getResourceBundle();
//
// /**
// * Default handling of the exception, displays information in an alert dialog.
// *
// * @param e the exception
// */
// public void handleInterruption(ProcessInterruptedException e) {
// if (Platform.isFxApplicationThread()) {
// showAlert(e);
// } else {
// Platform.runLater(() -> showAlert(e));
// }
// }
//
// private void showAlert(ProcessInterruptedException e) {
// Alert alert = new Alert(Alert.AlertType.ERROR);
// ResourceBundle resources = getResourceBundle();
// alert.setTitle(resources.getString("exception_alert.title"));
// alert.setHeaderText(resources.getString("exception_alert.header"));
// alert.setContentText(e.getMessage());
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// String exceptionText = sw.toString();
//
// Label stackTraceLabel = new Label(resources.getString("exception_alert.label"));
// TextArea stackTraceTextArea = new TextArea(exceptionText);
// stackTraceTextArea.setEditable(false);
// stackTraceTextArea.setWrapText(true);
// GridPane.setVgrow(stackTraceTextArea, Priority.ALWAYS);
// GridPane.setHgrow(stackTraceTextArea, Priority.ALWAYS);
//
// GridPane expandableContent = new GridPane();
// expandableContent.setPrefSize(400, 400);
// expandableContent.setMaxWidth(Double.MAX_VALUE);
// expandableContent.add(stackTraceLabel, 0, 0);
// expandableContent.add(stackTraceTextArea, 0, 1);
//
// alert.getDialogPane().setExpandableContent(expandableContent);
// // Dirty Linux only fix...
// // Expandable zones cause the dialog not to resize correctly
// if (System.getProperty("os.name").matches(".*[Ll]inux.*")) {
// alert.getDialogPane().setPrefSize(600, 400);
// alert.setResizable(true);
// alert.getDialogPane().setExpanded(true);
// }
//
// alert.showAndWait();
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/SecurityConstants.java
// public static final String PROPERTIES_LOG4J = "log4j.properties";
| import org.apache.log4j.PropertyConfigurator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Security;
import java.util.ResourceBundle;
import static ch.ge.ve.offlineadmin.util.SecurityConstants.PROPERTIES_LOG4J;
import ch.ge.ve.offlineadmin.controller.InterruptibleProcessController;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage; | InterruptibleProcessController interruptibleProcessController = new InterruptibleProcessController() {
@Override
protected ResourceBundle getResourceBundle() {
return resourceBundle;
}
};
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
final ProcessInterruptedException processInterruptedException = new ProcessInterruptedException(resourceBundle.getString("exception_alert.generic-message"), e);
interruptibleProcessController.handleInterruption(processInterruptedException);
});
}
private BorderPane initRootLayout(ResourceBundle bundle) throws IOException {
FXMLLoader loader = new FXMLLoader();
URL resource = this.getClass().getResource("/ch/ge/ve/offlineadmin/view/RootLayout.fxml");
loader.setLocation(resource);
loader.setResources(bundle);
return loader.load();
}
private URL getStyleSheet() {
return this.getClass().getResource("/ch/ge/ve/offlineadmin/styles/offlineadmin.css");
}
private static ResourceBundle getBundle() {
return ResourceBundle.getBundle("ch.ge.ve.offlineadmin.bundles.offlineadmin-messages");
}
private InputStream getLog4jProperties() throws IOException { | // Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/controller/InterruptibleProcessController.java
// public abstract class InterruptibleProcessController {
// public static final String PROCESS_INTERRUPTED_MESSAGE = "Process interrupted";
//
// protected abstract ResourceBundle getResourceBundle();
//
// /**
// * Default handling of the exception, displays information in an alert dialog.
// *
// * @param e the exception
// */
// public void handleInterruption(ProcessInterruptedException e) {
// if (Platform.isFxApplicationThread()) {
// showAlert(e);
// } else {
// Platform.runLater(() -> showAlert(e));
// }
// }
//
// private void showAlert(ProcessInterruptedException e) {
// Alert alert = new Alert(Alert.AlertType.ERROR);
// ResourceBundle resources = getResourceBundle();
// alert.setTitle(resources.getString("exception_alert.title"));
// alert.setHeaderText(resources.getString("exception_alert.header"));
// alert.setContentText(e.getMessage());
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// String exceptionText = sw.toString();
//
// Label stackTraceLabel = new Label(resources.getString("exception_alert.label"));
// TextArea stackTraceTextArea = new TextArea(exceptionText);
// stackTraceTextArea.setEditable(false);
// stackTraceTextArea.setWrapText(true);
// GridPane.setVgrow(stackTraceTextArea, Priority.ALWAYS);
// GridPane.setHgrow(stackTraceTextArea, Priority.ALWAYS);
//
// GridPane expandableContent = new GridPane();
// expandableContent.setPrefSize(400, 400);
// expandableContent.setMaxWidth(Double.MAX_VALUE);
// expandableContent.add(stackTraceLabel, 0, 0);
// expandableContent.add(stackTraceTextArea, 0, 1);
//
// alert.getDialogPane().setExpandableContent(expandableContent);
// // Dirty Linux only fix...
// // Expandable zones cause the dialog not to resize correctly
// if (System.getProperty("os.name").matches(".*[Ll]inux.*")) {
// alert.getDialogPane().setPrefSize(600, 400);
// alert.setResizable(true);
// alert.getDialogPane().setExpanded(true);
// }
//
// alert.showAndWait();
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/exception/ProcessInterruptedException.java
// public class ProcessInterruptedException extends Exception {
// /**
// * Constructor usually used when the interruption was caused by a user action
// *
// * @param message the message explaining the interruption
// */
// public ProcessInterruptedException(String message) {
// super(message);
// }
//
// /**
// * Contructor used when the interruption is caused by a previous exception
// *
// * @param message the message explaining the interruption
// * @param cause the cause of the interruption
// */
// public ProcessInterruptedException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/util/SecurityConstants.java
// public static final String PROPERTIES_LOG4J = "log4j.properties";
// Path: admin-offline/src/main/java/ch/ge/ve/offlineadmin/OfflineAdminApp.java
import org.apache.log4j.PropertyConfigurator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Security;
import java.util.ResourceBundle;
import static ch.ge.ve.offlineadmin.util.SecurityConstants.PROPERTIES_LOG4J;
import ch.ge.ve.offlineadmin.controller.InterruptibleProcessController;
import ch.ge.ve.offlineadmin.exception.ProcessInterruptedException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
InterruptibleProcessController interruptibleProcessController = new InterruptibleProcessController() {
@Override
protected ResourceBundle getResourceBundle() {
return resourceBundle;
}
};
Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
final ProcessInterruptedException processInterruptedException = new ProcessInterruptedException(resourceBundle.getString("exception_alert.generic-message"), e);
interruptibleProcessController.handleInterruption(processInterruptedException);
});
}
private BorderPane initRootLayout(ResourceBundle bundle) throws IOException {
FXMLLoader loader = new FXMLLoader();
URL resource = this.getClass().getResource("/ch/ge/ve/offlineadmin/view/RootLayout.fxml");
loader.setLocation(resource);
loader.setResources(bundle);
return loader.load();
}
private URL getStyleSheet() {
return this.getClass().getResource("/ch/ge/ve/offlineadmin/styles/offlineadmin.css");
}
private static ResourceBundle getBundle() {
return ResourceBundle.getBundle("ch.ge.ve.offlineadmin.bundles.offlineadmin-messages");
}
private InputStream getLog4jProperties() throws IOException { | return OfflineAdminApp.class.getClassLoader().getResourceAsStream(PROPERTIES_LOG4J); |
tools4j/spockito | spockito-table/src/main/java/org/tools4j/spockito/table/SpockitoTableConverter.java | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/Converters.java
// public static class CollectionConverter implements ValueConverter {
// private final ValueConverter elementConverter;
// public CollectionConverter(final ValueConverter elementConverter) {
// this.elementConverter = requireNonNull(elementConverter);
// }
//
// @Override
// public <T> T convert(final Class<T> type, final Type genericType, final String value) {
// if (!Collection.class.isAssignableFrom(type)) {
// throw new IllegalArgumentException("Type must be a collection: " + type.getName());
// }
// final ActualType elementType = actualTypeForTypeParam(genericType, 0, 1);
// final List<?> list = toList(elementType, value);
// return convert(type, genericType, list, value);
// }
//
// public <T> T convert(final Class<T> type, final Type genericType, final List<?> list) {
// return convert(type, genericType, list, list);
// }
//
// public <T> T convert(final Class<T> type, final Type genericType, final List<?> list, final Object value) {
// if (type.isInstance(list)) {
// return type.cast(list);
// }
// if (type.isAssignableFrom(ArrayList.class)) {
// return type.cast(new ArrayList<>(list));
// }
// if (type.isAssignableFrom(Vector.class)) {
// return type.cast(new Vector<>(list));
// }
// if (type.isAssignableFrom(LinkedList.class)) {
// return type.cast(new LinkedList<>(list));
// }
// if (type.isAssignableFrom(ArrayDeque.class)) {
// return type.cast(new ArrayDeque<>(list));
// }
// if (type.isAssignableFrom(LinkedHashSet.class)) {
// return type.cast(new LinkedHashSet<>(list));
// }
// if (type.isAssignableFrom(TreeSet.class)) {
// return type.cast(new TreeSet<>(list));
// }
// if (type.isAssignableFrom(HashSet.class)) {
// return type.cast(new HashSet<>(list));
// }
// if (type.isAssignableFrom(EnumSet.class)) {
// final ActualType elementType = actualTypeForTypeParam(genericType, 0, 1);
// final EnumSet<?> enumSet = enumSet(elementType.rawType().asSubclass(Enum.class), list);
// return type.cast(enumSet);
// }
// if (type.isAssignableFrom(ConcurrentLinkedQueue.class)) {
// return type.cast(new ConcurrentLinkedQueue<>(list));
// }
// if (type.isAssignableFrom(ConcurrentLinkedDeque.class)) {
// return type.cast(new ConcurrentLinkedDeque<>(list));
// }
// if (type.isAssignableFrom(ConcurrentSkipListSet.class)) {
// return type.cast(new ConcurrentSkipListSet<>(list));
// }
// //unsupported collection type
// throw new IllegalArgumentException("Cannot convert value to " + type.getName() + ": " + value);
// }
//
// private List<Object> toList(final ActualType elementType, final String value) {
// final String plainValue = Strings.removeStartAndEndChars(value, '[', ']');
// if (plainValue.trim().isEmpty()) {
// return Collections.emptyList();
// }
// final String[] parts = parseListValues(plainValue);
// final List<Object> list = new ArrayList<>(parts.length);
// for (int i = 0; i < parts.length; i++) {
// list.add(elementConverter.convert(elementType.rawType(), elementType.genericType(), parts[i].trim()));
// }
// return list;
// }
//
// private static <E extends Enum<E>> EnumSet<E> enumSet(final Class<E> enumType, final List<?> list) {
// final EnumSet<E> set = EnumSet.noneOf(enumType);
// list.forEach(v -> set.add(enumType.cast(v)));
// return set;
// }
// }
| import java.util.Collection;
import java.util.List;
import static java.util.Objects.requireNonNull;
import static org.tools4j.spockito.table.GenericTypes.actualTypeForTypeParam;
import static org.tools4j.spockito.table.GenericTypes.genericComponentType;
import org.tools4j.spockito.table.Converters.CollectionConverter;
import org.tools4j.spockito.table.GenericTypes.ActualType;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type; | this.valueConverter = requireNonNull(valueConverter);
}
public static TableConverter create(final Parameter parameter, final ValueConverter valueConverter) {
return new SpockitoTableConverter(parameter.getType(), parameter.getParameterizedType(), valueConverter);
}
public static TableConverter create(final Field field, final ValueConverter valueConverter) {
return new SpockitoTableConverter(field.getType(), field.getGenericType(), valueConverter);
}
@Override
public Object convert(final Table table) {
requireNonNull(table);
if (targetClass.isInstance(table)) {
return table;
}
final ActualType rowType;
if (Collection.class.isAssignableFrom(targetClass)) {
rowType = actualTypeForTypeParam(targetType, 0, 1);
} else if (targetClass.isArray()) {
rowType = genericComponentType(targetClass, targetType);
} else {
throw new IllegalArgumentException("No known conversion from Table to " + targetType);
}
final List<?> rows = table.toList(rowType.rawType(), rowType.genericType(), valueConverter);
if (List.class.isAssignableFrom(targetClass)) {
return targetClass.cast(rows);
}
if (Collection.class.isAssignableFrom(targetClass)) { | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/Converters.java
// public static class CollectionConverter implements ValueConverter {
// private final ValueConverter elementConverter;
// public CollectionConverter(final ValueConverter elementConverter) {
// this.elementConverter = requireNonNull(elementConverter);
// }
//
// @Override
// public <T> T convert(final Class<T> type, final Type genericType, final String value) {
// if (!Collection.class.isAssignableFrom(type)) {
// throw new IllegalArgumentException("Type must be a collection: " + type.getName());
// }
// final ActualType elementType = actualTypeForTypeParam(genericType, 0, 1);
// final List<?> list = toList(elementType, value);
// return convert(type, genericType, list, value);
// }
//
// public <T> T convert(final Class<T> type, final Type genericType, final List<?> list) {
// return convert(type, genericType, list, list);
// }
//
// public <T> T convert(final Class<T> type, final Type genericType, final List<?> list, final Object value) {
// if (type.isInstance(list)) {
// return type.cast(list);
// }
// if (type.isAssignableFrom(ArrayList.class)) {
// return type.cast(new ArrayList<>(list));
// }
// if (type.isAssignableFrom(Vector.class)) {
// return type.cast(new Vector<>(list));
// }
// if (type.isAssignableFrom(LinkedList.class)) {
// return type.cast(new LinkedList<>(list));
// }
// if (type.isAssignableFrom(ArrayDeque.class)) {
// return type.cast(new ArrayDeque<>(list));
// }
// if (type.isAssignableFrom(LinkedHashSet.class)) {
// return type.cast(new LinkedHashSet<>(list));
// }
// if (type.isAssignableFrom(TreeSet.class)) {
// return type.cast(new TreeSet<>(list));
// }
// if (type.isAssignableFrom(HashSet.class)) {
// return type.cast(new HashSet<>(list));
// }
// if (type.isAssignableFrom(EnumSet.class)) {
// final ActualType elementType = actualTypeForTypeParam(genericType, 0, 1);
// final EnumSet<?> enumSet = enumSet(elementType.rawType().asSubclass(Enum.class), list);
// return type.cast(enumSet);
// }
// if (type.isAssignableFrom(ConcurrentLinkedQueue.class)) {
// return type.cast(new ConcurrentLinkedQueue<>(list));
// }
// if (type.isAssignableFrom(ConcurrentLinkedDeque.class)) {
// return type.cast(new ConcurrentLinkedDeque<>(list));
// }
// if (type.isAssignableFrom(ConcurrentSkipListSet.class)) {
// return type.cast(new ConcurrentSkipListSet<>(list));
// }
// //unsupported collection type
// throw new IllegalArgumentException("Cannot convert value to " + type.getName() + ": " + value);
// }
//
// private List<Object> toList(final ActualType elementType, final String value) {
// final String plainValue = Strings.removeStartAndEndChars(value, '[', ']');
// if (plainValue.trim().isEmpty()) {
// return Collections.emptyList();
// }
// final String[] parts = parseListValues(plainValue);
// final List<Object> list = new ArrayList<>(parts.length);
// for (int i = 0; i < parts.length; i++) {
// list.add(elementConverter.convert(elementType.rawType(), elementType.genericType(), parts[i].trim()));
// }
// return list;
// }
//
// private static <E extends Enum<E>> EnumSet<E> enumSet(final Class<E> enumType, final List<?> list) {
// final EnumSet<E> set = EnumSet.noneOf(enumType);
// list.forEach(v -> set.add(enumType.cast(v)));
// return set;
// }
// }
// Path: spockito-table/src/main/java/org/tools4j/spockito/table/SpockitoTableConverter.java
import java.util.Collection;
import java.util.List;
import static java.util.Objects.requireNonNull;
import static org.tools4j.spockito.table.GenericTypes.actualTypeForTypeParam;
import static org.tools4j.spockito.table.GenericTypes.genericComponentType;
import org.tools4j.spockito.table.Converters.CollectionConverter;
import org.tools4j.spockito.table.GenericTypes.ActualType;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
this.valueConverter = requireNonNull(valueConverter);
}
public static TableConverter create(final Parameter parameter, final ValueConverter valueConverter) {
return new SpockitoTableConverter(parameter.getType(), parameter.getParameterizedType(), valueConverter);
}
public static TableConverter create(final Field field, final ValueConverter valueConverter) {
return new SpockitoTableConverter(field.getType(), field.getGenericType(), valueConverter);
}
@Override
public Object convert(final Table table) {
requireNonNull(table);
if (targetClass.isInstance(table)) {
return table;
}
final ActualType rowType;
if (Collection.class.isAssignableFrom(targetClass)) {
rowType = actualTypeForTypeParam(targetType, 0, 1);
} else if (targetClass.isArray()) {
rowType = genericComponentType(targetClass, targetType);
} else {
throw new IllegalArgumentException("No known conversion from Table to " + targetType);
}
final List<?> rows = table.toList(rowType.rawType(), rowType.genericType(), valueConverter);
if (List.class.isAssignableFrom(targetClass)) {
return targetClass.cast(rows);
}
if (Collection.class.isAssignableFrom(targetClass)) { | return new CollectionConverter(valueConverter).convert(targetClass, targetType, rows); |
tools4j/spockito | spockito-junit5/src/test/java/org/tools4j/spockito/jupiter/SpockitoExtensionTest.java | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/TableRow.java
// public interface TableRow extends Iterable<String> {
//
// Table getTable();
// int getColumnCount();
// int getRowIndex();
// boolean isSeparatorRow();
//
// String get(int index);
// String get(String name);
// int indexOf(String value);
//
// String[] toArray();
// List<String> toList();
// Map<String, String> toMap();
// <T> T to(Class<T> type);
// <T> T to(Class<T> type, ValueConverter valueConverter);
// <T> T to(Class<T> type, Type genericType, ValueConverter valueConverter);
//
// @Override
// Iterator<String> iterator();
// default Stream<String> stream() {
// return StreamSupport.stream(spliterator(), false);
// }
//
// }
| import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.tools4j.spockito.table.TableRow;
import static org.junit.jupiter.api.Assertions.assertEquals; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2021 tools4j.org (Marco Terzer)
*
* 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.tools4j.spockito.jupiter;
@ExtendWith(SpockitoExtension.class)
@Disabled
public class SpockitoExtensionTest {
public static class DataRow {
Operation operation;
char sign;
int operand1;
int operand2;
int result;
int neutralOperand;
}
@TableSource({
"| Operation | Sign | Operand1 | Operand2 | Result | NeutralOperand |",
"|-----------|------|----------|----------|--------|----------------|",
"| Add | + | 4 | 7 | 11 | 0 |",
"| Subtract | - | 111 | 12 | 99 | 0 |",
"| Multiply | * | 24 | 5 | 120 | 1 |",
"| Divide | / | 24 | 3 | 8 | 1 |"
}) | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/TableRow.java
// public interface TableRow extends Iterable<String> {
//
// Table getTable();
// int getColumnCount();
// int getRowIndex();
// boolean isSeparatorRow();
//
// String get(int index);
// String get(String name);
// int indexOf(String value);
//
// String[] toArray();
// List<String> toList();
// Map<String, String> toMap();
// <T> T to(Class<T> type);
// <T> T to(Class<T> type, ValueConverter valueConverter);
// <T> T to(Class<T> type, Type genericType, ValueConverter valueConverter);
//
// @Override
// Iterator<String> iterator();
// default Stream<String> stream() {
// return StreamSupport.stream(spliterator(), false);
// }
//
// }
// Path: spockito-junit5/src/test/java/org/tools4j/spockito/jupiter/SpockitoExtensionTest.java
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.tools4j.spockito.table.TableRow;
import static org.junit.jupiter.api.Assertions.assertEquals;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2021 tools4j.org (Marco Terzer)
*
* 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.tools4j.spockito.jupiter;
@ExtendWith(SpockitoExtension.class)
@Disabled
public class SpockitoExtensionTest {
public static class DataRow {
Operation operation;
char sign;
int operand1;
int operand2;
int result;
int neutralOperand;
}
@TableSource({
"| Operation | Sign | Operand1 | Operand2 | Result | NeutralOperand |",
"|-----------|------|----------|----------|--------|----------------|",
"| Add | + | 4 | 7 | 11 | 0 |",
"| Subtract | - | 111 | 12 | 99 | 0 |",
"| Multiply | * | 24 | 5 | 120 | 1 |",
"| Divide | / | 24 | 3 | 8 | 1 |"
}) | private TableRow[] testData; |
tools4j/spockito | spockito-table/src/main/java/org/tools4j/spockito/table/SpockitoTableRowConverter.java | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/InjectionContext.java
// enum Phase {
// /**
// * Initialisation phase if injection is triggered at initialisation time, for instance when using the Junit-5
// * {@code SpockitoExtension}, when using {@link SpockitoData} or when directly invoking
// * {@link SpockitoAnnotations#initData(Object)}.
// */
// INIT,
// /**
// * Test phase if injection is triggered via a test framework such as junit when invoking the test.
// */
// TEST
// }
| import static java.util.Objects.requireNonNull;
import static org.tools4j.spockito.table.SpockitoAnnotations.annotationDirectOrMeta;
import org.tools4j.spockito.table.InjectionContext.Phase;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type; | try {
column = tableRow.getTable().getColumnIndexByName(name);
} catch (final Exception e) {
throw new IllegalArgumentException("Could not access table column " + name, e);
}
return valueByIndex(tableRow, column);
}
private String valueByIndex(final TableRow tableRow, final int index) {
try {
return tableRow.get(index);
} catch (final Exception e) {
throw new IllegalArgumentException("Could not access table value for column index " + index, e);
}
}
private Object convert(final String value, final Object column) {
try {
return valueConverter.convert(targetClass, targetType, value);
} catch (final Exception e) {
throw new IllegalArgumentException("Conversion to " + targetClass + " failed for column '" + column +
"': " + value, e);
}
}
private static Object dataForAnnotatedElement(final AnnotatedElement element) {
requireNonNull(element);
final Data data = annotationDirectOrMeta(element, Data.class);
try {
final DataProvider dataProvider = data.value().newInstance(); | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/InjectionContext.java
// enum Phase {
// /**
// * Initialisation phase if injection is triggered at initialisation time, for instance when using the Junit-5
// * {@code SpockitoExtension}, when using {@link SpockitoData} or when directly invoking
// * {@link SpockitoAnnotations#initData(Object)}.
// */
// INIT,
// /**
// * Test phase if injection is triggered via a test framework such as junit when invoking the test.
// */
// TEST
// }
// Path: spockito-table/src/main/java/org/tools4j/spockito/table/SpockitoTableRowConverter.java
import static java.util.Objects.requireNonNull;
import static org.tools4j.spockito.table.SpockitoAnnotations.annotationDirectOrMeta;
import org.tools4j.spockito.table.InjectionContext.Phase;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
try {
column = tableRow.getTable().getColumnIndexByName(name);
} catch (final Exception e) {
throw new IllegalArgumentException("Could not access table column " + name, e);
}
return valueByIndex(tableRow, column);
}
private String valueByIndex(final TableRow tableRow, final int index) {
try {
return tableRow.get(index);
} catch (final Exception e) {
throw new IllegalArgumentException("Could not access table value for column index " + index, e);
}
}
private Object convert(final String value, final Object column) {
try {
return valueConverter.convert(targetClass, targetType, value);
} catch (final Exception e) {
throw new IllegalArgumentException("Conversion to " + targetClass + " failed for column '" + column +
"': " + value, e);
}
}
private static Object dataForAnnotatedElement(final AnnotatedElement element) {
requireNonNull(element);
final Data data = annotationDirectOrMeta(element, Data.class);
try {
final DataProvider dataProvider = data.value().newInstance(); | final InjectionContext context = InjectionContext.create(Phase.INIT, element); |
tools4j/spockito | spockito-table/src/main/java/org/tools4j/spockito/table/SpockitoAnnotations.java | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/InjectionContext.java
// enum Phase {
// /**
// * Initialisation phase if injection is triggered at initialisation time, for instance when using the Junit-5
// * {@code SpockitoExtension}, when using {@link SpockitoData} or when directly invoking
// * {@link SpockitoAnnotations#initData(Object)}.
// */
// INIT,
// /**
// * Test phase if injection is triggered via a test framework such as junit when invoking the test.
// */
// TEST
// }
| import java.util.HashSet;
import java.util.Set;
import org.tools4j.spockito.table.InjectionContext.Phase;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays; | private static void initDataFields(final Object instance, final Class<?> clazz) {
if (clazz == null || clazz == Object.class) {
return;
}
for (final Field field : clazz.getDeclaredFields()) {
final Data data = annotationDirectOrMeta(field, Data.class);
if (data != null) {
initDataField(instance, field, data);
}
}
initDataFields(instance, clazz.getSuperclass());
}
private static void invokeDataMethods(final Object instance, final Class<?> clazz) {
if (clazz == null || clazz == Object.class) {
return;
}
for (final Method method : clazz.getDeclaredMethods()) {
final Data data = annotationDirectOrMeta(method, Data.class);
if (data != null) {
invokeDataMethod(instance, method, data);
}
}
invokeDataMethods(instance, clazz.getSuperclass());
}
private static void initDataField(final Object instance, final Field field, final Data data) {
final boolean accessible = field.isAccessible();
try {
final DataProvider dataProvider = data.value().newInstance(); | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/InjectionContext.java
// enum Phase {
// /**
// * Initialisation phase if injection is triggered at initialisation time, for instance when using the Junit-5
// * {@code SpockitoExtension}, when using {@link SpockitoData} or when directly invoking
// * {@link SpockitoAnnotations#initData(Object)}.
// */
// INIT,
// /**
// * Test phase if injection is triggered via a test framework such as junit when invoking the test.
// */
// TEST
// }
// Path: spockito-table/src/main/java/org/tools4j/spockito/table/SpockitoAnnotations.java
import java.util.HashSet;
import java.util.Set;
import org.tools4j.spockito.table.InjectionContext.Phase;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
private static void initDataFields(final Object instance, final Class<?> clazz) {
if (clazz == null || clazz == Object.class) {
return;
}
for (final Field field : clazz.getDeclaredFields()) {
final Data data = annotationDirectOrMeta(field, Data.class);
if (data != null) {
initDataField(instance, field, data);
}
}
initDataFields(instance, clazz.getSuperclass());
}
private static void invokeDataMethods(final Object instance, final Class<?> clazz) {
if (clazz == null || clazz == Object.class) {
return;
}
for (final Method method : clazz.getDeclaredMethods()) {
final Data data = annotationDirectOrMeta(method, Data.class);
if (data != null) {
invokeDataMethod(instance, method, data);
}
}
invokeDataMethods(instance, clazz.getSuperclass());
}
private static void initDataField(final Object instance, final Field field, final Data data) {
final boolean accessible = field.isAccessible();
try {
final DataProvider dataProvider = data.value().newInstance(); | final InjectionContext context = InjectionContext.create(Phase.INIT, field); |
tools4j/spockito | spockito-junit4/src/test/java/org/tools4j/spockito/CustomConverterTest.java | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/ValueConverter.java
// public interface ValueConverter {
// /**
// * Converts the given string value into the target type specified by raw and generic type.
// *
// * @param type the target type in raw form, for instance {@code int.class}, {@code List.class} etc.
// * @param genericType the generic target type, same as type for non-generic types; generic type examples are
// * {@code List<String>}, {@code Map<String, Integer>} etc.
// * @param value the value to convert, may be null
// * @param <T> the target type parameter
// * @return the converted value
// */
// <T> T convert(Class<T> type, Type genericType, String value);
//
// /**
// * Converts the given string value into the target type. Use this method for non-generic types, and
// * {@link #convert(Class, Type, String)} for generic types.
// *
// * @param type the target type, a non-generic type such as {@code String.class}
// * @param value the value to convert, may be null
// * @param <T> the target type parameter
// * @return the converted value
// */
// default <T> T convert(Class<T> type, String value) {
// return convert(type, type, value);
// }
//
// static ValueConverter create(final Class<? extends ValueConverter> type) {
// if (SpockitoValueConverter.class.equals(type)) {
// return SpockitoValueConverter.DEFAULT_INSTANCE;
// }
// try {
// return type.newInstance();
// } catch (final Exception e) {
// throw new SpockitoException("Could not create value converter instance of type " + type.getName(), e);
// }
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.tools4j.spockito.table.ValueConverter;
import java.lang.reflect.Type; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2021 tools4j.org (Marco Terzer)
*
* 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.tools4j.spockito;
@RunWith(Spockito.class)
@Spockito.UseValueConverter(CustomConverterTest.MyIntegerConverter.class)
public class CustomConverterTest {
static class MyInteger {
int intValue;
static MyInteger parse(final String s) {
final int intValue = Integer.parseInt(s.trim());
final MyInteger myInteger = new MyInteger();
myInteger.intValue = intValue;
return myInteger;
}
}
static class Point {
int x;
int y;
static Point parse(final String s) {
final String trimmed = s.trim();
final int comma = trimmed.indexOf(',');
if (comma >= 0 && trimmed.startsWith("(") && trimmed.endsWith(")")) {
final int x = Integer.parseInt(trimmed.substring(1, comma));
final int y = Integer.parseInt(trimmed.substring(comma + 1, trimmed.length() - 1));
final Point p = new Point();
p.x = x;
p.y = y;
return p;
}
throw new IllegalArgumentException("Cannot convert string intValue to Point: " + s);
}
}
| // Path: spockito-table/src/main/java/org/tools4j/spockito/table/ValueConverter.java
// public interface ValueConverter {
// /**
// * Converts the given string value into the target type specified by raw and generic type.
// *
// * @param type the target type in raw form, for instance {@code int.class}, {@code List.class} etc.
// * @param genericType the generic target type, same as type for non-generic types; generic type examples are
// * {@code List<String>}, {@code Map<String, Integer>} etc.
// * @param value the value to convert, may be null
// * @param <T> the target type parameter
// * @return the converted value
// */
// <T> T convert(Class<T> type, Type genericType, String value);
//
// /**
// * Converts the given string value into the target type. Use this method for non-generic types, and
// * {@link #convert(Class, Type, String)} for generic types.
// *
// * @param type the target type, a non-generic type such as {@code String.class}
// * @param value the value to convert, may be null
// * @param <T> the target type parameter
// * @return the converted value
// */
// default <T> T convert(Class<T> type, String value) {
// return convert(type, type, value);
// }
//
// static ValueConverter create(final Class<? extends ValueConverter> type) {
// if (SpockitoValueConverter.class.equals(type)) {
// return SpockitoValueConverter.DEFAULT_INSTANCE;
// }
// try {
// return type.newInstance();
// } catch (final Exception e) {
// throw new SpockitoException("Could not create value converter instance of type " + type.getName(), e);
// }
// }
// }
// Path: spockito-junit4/src/test/java/org/tools4j/spockito/CustomConverterTest.java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.tools4j.spockito.table.ValueConverter;
import java.lang.reflect.Type;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2021 tools4j.org (Marco Terzer)
*
* 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.tools4j.spockito;
@RunWith(Spockito.class)
@Spockito.UseValueConverter(CustomConverterTest.MyIntegerConverter.class)
public class CustomConverterTest {
static class MyInteger {
int intValue;
static MyInteger parse(final String s) {
final int intValue = Integer.parseInt(s.trim());
final MyInteger myInteger = new MyInteger();
myInteger.intValue = intValue;
return myInteger;
}
}
static class Point {
int x;
int y;
static Point parse(final String s) {
final String trimmed = s.trim();
final int comma = trimmed.indexOf(',');
if (comma >= 0 && trimmed.startsWith("(") && trimmed.endsWith(")")) {
final int x = Integer.parseInt(trimmed.substring(1, comma));
final int y = Integer.parseInt(trimmed.substring(comma + 1, trimmed.length() - 1));
final Point p = new Point();
p.x = x;
p.y = y;
return p;
}
throw new IllegalArgumentException("Cannot convert string intValue to Point: " + s);
}
}
| static class MyIntegerConverter implements ValueConverter { |
tools4j/spockito | spockito-junit4/src/main/java/org/tools4j/spockito/UnrolledTestMethod.java | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/TableRow.java
// public interface TableRow extends Iterable<String> {
//
// Table getTable();
// int getColumnCount();
// int getRowIndex();
// boolean isSeparatorRow();
//
// String get(int index);
// String get(String name);
// int indexOf(String value);
//
// String[] toArray();
// List<String> toList();
// Map<String, String> toMap();
// <T> T to(Class<T> type);
// <T> T to(Class<T> type, ValueConverter valueConverter);
// <T> T to(Class<T> type, Type genericType, ValueConverter valueConverter);
//
// @Override
// Iterator<String> iterator();
// default Stream<String> stream() {
// return StreamSupport.stream(spliterator(), false);
// }
//
// }
//
// Path: spockito-table/src/main/java/org/tools4j/spockito/table/ValueConverter.java
// public interface ValueConverter {
// /**
// * Converts the given string value into the target type specified by raw and generic type.
// *
// * @param type the target type in raw form, for instance {@code int.class}, {@code List.class} etc.
// * @param genericType the generic target type, same as type for non-generic types; generic type examples are
// * {@code List<String>}, {@code Map<String, Integer>} etc.
// * @param value the value to convert, may be null
// * @param <T> the target type parameter
// * @return the converted value
// */
// <T> T convert(Class<T> type, Type genericType, String value);
//
// /**
// * Converts the given string value into the target type. Use this method for non-generic types, and
// * {@link #convert(Class, Type, String)} for generic types.
// *
// * @param type the target type, a non-generic type such as {@code String.class}
// * @param value the value to convert, may be null
// * @param <T> the target type parameter
// * @return the converted value
// */
// default <T> T convert(Class<T> type, String value) {
// return convert(type, type, value);
// }
//
// static ValueConverter create(final Class<? extends ValueConverter> type) {
// if (SpockitoValueConverter.class.equals(type)) {
// return SpockitoValueConverter.DEFAULT_INSTANCE;
// }
// try {
// return type.newInstance();
// } catch (final Exception e) {
// throw new SpockitoException("Could not create value converter instance of type " + type.getName(), e);
// }
// }
// }
| import org.junit.runners.model.FrameworkMethod;
import org.tools4j.spockito.table.TableRow;
import org.tools4j.spockito.table.ValueConverter;
import java.lang.reflect.Method;
import static java.util.Objects.requireNonNull; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2021 tools4j.org (Marco Terzer)
*
* 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.tools4j.spockito;
/**
* Extension of framework method representing a test method with a data row.
*/
public class UnrolledTestMethod extends FrameworkMethod {
private final TableRow tableRow; | // Path: spockito-table/src/main/java/org/tools4j/spockito/table/TableRow.java
// public interface TableRow extends Iterable<String> {
//
// Table getTable();
// int getColumnCount();
// int getRowIndex();
// boolean isSeparatorRow();
//
// String get(int index);
// String get(String name);
// int indexOf(String value);
//
// String[] toArray();
// List<String> toList();
// Map<String, String> toMap();
// <T> T to(Class<T> type);
// <T> T to(Class<T> type, ValueConverter valueConverter);
// <T> T to(Class<T> type, Type genericType, ValueConverter valueConverter);
//
// @Override
// Iterator<String> iterator();
// default Stream<String> stream() {
// return StreamSupport.stream(spliterator(), false);
// }
//
// }
//
// Path: spockito-table/src/main/java/org/tools4j/spockito/table/ValueConverter.java
// public interface ValueConverter {
// /**
// * Converts the given string value into the target type specified by raw and generic type.
// *
// * @param type the target type in raw form, for instance {@code int.class}, {@code List.class} etc.
// * @param genericType the generic target type, same as type for non-generic types; generic type examples are
// * {@code List<String>}, {@code Map<String, Integer>} etc.
// * @param value the value to convert, may be null
// * @param <T> the target type parameter
// * @return the converted value
// */
// <T> T convert(Class<T> type, Type genericType, String value);
//
// /**
// * Converts the given string value into the target type. Use this method for non-generic types, and
// * {@link #convert(Class, Type, String)} for generic types.
// *
// * @param type the target type, a non-generic type such as {@code String.class}
// * @param value the value to convert, may be null
// * @param <T> the target type parameter
// * @return the converted value
// */
// default <T> T convert(Class<T> type, String value) {
// return convert(type, type, value);
// }
//
// static ValueConverter create(final Class<? extends ValueConverter> type) {
// if (SpockitoValueConverter.class.equals(type)) {
// return SpockitoValueConverter.DEFAULT_INSTANCE;
// }
// try {
// return type.newInstance();
// } catch (final Exception e) {
// throw new SpockitoException("Could not create value converter instance of type " + type.getName(), e);
// }
// }
// }
// Path: spockito-junit4/src/main/java/org/tools4j/spockito/UnrolledTestMethod.java
import org.junit.runners.model.FrameworkMethod;
import org.tools4j.spockito.table.TableRow;
import org.tools4j.spockito.table.ValueConverter;
import java.lang.reflect.Method;
import static java.util.Objects.requireNonNull;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2021 tools4j.org (Marco Terzer)
*
* 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.tools4j.spockito;
/**
* Extension of framework method representing a test method with a data row.
*/
public class UnrolledTestMethod extends FrameworkMethod {
private final TableRow tableRow; | private final ValueConverter valueConverter; |
JosuaKrause/BusVisPublic | src/main/java/infovis/draw/LineRealizer.java | // Path: src/main/java/infovis/data/BusLine.java
// public final class BusLine implements Comparable<BusLine> {
//
// /** Bus line used for walked sections of a route. */
// public static final BusLine WALK = new BusLine("Walk", null, Color.BLACK);
//
// /** Bus line name. */
// private final String name;
//
// /** Long bus line name. */
// private final String longName;
//
// /** Bus color. */
// private final Color color;
//
// /** The hidden sorting name. */
// private final String hiddenSortingName;
//
// /**
// * Constructor taking the name and the color.
// *
// * @param name Bus line name,
// * @param longName Long bus line name, may be <code>null</code>.
// * @param color Bus line color.
// */
// BusLine(final String name, final String longName, final Color color) {
// this.name = Objects.requireNonNull(name).intern();
// this.longName = Objects.nonNull(longName, this.name);
// this.color = Objects.requireNonNull(color);
// final String tmp = "0000000000" + name;
// final int l = tmp.length();
// hiddenSortingName = tmp.substring(l - 10, l);
// }
//
// /**
// * Getter.
// *
// * @return bus line name
// */
// public String getName() {
// return name;
// }
//
// /**
// * Getter.
// *
// * @return The full bus line name.
// */
// public String getFullName() {
// return longName;
// }
//
// /**
// * Getter.
// *
// * @return bus line color
// */
// public Color getColor() {
// return color;
// }
//
// @Override
// public String toString() {
// return String.format("%s[%s, %08X]", getClass().getSimpleName(), name, color.getRGB());
// }
//
// /**
// * Checks for equality with other bus lines.
// *
// * @param line The other line.
// * @return If both are equal and non-null.
// */
// public boolean equals(final BusLine line) {
// return line != null && (this == line || name.equals(line.name));
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof BusLine && name.equals(((BusLine) obj).name);
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public int compareTo(final BusLine o) {
// return -hiddenSortingName.compareTo(o.hiddenSortingName);
// }
//
// }
| import infovis.data.BusLine;
import infovis.util.VecUtil;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D; | package infovis.draw;
/**
* Realizes the actual painting of bus lines.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public interface LineRealizer {
/**
* The shape of the line between bus stations.
*
* @param line The actual line (assumed to contain no NaN values).
* @param number The currently drawn bus line. If the number is negative the
* overall shape (click area and bounding box computation) should be
* returned.
* @param maxNumber The number of bus lines that will be drawn.
* @return The shape of the bus line.
*/
Shape createLineShape(Line2D line, int number, int maxNumber);
/**
* Draws lines.
*
* @param g The graphics context.
* @param line The line coordinates (assumed to contain no NaN values).
* @param unused The unused bus lines.
* @param used The used bus lines.
*/ | // Path: src/main/java/infovis/data/BusLine.java
// public final class BusLine implements Comparable<BusLine> {
//
// /** Bus line used for walked sections of a route. */
// public static final BusLine WALK = new BusLine("Walk", null, Color.BLACK);
//
// /** Bus line name. */
// private final String name;
//
// /** Long bus line name. */
// private final String longName;
//
// /** Bus color. */
// private final Color color;
//
// /** The hidden sorting name. */
// private final String hiddenSortingName;
//
// /**
// * Constructor taking the name and the color.
// *
// * @param name Bus line name,
// * @param longName Long bus line name, may be <code>null</code>.
// * @param color Bus line color.
// */
// BusLine(final String name, final String longName, final Color color) {
// this.name = Objects.requireNonNull(name).intern();
// this.longName = Objects.nonNull(longName, this.name);
// this.color = Objects.requireNonNull(color);
// final String tmp = "0000000000" + name;
// final int l = tmp.length();
// hiddenSortingName = tmp.substring(l - 10, l);
// }
//
// /**
// * Getter.
// *
// * @return bus line name
// */
// public String getName() {
// return name;
// }
//
// /**
// * Getter.
// *
// * @return The full bus line name.
// */
// public String getFullName() {
// return longName;
// }
//
// /**
// * Getter.
// *
// * @return bus line color
// */
// public Color getColor() {
// return color;
// }
//
// @Override
// public String toString() {
// return String.format("%s[%s, %08X]", getClass().getSimpleName(), name, color.getRGB());
// }
//
// /**
// * Checks for equality with other bus lines.
// *
// * @param line The other line.
// * @return If both are equal and non-null.
// */
// public boolean equals(final BusLine line) {
// return line != null && (this == line || name.equals(line.name));
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof BusLine && name.equals(((BusLine) obj).name);
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public int compareTo(final BusLine o) {
// return -hiddenSortingName.compareTo(o.hiddenSortingName);
// }
//
// }
// Path: src/main/java/infovis/draw/LineRealizer.java
import infovis.data.BusLine;
import infovis.util.VecUtil;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
package infovis.draw;
/**
* Realizes the actual painting of bus lines.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public interface LineRealizer {
/**
* The shape of the line between bus stations.
*
* @param line The actual line (assumed to contain no NaN values).
* @param number The currently drawn bus line. If the number is negative the
* overall shape (click area and bounding box computation) should be
* returned.
* @param maxNumber The number of bus lines that will be drawn.
* @return The shape of the bus line.
*/
Shape createLineShape(Line2D line, int number, int maxNumber);
/**
* Draws lines.
*
* @param g The graphics context.
* @param line The line coordinates (assumed to contain no NaN values).
* @param unused The unused bus lines.
* @param used The used bus lines.
*/ | void drawLines(Graphics2D g, Line2D line, BusLine[] unused, BusLine[] used); |
JosuaKrause/BusVisPublic | src/main/java/infovis/draw/StationRealizer.java | // Path: src/main/java/infovis/data/BusLine.java
// public final class BusLine implements Comparable<BusLine> {
//
// /** Bus line used for walked sections of a route. */
// public static final BusLine WALK = new BusLine("Walk", null, Color.BLACK);
//
// /** Bus line name. */
// private final String name;
//
// /** Long bus line name. */
// private final String longName;
//
// /** Bus color. */
// private final Color color;
//
// /** The hidden sorting name. */
// private final String hiddenSortingName;
//
// /**
// * Constructor taking the name and the color.
// *
// * @param name Bus line name,
// * @param longName Long bus line name, may be <code>null</code>.
// * @param color Bus line color.
// */
// BusLine(final String name, final String longName, final Color color) {
// this.name = Objects.requireNonNull(name).intern();
// this.longName = Objects.nonNull(longName, this.name);
// this.color = Objects.requireNonNull(color);
// final String tmp = "0000000000" + name;
// final int l = tmp.length();
// hiddenSortingName = tmp.substring(l - 10, l);
// }
//
// /**
// * Getter.
// *
// * @return bus line name
// */
// public String getName() {
// return name;
// }
//
// /**
// * Getter.
// *
// * @return The full bus line name.
// */
// public String getFullName() {
// return longName;
// }
//
// /**
// * Getter.
// *
// * @return bus line color
// */
// public Color getColor() {
// return color;
// }
//
// @Override
// public String toString() {
// return String.format("%s[%s, %08X]", getClass().getSimpleName(), name, color.getRGB());
// }
//
// /**
// * Checks for equality with other bus lines.
// *
// * @param line The other line.
// * @return If both are equal and non-null.
// */
// public boolean equals(final BusLine line) {
// return line != null && (this == line || name.equals(line.name));
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof BusLine && name.equals(((BusLine) obj).name);
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public int compareTo(final BusLine o) {
// return -hiddenSortingName.compareTo(o.hiddenSortingName);
// }
//
// }
| import infovis.data.BusLine;
import infovis.util.VecUtil;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D; | package infovis.draw;
/**
* Realizes the actual painting of bus stations.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public interface StationRealizer {
/**
* The shape of the depiction of the bus station. This is also the area that
* can be clicked on.
*
* @param x The x translation.
* @param y The y translation.
* @param r The radius of the station.
* @return The shape of the bus station.
*/
Shape createStationShape(double x, double y, double r);
/**
* Draws the bus station.
*
* @param g The graphics context.
* @param station The station that is drawn.
* @param stroke The stroke that can be used.
* @param referenceNode Whether this node is the reference node.
* @param secondarySelected Whether this node is secondary selected.
*/
void drawStation(Graphics2D g, Shape station, Stroke stroke, boolean referenceNode,
boolean secondarySelected);
/**
* Highlights a selected route.
*
* @param g The graphics context.
* @param liner The method to draw lines.
* @param stations The shapes of the used stations.
* @param lines The used lines.
* @param busLines The used bus lines.
* @param numbers The numbers of the highlighted lines.
* @param maxNumbers The max numbers of the lines.
*/
void drawRoute(Graphics2D g, LineRealizer liner, Shape[] stations, Line2D[] lines, | // Path: src/main/java/infovis/data/BusLine.java
// public final class BusLine implements Comparable<BusLine> {
//
// /** Bus line used for walked sections of a route. */
// public static final BusLine WALK = new BusLine("Walk", null, Color.BLACK);
//
// /** Bus line name. */
// private final String name;
//
// /** Long bus line name. */
// private final String longName;
//
// /** Bus color. */
// private final Color color;
//
// /** The hidden sorting name. */
// private final String hiddenSortingName;
//
// /**
// * Constructor taking the name and the color.
// *
// * @param name Bus line name,
// * @param longName Long bus line name, may be <code>null</code>.
// * @param color Bus line color.
// */
// BusLine(final String name, final String longName, final Color color) {
// this.name = Objects.requireNonNull(name).intern();
// this.longName = Objects.nonNull(longName, this.name);
// this.color = Objects.requireNonNull(color);
// final String tmp = "0000000000" + name;
// final int l = tmp.length();
// hiddenSortingName = tmp.substring(l - 10, l);
// }
//
// /**
// * Getter.
// *
// * @return bus line name
// */
// public String getName() {
// return name;
// }
//
// /**
// * Getter.
// *
// * @return The full bus line name.
// */
// public String getFullName() {
// return longName;
// }
//
// /**
// * Getter.
// *
// * @return bus line color
// */
// public Color getColor() {
// return color;
// }
//
// @Override
// public String toString() {
// return String.format("%s[%s, %08X]", getClass().getSimpleName(), name, color.getRGB());
// }
//
// /**
// * Checks for equality with other bus lines.
// *
// * @param line The other line.
// * @return If both are equal and non-null.
// */
// public boolean equals(final BusLine line) {
// return line != null && (this == line || name.equals(line.name));
// }
//
// @Override
// public boolean equals(final Object obj) {
// return obj instanceof BusLine && name.equals(((BusLine) obj).name);
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public int compareTo(final BusLine o) {
// return -hiddenSortingName.compareTo(o.hiddenSortingName);
// }
//
// }
// Path: src/main/java/infovis/draw/StationRealizer.java
import infovis.data.BusLine;
import infovis.util.VecUtil;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
package infovis.draw;
/**
* Realizes the actual painting of bus stations.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public interface StationRealizer {
/**
* The shape of the depiction of the bus station. This is also the area that
* can be clicked on.
*
* @param x The x translation.
* @param y The y translation.
* @param r The radius of the station.
* @return The shape of the bus station.
*/
Shape createStationShape(double x, double y, double r);
/**
* Draws the bus station.
*
* @param g The graphics context.
* @param station The station that is drawn.
* @param stroke The stroke that can be used.
* @param referenceNode Whether this node is the reference node.
* @param secondarySelected Whether this node is secondary selected.
*/
void drawStation(Graphics2D g, Shape station, Stroke stroke, boolean referenceNode,
boolean secondarySelected);
/**
* Highlights a selected route.
*
* @param g The graphics context.
* @param liner The method to draw lines.
* @param stations The shapes of the used stations.
* @param lines The used lines.
* @param busLines The used bus lines.
* @param numbers The numbers of the highlighted lines.
* @param maxNumbers The max numbers of the lines.
*/
void drawRoute(Graphics2D g, LineRealizer liner, Shape[] stations, Line2D[] lines, | BusLine[] busLines, int[] numbers, int[] maxNumbers); |
JosuaKrause/BusVisPublic | src/main/java/infovis/data/BusLine.java | // Path: src/main/java/infovis/util/Objects.java
// public final class Objects {
//
// /** No instance. */
// private Objects() {
// throw new AssertionError();
// }
//
// /**
// * Requires a non-null argument. This can be used in constructors to enforce
// * non-null arguments.
// *
// * @param <T> The type of the argument.
// * @param obj The argument.
// * @return The argument.
// * @throws IllegalArgumentException When the argument is <code>null</code>.
// */
// public static <T> T requireNonNull(final T obj) {
// if(obj == null) throw new IllegalArgumentException("null argument");
// return obj;
// }
//
// /**
// * Requires a null argument.
// *
// * @param obj The argument.
// * @throws IllegalArgumentException When the argument is <code>null</code>.
// */
// public static void requireNull(final Object obj) {
// if(obj != null) throw new IllegalArgumentException("non-null argument: " + obj);
// }
//
// /**
// * Requires a <code>true</code> statement.
// *
// * @param value The statement that needs to be <code>true</code>.
// * @throws IllegalStateException When the statement is <code>false</code>.
// */
// public static void requireTrue(final boolean value) {
// if(!value) throw new IllegalStateException("expected true");
// }
//
// /**
// * Returns the first argument if it is non-null otherwise the second argument
// * is returned. This is a short-hand for:
// * <code>(obj != null ? obj : or)</code>
// *
// * @param <T> The type of the arguments.
// * @param obj The object.
// * @param or The alternative.
// * @return The first argument if it is non-null or else the second argument.
// */
// public static <T> T nonNull(final T obj, final T or) {
// return obj != null ? obj : or;
// }
//
// }
| import infovis.util.Objects;
import java.awt.Color; | package infovis.data;
/**
* A bus line, having a name and a color.
*
* @author Leo Woerteler
*/
public final class BusLine implements Comparable<BusLine> {
/** Bus line used for walked sections of a route. */
public static final BusLine WALK = new BusLine("Walk", null, Color.BLACK);
/** Bus line name. */
private final String name;
/** Long bus line name. */
private final String longName;
/** Bus color. */
private final Color color;
/** The hidden sorting name. */
private final String hiddenSortingName;
/**
* Constructor taking the name and the color.
*
* @param name Bus line name,
* @param longName Long bus line name, may be <code>null</code>.
* @param color Bus line color.
*/
BusLine(final String name, final String longName, final Color color) { | // Path: src/main/java/infovis/util/Objects.java
// public final class Objects {
//
// /** No instance. */
// private Objects() {
// throw new AssertionError();
// }
//
// /**
// * Requires a non-null argument. This can be used in constructors to enforce
// * non-null arguments.
// *
// * @param <T> The type of the argument.
// * @param obj The argument.
// * @return The argument.
// * @throws IllegalArgumentException When the argument is <code>null</code>.
// */
// public static <T> T requireNonNull(final T obj) {
// if(obj == null) throw new IllegalArgumentException("null argument");
// return obj;
// }
//
// /**
// * Requires a null argument.
// *
// * @param obj The argument.
// * @throws IllegalArgumentException When the argument is <code>null</code>.
// */
// public static void requireNull(final Object obj) {
// if(obj != null) throw new IllegalArgumentException("non-null argument: " + obj);
// }
//
// /**
// * Requires a <code>true</code> statement.
// *
// * @param value The statement that needs to be <code>true</code>.
// * @throws IllegalStateException When the statement is <code>false</code>.
// */
// public static void requireTrue(final boolean value) {
// if(!value) throw new IllegalStateException("expected true");
// }
//
// /**
// * Returns the first argument if it is non-null otherwise the second argument
// * is returned. This is a short-hand for:
// * <code>(obj != null ? obj : or)</code>
// *
// * @param <T> The type of the arguments.
// * @param obj The object.
// * @param or The alternative.
// * @return The first argument if it is non-null or else the second argument.
// */
// public static <T> T nonNull(final T obj, final T or) {
// return obj != null ? obj : or;
// }
//
// }
// Path: src/main/java/infovis/data/BusLine.java
import infovis.util.Objects;
import java.awt.Color;
package infovis.data;
/**
* A bus line, having a name and a color.
*
* @author Leo Woerteler
*/
public final class BusLine implements Comparable<BusLine> {
/** Bus line used for walked sections of a route. */
public static final BusLine WALK = new BusLine("Walk", null, Color.BLACK);
/** Bus line name. */
private final String name;
/** Long bus line name. */
private final String longName;
/** Bus color. */
private final Color color;
/** The hidden sorting name. */
private final String hiddenSortingName;
/**
* Constructor taking the name and the color.
*
* @param name Bus line name,
* @param longName Long bus line name, may be <code>null</code>.
* @param color Bus line color.
*/
BusLine(final String name, final String longName, final Color color) { | this.name = Objects.requireNonNull(name).intern(); |
JosuaKrause/BusVisPublic | src/main/java/infovis/gui/Canvas.java | // Path: src/main/java/infovis/util/Objects.java
// public final class Objects {
//
// /** No instance. */
// private Objects() {
// throw new AssertionError();
// }
//
// /**
// * Requires a non-null argument. This can be used in constructors to enforce
// * non-null arguments.
// *
// * @param <T> The type of the argument.
// * @param obj The argument.
// * @return The argument.
// * @throws IllegalArgumentException When the argument is <code>null</code>.
// */
// public static <T> T requireNonNull(final T obj) {
// if(obj == null) throw new IllegalArgumentException("null argument");
// return obj;
// }
//
// /**
// * Requires a null argument.
// *
// * @param obj The argument.
// * @throws IllegalArgumentException When the argument is <code>null</code>.
// */
// public static void requireNull(final Object obj) {
// if(obj != null) throw new IllegalArgumentException("non-null argument: " + obj);
// }
//
// /**
// * Requires a <code>true</code> statement.
// *
// * @param value The statement that needs to be <code>true</code>.
// * @throws IllegalStateException When the statement is <code>false</code>.
// */
// public static void requireTrue(final boolean value) {
// if(!value) throw new IllegalStateException("expected true");
// }
//
// /**
// * Returns the first argument if it is non-null otherwise the second argument
// * is returned. This is a short-hand for:
// * <code>(obj != null ? obj : or)</code>
// *
// * @param <T> The type of the arguments.
// * @param obj The object.
// * @param or The alternative.
// * @return The first argument if it is non-null or else the second argument.
// */
// public static <T> T nonNull(final T obj, final T or) {
// return obj != null ? obj : or;
// }
//
// }
| import infovis.util.Objects;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities; | package infovis.gui;
/**
* A simple class adding panning and zooming functionality to a
* {@link JComponent}.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public class Canvas extends JComponent implements Refreshable {
/** The underlying zoomable user interface. */
protected final ZoomableUI zui;
/** The painter. */
protected Painter painter;
/** The focused component. */
private JComponent focus;
/**
* Creates a canvas for the given painter.
*
* @param p The painter.
* @param width The initial width of the component.
* @param height The initial height of the component.
*/
public Canvas(final Painter p, final int width, final int height) {
setPreferredSize(new Dimension(width, height)); | // Path: src/main/java/infovis/util/Objects.java
// public final class Objects {
//
// /** No instance. */
// private Objects() {
// throw new AssertionError();
// }
//
// /**
// * Requires a non-null argument. This can be used in constructors to enforce
// * non-null arguments.
// *
// * @param <T> The type of the argument.
// * @param obj The argument.
// * @return The argument.
// * @throws IllegalArgumentException When the argument is <code>null</code>.
// */
// public static <T> T requireNonNull(final T obj) {
// if(obj == null) throw new IllegalArgumentException("null argument");
// return obj;
// }
//
// /**
// * Requires a null argument.
// *
// * @param obj The argument.
// * @throws IllegalArgumentException When the argument is <code>null</code>.
// */
// public static void requireNull(final Object obj) {
// if(obj != null) throw new IllegalArgumentException("non-null argument: " + obj);
// }
//
// /**
// * Requires a <code>true</code> statement.
// *
// * @param value The statement that needs to be <code>true</code>.
// * @throws IllegalStateException When the statement is <code>false</code>.
// */
// public static void requireTrue(final boolean value) {
// if(!value) throw new IllegalStateException("expected true");
// }
//
// /**
// * Returns the first argument if it is non-null otherwise the second argument
// * is returned. This is a short-hand for:
// * <code>(obj != null ? obj : or)</code>
// *
// * @param <T> The type of the arguments.
// * @param obj The object.
// * @param or The alternative.
// * @return The first argument if it is non-null or else the second argument.
// */
// public static <T> T nonNull(final T obj, final T or) {
// return obj != null ? obj : or;
// }
//
// }
// Path: src/main/java/infovis/gui/Canvas.java
import infovis.util.Objects;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
package infovis.gui;
/**
* A simple class adding panning and zooming functionality to a
* {@link JComponent}.
*
* @author Joschi <josua.krause@googlemail.com>
*/
public class Canvas extends JComponent implements Refreshable {
/** The underlying zoomable user interface. */
protected final ZoomableUI zui;
/** The painter. */
protected Painter painter;
/** The focused component. */
private JComponent focus;
/**
* Creates a canvas for the given painter.
*
* @param p The painter.
* @param width The initial width of the component.
* @param height The initial height of the component.
*/
public Canvas(final Painter p, final int width, final int height) {
setPreferredSize(new Dimension(width, height)); | painter = Objects.requireNonNull(p); |
integeruser/jgltut | src/integeruser/jgltut/framework/MousePole.java | // Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public enum MouseButtons {
// MB_LEFT_BTN,
// MB_RIGHT_BTN,
// MB_MIDDLE_BTN
// }
//
// Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public enum MouseModifiers {
// MM_KEY_SHIFT,
// MM_KEY_CTRL,
// MM_KEY_ALT
// }
//
// Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public static abstract class Pole {
// public abstract void mouseMove(Vector2i vec2);
//
// public abstract void mouseClick(MouseButtons button, boolean isPressed, MouseModifiers modifiers, Vector2i position);
//
// public abstract void mouseWheel(int direction, MouseModifiers modifiers, Vector2i position);
//
//
// public abstract void charPress(int key, boolean isShiftPressed, float lastFrameDuration);
// }
| import integeruser.jglsdk.glutil.MousePoles.MouseButtons;
import integeruser.jglsdk.glutil.MousePoles.MouseModifiers;
import integeruser.jglsdk.glutil.MousePoles.Pole;
import org.joml.Vector2i;
import static org.lwjgl.glfw.GLFW.*; | package integeruser.jgltut.framework;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
* Original: https://bitbucket.org/alfonse/gltut/src/default/framework/MousePole.h
*/
public class MousePole {
public static void forwardMouseMotion(Pole forward, int x, int y) {
forward.mouseMove(new Vector2i(x, y));
}
public static void forwardMouseButton(long window, Pole forwardPole, int button, boolean state, int x, int y) { | // Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public enum MouseButtons {
// MB_LEFT_BTN,
// MB_RIGHT_BTN,
// MB_MIDDLE_BTN
// }
//
// Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public enum MouseModifiers {
// MM_KEY_SHIFT,
// MM_KEY_CTRL,
// MM_KEY_ALT
// }
//
// Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public static abstract class Pole {
// public abstract void mouseMove(Vector2i vec2);
//
// public abstract void mouseClick(MouseButtons button, boolean isPressed, MouseModifiers modifiers, Vector2i position);
//
// public abstract void mouseWheel(int direction, MouseModifiers modifiers, Vector2i position);
//
//
// public abstract void charPress(int key, boolean isShiftPressed, float lastFrameDuration);
// }
// Path: src/integeruser/jgltut/framework/MousePole.java
import integeruser.jglsdk.glutil.MousePoles.MouseButtons;
import integeruser.jglsdk.glutil.MousePoles.MouseModifiers;
import integeruser.jglsdk.glutil.MousePoles.Pole;
import org.joml.Vector2i;
import static org.lwjgl.glfw.GLFW.*;
package integeruser.jgltut.framework;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
* Original: https://bitbucket.org/alfonse/gltut/src/default/framework/MousePole.h
*/
public class MousePole {
public static void forwardMouseMotion(Pole forward, int x, int y) {
forward.mouseMove(new Vector2i(x, y));
}
public static void forwardMouseButton(long window, Pole forwardPole, int button, boolean state, int x, int y) { | MouseModifiers modifiers = calcModifiers(window); |
integeruser/jgltut | src/integeruser/jgltut/framework/MousePole.java | // Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public enum MouseButtons {
// MB_LEFT_BTN,
// MB_RIGHT_BTN,
// MB_MIDDLE_BTN
// }
//
// Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public enum MouseModifiers {
// MM_KEY_SHIFT,
// MM_KEY_CTRL,
// MM_KEY_ALT
// }
//
// Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public static abstract class Pole {
// public abstract void mouseMove(Vector2i vec2);
//
// public abstract void mouseClick(MouseButtons button, boolean isPressed, MouseModifiers modifiers, Vector2i position);
//
// public abstract void mouseWheel(int direction, MouseModifiers modifiers, Vector2i position);
//
//
// public abstract void charPress(int key, boolean isShiftPressed, float lastFrameDuration);
// }
| import integeruser.jglsdk.glutil.MousePoles.MouseButtons;
import integeruser.jglsdk.glutil.MousePoles.MouseModifiers;
import integeruser.jglsdk.glutil.MousePoles.Pole;
import org.joml.Vector2i;
import static org.lwjgl.glfw.GLFW.*; | package integeruser.jgltut.framework;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
* Original: https://bitbucket.org/alfonse/gltut/src/default/framework/MousePole.h
*/
public class MousePole {
public static void forwardMouseMotion(Pole forward, int x, int y) {
forward.mouseMove(new Vector2i(x, y));
}
public static void forwardMouseButton(long window, Pole forwardPole, int button, boolean state, int x, int y) {
MouseModifiers modifiers = calcModifiers(window);
Vector2i mouseLoc = new Vector2i(x, y); | // Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public enum MouseButtons {
// MB_LEFT_BTN,
// MB_RIGHT_BTN,
// MB_MIDDLE_BTN
// }
//
// Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public enum MouseModifiers {
// MM_KEY_SHIFT,
// MM_KEY_CTRL,
// MM_KEY_ALT
// }
//
// Path: src/integeruser/jglsdk/glutil/MousePoles.java
// public static abstract class Pole {
// public abstract void mouseMove(Vector2i vec2);
//
// public abstract void mouseClick(MouseButtons button, boolean isPressed, MouseModifiers modifiers, Vector2i position);
//
// public abstract void mouseWheel(int direction, MouseModifiers modifiers, Vector2i position);
//
//
// public abstract void charPress(int key, boolean isShiftPressed, float lastFrameDuration);
// }
// Path: src/integeruser/jgltut/framework/MousePole.java
import integeruser.jglsdk.glutil.MousePoles.MouseButtons;
import integeruser.jglsdk.glutil.MousePoles.MouseModifiers;
import integeruser.jglsdk.glutil.MousePoles.Pole;
import org.joml.Vector2i;
import static org.lwjgl.glfw.GLFW.*;
package integeruser.jgltut.framework;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
* Original: https://bitbucket.org/alfonse/gltut/src/default/framework/MousePole.h
*/
public class MousePole {
public static void forwardMouseMotion(Pole forward, int x, int y) {
forward.mouseMove(new Vector2i(x, y));
}
public static void forwardMouseButton(long window, Pole forwardPole, int button, boolean state, int x, int y) {
MouseModifiers modifiers = calcModifiers(window);
Vector2i mouseLoc = new Vector2i(x, y); | MouseButtons mouseButtons = null; |
integeruser/jgltut | src/integeruser/jgltut/framework/Framework.java | // Path: src/integeruser/jglsdk/glutil/Shader.java
// public class Shader {
// private static class CompileLinkShaderException extends RuntimeException {
// private static final long serialVersionUID = 5490603440382398244L;
//
// CompileLinkShaderException(int shader) {
// super(glGetShaderInfoLog(
// shader,
// glGetShaderi(shader, GL_INFO_LOG_LENGTH)));
// }
// }
//
// private static class CompileLinkProgramException extends RuntimeException {
// private static final long serialVersionUID = 7321217286524434327L;
//
// CompileLinkProgramException(int program) {
// super(glGetShaderInfoLog(
// program,
// glGetShaderi(program, GL_INFO_LOG_LENGTH)));
// }
// }
//
//
// public static int compileShader(int shaderType, String shaderCode) {
// int shader = glCreateShader(shaderType);
//
// glShaderSource(shader, shaderCode);
// glCompileShader(shader);
//
// int status = glGetShaderi(shader, GL_COMPILE_STATUS);
// if (status == GL_FALSE) {
// glDeleteShader(shader);
// throw new CompileLinkShaderException(shader);
// }
//
// return shader;
// }
//
//
// public static int linkProgram(ArrayList<Integer> shaders) {
// int program = glCreateProgram();
// return linkProgram(program, shaders);
// }
//
// private static int linkProgram(int program, ArrayList<Integer> shaders) {
// for (Integer shader : shaders) {
// glAttachShader(program, shader);
// }
//
// glLinkProgram(program);
//
// int status = glGetProgrami(program, GL_LINK_STATUS);
// if (status == GL_FALSE) {
// glDeleteProgram(program);
// throw new CompileLinkProgramException(program);
// }
//
// for (Integer shader : shaders) {
// glDetachShader(program, shader);
// }
//
// return program;
// }
// }
| import integeruser.jglsdk.glutil.Shader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import static org.lwjgl.opengl.GL20.glDeleteShader; | package integeruser.jgltut.framework;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
* Original: https://bitbucket.org/alfonse/gltut/src/default/framework/framework.cpp
*/
public class Framework {
public static String COMMON_DATAPATH = "/integeruser/jgltut/data/";
public static String CURRENT_TUTORIAL_DATAPATH = null;
public static String findFileOrThrow(String fileName) {
// search the file in '/jgltut/tut##/data/'
InputStream fileStream = Framework.class.getResourceAsStream(CURRENT_TUTORIAL_DATAPATH + fileName);
if (fileStream != null) return CURRENT_TUTORIAL_DATAPATH + fileName;
// search the file in '/jgltut/data/'
fileStream = Framework.class.getResourceAsStream(COMMON_DATAPATH + fileName);
if (fileStream != null) return COMMON_DATAPATH + fileName;
throw new RuntimeException("Could not find the file " + fileName);
}
////////////////////////////////
public static int loadShader(int shaderType, String shaderFilename) {
String filePath = Framework.findFileOrThrow(shaderFilename);
String shaderCode = loadShaderFile(filePath); | // Path: src/integeruser/jglsdk/glutil/Shader.java
// public class Shader {
// private static class CompileLinkShaderException extends RuntimeException {
// private static final long serialVersionUID = 5490603440382398244L;
//
// CompileLinkShaderException(int shader) {
// super(glGetShaderInfoLog(
// shader,
// glGetShaderi(shader, GL_INFO_LOG_LENGTH)));
// }
// }
//
// private static class CompileLinkProgramException extends RuntimeException {
// private static final long serialVersionUID = 7321217286524434327L;
//
// CompileLinkProgramException(int program) {
// super(glGetShaderInfoLog(
// program,
// glGetShaderi(program, GL_INFO_LOG_LENGTH)));
// }
// }
//
//
// public static int compileShader(int shaderType, String shaderCode) {
// int shader = glCreateShader(shaderType);
//
// glShaderSource(shader, shaderCode);
// glCompileShader(shader);
//
// int status = glGetShaderi(shader, GL_COMPILE_STATUS);
// if (status == GL_FALSE) {
// glDeleteShader(shader);
// throw new CompileLinkShaderException(shader);
// }
//
// return shader;
// }
//
//
// public static int linkProgram(ArrayList<Integer> shaders) {
// int program = glCreateProgram();
// return linkProgram(program, shaders);
// }
//
// private static int linkProgram(int program, ArrayList<Integer> shaders) {
// for (Integer shader : shaders) {
// glAttachShader(program, shader);
// }
//
// glLinkProgram(program);
//
// int status = glGetProgrami(program, GL_LINK_STATUS);
// if (status == GL_FALSE) {
// glDeleteProgram(program);
// throw new CompileLinkProgramException(program);
// }
//
// for (Integer shader : shaders) {
// glDetachShader(program, shader);
// }
//
// return program;
// }
// }
// Path: src/integeruser/jgltut/framework/Framework.java
import integeruser.jglsdk.glutil.Shader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import static org.lwjgl.opengl.GL20.glDeleteShader;
package integeruser.jgltut.framework;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
* Original: https://bitbucket.org/alfonse/gltut/src/default/framework/framework.cpp
*/
public class Framework {
public static String COMMON_DATAPATH = "/integeruser/jgltut/data/";
public static String CURRENT_TUTORIAL_DATAPATH = null;
public static String findFileOrThrow(String fileName) {
// search the file in '/jgltut/tut##/data/'
InputStream fileStream = Framework.class.getResourceAsStream(CURRENT_TUTORIAL_DATAPATH + fileName);
if (fileStream != null) return CURRENT_TUTORIAL_DATAPATH + fileName;
// search the file in '/jgltut/data/'
fileStream = Framework.class.getResourceAsStream(COMMON_DATAPATH + fileName);
if (fileStream != null) return COMMON_DATAPATH + fileName;
throw new RuntimeException("Could not find the file " + fileName);
}
////////////////////////////////
public static int loadShader(int shaderType, String shaderFilename) {
String filePath = Framework.findFileOrThrow(shaderFilename);
String shaderCode = loadShaderFile(filePath); | return Shader.compileShader(shaderType, shaderCode); |
integeruser/jgltut | src/integeruser/jgltut/Tutorial.java | // Path: src/integeruser/jgltut/commons/LightBlock.java
// public class LightBlock implements Bufferable {
// public static final int MAX_NUMBER_OF_LIGHTS = 5;
// public static final int BYTES = Float.BYTES * (4 + 1 + 1 + 2) + PerLight.BYTES * MAX_NUMBER_OF_LIGHTS;
//
// public Vector4f ambientIntensity;
// public float lightAttenuation;
// public float maxIntensity;
// public float padding[] = new float[2];
// public PerLight lights[] = new PerLight[MAX_NUMBER_OF_LIGHTS];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// ambientIntensity.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(lightAttenuation);
//
// buffer.putFloat(maxIntensity);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
//
// for (PerLight light : lights) {
// if (light == null) break;
// light.get(buffer);
// }
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/MaterialBlock.java
// public class MaterialBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (4 + 4 + 1 + 3);
//
// public Vector4f diffuseColor;
// public Vector4f specularColor;
// public float specularShininess;
// public float padding[] = new float[3];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// diffuseColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// specularColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(specularShininess);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
// buffer.putFloat(padding[2]);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/ProjectionBlock.java
// public class ProjectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16);
//
// public Matrix4f cameraToClipMatrix;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// cameraToClipMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/UnprojectionBlock.java
// public class UnprojectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16) + Integer.BYTES * (2);
//
// public Matrix4f clipToCameraMatrix;
// public Vector2i windowSize;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// clipToCameraMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
//
// windowSize.get(buffer);
// buffer.position(buffer.position() + Integer.BYTES * 2);
// return buffer;
// }
// }
| import integeruser.jgltut.commons.LightBlock;
import integeruser.jgltut.commons.MaterialBlock;
import integeruser.jgltut.commons.ProjectionBlock;
import integeruser.jgltut.commons.UnprojectionBlock;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Platform;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL; | package integeruser.jgltut;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
*/
public abstract class Tutorial {
protected long window;
protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);
protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);
// Measured in seconds
protected float elapsedTime;
protected float lastFrameDuration;
private double lastFrameTimestamp;
protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);
protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);
protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16); | // Path: src/integeruser/jgltut/commons/LightBlock.java
// public class LightBlock implements Bufferable {
// public static final int MAX_NUMBER_OF_LIGHTS = 5;
// public static final int BYTES = Float.BYTES * (4 + 1 + 1 + 2) + PerLight.BYTES * MAX_NUMBER_OF_LIGHTS;
//
// public Vector4f ambientIntensity;
// public float lightAttenuation;
// public float maxIntensity;
// public float padding[] = new float[2];
// public PerLight lights[] = new PerLight[MAX_NUMBER_OF_LIGHTS];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// ambientIntensity.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(lightAttenuation);
//
// buffer.putFloat(maxIntensity);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
//
// for (PerLight light : lights) {
// if (light == null) break;
// light.get(buffer);
// }
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/MaterialBlock.java
// public class MaterialBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (4 + 4 + 1 + 3);
//
// public Vector4f diffuseColor;
// public Vector4f specularColor;
// public float specularShininess;
// public float padding[] = new float[3];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// diffuseColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// specularColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(specularShininess);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
// buffer.putFloat(padding[2]);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/ProjectionBlock.java
// public class ProjectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16);
//
// public Matrix4f cameraToClipMatrix;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// cameraToClipMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/UnprojectionBlock.java
// public class UnprojectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16) + Integer.BYTES * (2);
//
// public Matrix4f clipToCameraMatrix;
// public Vector2i windowSize;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// clipToCameraMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
//
// windowSize.get(buffer);
// buffer.position(buffer.position() + Integer.BYTES * 2);
// return buffer;
// }
// }
// Path: src/integeruser/jgltut/Tutorial.java
import integeruser.jgltut.commons.LightBlock;
import integeruser.jgltut.commons.MaterialBlock;
import integeruser.jgltut.commons.ProjectionBlock;
import integeruser.jgltut.commons.UnprojectionBlock;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Platform;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL;
package integeruser.jgltut;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
*/
public abstract class Tutorial {
protected long window;
protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);
protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);
// Measured in seconds
protected float elapsedTime;
protected float lastFrameDuration;
private double lastFrameTimestamp;
protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);
protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);
protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16); | protected ByteBuffer projectionBlockBuffer = BufferUtils.createByteBuffer(ProjectionBlock.BYTES); |
integeruser/jgltut | src/integeruser/jgltut/Tutorial.java | // Path: src/integeruser/jgltut/commons/LightBlock.java
// public class LightBlock implements Bufferable {
// public static final int MAX_NUMBER_OF_LIGHTS = 5;
// public static final int BYTES = Float.BYTES * (4 + 1 + 1 + 2) + PerLight.BYTES * MAX_NUMBER_OF_LIGHTS;
//
// public Vector4f ambientIntensity;
// public float lightAttenuation;
// public float maxIntensity;
// public float padding[] = new float[2];
// public PerLight lights[] = new PerLight[MAX_NUMBER_OF_LIGHTS];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// ambientIntensity.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(lightAttenuation);
//
// buffer.putFloat(maxIntensity);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
//
// for (PerLight light : lights) {
// if (light == null) break;
// light.get(buffer);
// }
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/MaterialBlock.java
// public class MaterialBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (4 + 4 + 1 + 3);
//
// public Vector4f diffuseColor;
// public Vector4f specularColor;
// public float specularShininess;
// public float padding[] = new float[3];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// diffuseColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// specularColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(specularShininess);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
// buffer.putFloat(padding[2]);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/ProjectionBlock.java
// public class ProjectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16);
//
// public Matrix4f cameraToClipMatrix;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// cameraToClipMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/UnprojectionBlock.java
// public class UnprojectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16) + Integer.BYTES * (2);
//
// public Matrix4f clipToCameraMatrix;
// public Vector2i windowSize;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// clipToCameraMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
//
// windowSize.get(buffer);
// buffer.position(buffer.position() + Integer.BYTES * 2);
// return buffer;
// }
// }
| import integeruser.jgltut.commons.LightBlock;
import integeruser.jgltut.commons.MaterialBlock;
import integeruser.jgltut.commons.ProjectionBlock;
import integeruser.jgltut.commons.UnprojectionBlock;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Platform;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL; | package integeruser.jgltut;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
*/
public abstract class Tutorial {
protected long window;
protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);
protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);
// Measured in seconds
protected float elapsedTime;
protected float lastFrameDuration;
private double lastFrameTimestamp;
protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);
protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);
protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16);
protected ByteBuffer projectionBlockBuffer = BufferUtils.createByteBuffer(ProjectionBlock.BYTES); | // Path: src/integeruser/jgltut/commons/LightBlock.java
// public class LightBlock implements Bufferable {
// public static final int MAX_NUMBER_OF_LIGHTS = 5;
// public static final int BYTES = Float.BYTES * (4 + 1 + 1 + 2) + PerLight.BYTES * MAX_NUMBER_OF_LIGHTS;
//
// public Vector4f ambientIntensity;
// public float lightAttenuation;
// public float maxIntensity;
// public float padding[] = new float[2];
// public PerLight lights[] = new PerLight[MAX_NUMBER_OF_LIGHTS];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// ambientIntensity.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(lightAttenuation);
//
// buffer.putFloat(maxIntensity);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
//
// for (PerLight light : lights) {
// if (light == null) break;
// light.get(buffer);
// }
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/MaterialBlock.java
// public class MaterialBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (4 + 4 + 1 + 3);
//
// public Vector4f diffuseColor;
// public Vector4f specularColor;
// public float specularShininess;
// public float padding[] = new float[3];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// diffuseColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// specularColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(specularShininess);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
// buffer.putFloat(padding[2]);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/ProjectionBlock.java
// public class ProjectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16);
//
// public Matrix4f cameraToClipMatrix;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// cameraToClipMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/UnprojectionBlock.java
// public class UnprojectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16) + Integer.BYTES * (2);
//
// public Matrix4f clipToCameraMatrix;
// public Vector2i windowSize;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// clipToCameraMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
//
// windowSize.get(buffer);
// buffer.position(buffer.position() + Integer.BYTES * 2);
// return buffer;
// }
// }
// Path: src/integeruser/jgltut/Tutorial.java
import integeruser.jgltut.commons.LightBlock;
import integeruser.jgltut.commons.MaterialBlock;
import integeruser.jgltut.commons.ProjectionBlock;
import integeruser.jgltut.commons.UnprojectionBlock;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Platform;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL;
package integeruser.jgltut;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
*/
public abstract class Tutorial {
protected long window;
protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);
protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);
// Measured in seconds
protected float elapsedTime;
protected float lastFrameDuration;
private double lastFrameTimestamp;
protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);
protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);
protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16);
protected ByteBuffer projectionBlockBuffer = BufferUtils.createByteBuffer(ProjectionBlock.BYTES); | protected ByteBuffer unprojectionBlockBuffer = BufferUtils.createByteBuffer(UnprojectionBlock.BYTES); |
integeruser/jgltut | src/integeruser/jgltut/Tutorial.java | // Path: src/integeruser/jgltut/commons/LightBlock.java
// public class LightBlock implements Bufferable {
// public static final int MAX_NUMBER_OF_LIGHTS = 5;
// public static final int BYTES = Float.BYTES * (4 + 1 + 1 + 2) + PerLight.BYTES * MAX_NUMBER_OF_LIGHTS;
//
// public Vector4f ambientIntensity;
// public float lightAttenuation;
// public float maxIntensity;
// public float padding[] = new float[2];
// public PerLight lights[] = new PerLight[MAX_NUMBER_OF_LIGHTS];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// ambientIntensity.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(lightAttenuation);
//
// buffer.putFloat(maxIntensity);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
//
// for (PerLight light : lights) {
// if (light == null) break;
// light.get(buffer);
// }
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/MaterialBlock.java
// public class MaterialBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (4 + 4 + 1 + 3);
//
// public Vector4f diffuseColor;
// public Vector4f specularColor;
// public float specularShininess;
// public float padding[] = new float[3];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// diffuseColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// specularColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(specularShininess);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
// buffer.putFloat(padding[2]);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/ProjectionBlock.java
// public class ProjectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16);
//
// public Matrix4f cameraToClipMatrix;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// cameraToClipMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/UnprojectionBlock.java
// public class UnprojectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16) + Integer.BYTES * (2);
//
// public Matrix4f clipToCameraMatrix;
// public Vector2i windowSize;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// clipToCameraMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
//
// windowSize.get(buffer);
// buffer.position(buffer.position() + Integer.BYTES * 2);
// return buffer;
// }
// }
| import integeruser.jgltut.commons.LightBlock;
import integeruser.jgltut.commons.MaterialBlock;
import integeruser.jgltut.commons.ProjectionBlock;
import integeruser.jgltut.commons.UnprojectionBlock;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Platform;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL; | package integeruser.jgltut;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
*/
public abstract class Tutorial {
protected long window;
protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);
protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);
// Measured in seconds
protected float elapsedTime;
protected float lastFrameDuration;
private double lastFrameTimestamp;
protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);
protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);
protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16);
protected ByteBuffer projectionBlockBuffer = BufferUtils.createByteBuffer(ProjectionBlock.BYTES);
protected ByteBuffer unprojectionBlockBuffer = BufferUtils.createByteBuffer(UnprojectionBlock.BYTES); | // Path: src/integeruser/jgltut/commons/LightBlock.java
// public class LightBlock implements Bufferable {
// public static final int MAX_NUMBER_OF_LIGHTS = 5;
// public static final int BYTES = Float.BYTES * (4 + 1 + 1 + 2) + PerLight.BYTES * MAX_NUMBER_OF_LIGHTS;
//
// public Vector4f ambientIntensity;
// public float lightAttenuation;
// public float maxIntensity;
// public float padding[] = new float[2];
// public PerLight lights[] = new PerLight[MAX_NUMBER_OF_LIGHTS];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// ambientIntensity.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(lightAttenuation);
//
// buffer.putFloat(maxIntensity);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
//
// for (PerLight light : lights) {
// if (light == null) break;
// light.get(buffer);
// }
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/MaterialBlock.java
// public class MaterialBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (4 + 4 + 1 + 3);
//
// public Vector4f diffuseColor;
// public Vector4f specularColor;
// public float specularShininess;
// public float padding[] = new float[3];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// diffuseColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// specularColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(specularShininess);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
// buffer.putFloat(padding[2]);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/ProjectionBlock.java
// public class ProjectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16);
//
// public Matrix4f cameraToClipMatrix;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// cameraToClipMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/UnprojectionBlock.java
// public class UnprojectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16) + Integer.BYTES * (2);
//
// public Matrix4f clipToCameraMatrix;
// public Vector2i windowSize;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// clipToCameraMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
//
// windowSize.get(buffer);
// buffer.position(buffer.position() + Integer.BYTES * 2);
// return buffer;
// }
// }
// Path: src/integeruser/jgltut/Tutorial.java
import integeruser.jgltut.commons.LightBlock;
import integeruser.jgltut.commons.MaterialBlock;
import integeruser.jgltut.commons.ProjectionBlock;
import integeruser.jgltut.commons.UnprojectionBlock;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Platform;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL;
package integeruser.jgltut;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
*/
public abstract class Tutorial {
protected long window;
protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);
protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);
// Measured in seconds
protected float elapsedTime;
protected float lastFrameDuration;
private double lastFrameTimestamp;
protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);
protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);
protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16);
protected ByteBuffer projectionBlockBuffer = BufferUtils.createByteBuffer(ProjectionBlock.BYTES);
protected ByteBuffer unprojectionBlockBuffer = BufferUtils.createByteBuffer(UnprojectionBlock.BYTES); | protected ByteBuffer lightBlockBuffer = BufferUtils.createByteBuffer(LightBlock.BYTES); |
integeruser/jgltut | src/integeruser/jgltut/Tutorial.java | // Path: src/integeruser/jgltut/commons/LightBlock.java
// public class LightBlock implements Bufferable {
// public static final int MAX_NUMBER_OF_LIGHTS = 5;
// public static final int BYTES = Float.BYTES * (4 + 1 + 1 + 2) + PerLight.BYTES * MAX_NUMBER_OF_LIGHTS;
//
// public Vector4f ambientIntensity;
// public float lightAttenuation;
// public float maxIntensity;
// public float padding[] = new float[2];
// public PerLight lights[] = new PerLight[MAX_NUMBER_OF_LIGHTS];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// ambientIntensity.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(lightAttenuation);
//
// buffer.putFloat(maxIntensity);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
//
// for (PerLight light : lights) {
// if (light == null) break;
// light.get(buffer);
// }
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/MaterialBlock.java
// public class MaterialBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (4 + 4 + 1 + 3);
//
// public Vector4f diffuseColor;
// public Vector4f specularColor;
// public float specularShininess;
// public float padding[] = new float[3];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// diffuseColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// specularColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(specularShininess);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
// buffer.putFloat(padding[2]);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/ProjectionBlock.java
// public class ProjectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16);
//
// public Matrix4f cameraToClipMatrix;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// cameraToClipMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/UnprojectionBlock.java
// public class UnprojectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16) + Integer.BYTES * (2);
//
// public Matrix4f clipToCameraMatrix;
// public Vector2i windowSize;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// clipToCameraMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
//
// windowSize.get(buffer);
// buffer.position(buffer.position() + Integer.BYTES * 2);
// return buffer;
// }
// }
| import integeruser.jgltut.commons.LightBlock;
import integeruser.jgltut.commons.MaterialBlock;
import integeruser.jgltut.commons.ProjectionBlock;
import integeruser.jgltut.commons.UnprojectionBlock;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Platform;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL; | package integeruser.jgltut;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
*/
public abstract class Tutorial {
protected long window;
protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);
protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);
// Measured in seconds
protected float elapsedTime;
protected float lastFrameDuration;
private double lastFrameTimestamp;
protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);
protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);
protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16);
protected ByteBuffer projectionBlockBuffer = BufferUtils.createByteBuffer(ProjectionBlock.BYTES);
protected ByteBuffer unprojectionBlockBuffer = BufferUtils.createByteBuffer(UnprojectionBlock.BYTES);
protected ByteBuffer lightBlockBuffer = BufferUtils.createByteBuffer(LightBlock.BYTES); | // Path: src/integeruser/jgltut/commons/LightBlock.java
// public class LightBlock implements Bufferable {
// public static final int MAX_NUMBER_OF_LIGHTS = 5;
// public static final int BYTES = Float.BYTES * (4 + 1 + 1 + 2) + PerLight.BYTES * MAX_NUMBER_OF_LIGHTS;
//
// public Vector4f ambientIntensity;
// public float lightAttenuation;
// public float maxIntensity;
// public float padding[] = new float[2];
// public PerLight lights[] = new PerLight[MAX_NUMBER_OF_LIGHTS];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// ambientIntensity.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(lightAttenuation);
//
// buffer.putFloat(maxIntensity);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
//
// for (PerLight light : lights) {
// if (light == null) break;
// light.get(buffer);
// }
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/MaterialBlock.java
// public class MaterialBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (4 + 4 + 1 + 3);
//
// public Vector4f diffuseColor;
// public Vector4f specularColor;
// public float specularShininess;
// public float padding[] = new float[3];
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// diffuseColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// specularColor.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 4);
//
// buffer.putFloat(specularShininess);
//
// buffer.putFloat(padding[0]);
// buffer.putFloat(padding[1]);
// buffer.putFloat(padding[2]);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/ProjectionBlock.java
// public class ProjectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16);
//
// public Matrix4f cameraToClipMatrix;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// cameraToClipMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
// return buffer;
// }
// }
//
// Path: src/integeruser/jgltut/commons/UnprojectionBlock.java
// public class UnprojectionBlock implements Bufferable {
// public static final int BYTES = Float.BYTES * (16) + Integer.BYTES * (2);
//
// public Matrix4f clipToCameraMatrix;
// public Vector2i windowSize;
//
// @Override
// public ByteBuffer get(ByteBuffer buffer) {
// clipToCameraMatrix.get(buffer);
// buffer.position(buffer.position() + Float.BYTES * 16);
//
// windowSize.get(buffer);
// buffer.position(buffer.position() + Integer.BYTES * 2);
// return buffer;
// }
// }
// Path: src/integeruser/jgltut/Tutorial.java
import integeruser.jgltut.commons.LightBlock;
import integeruser.jgltut.commons.MaterialBlock;
import integeruser.jgltut.commons.ProjectionBlock;
import integeruser.jgltut.commons.UnprojectionBlock;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.Platform;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL;
package integeruser.jgltut;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
*/
public abstract class Tutorial {
protected long window;
protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);
protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);
// Measured in seconds
protected float elapsedTime;
protected float lastFrameDuration;
private double lastFrameTimestamp;
protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);
protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);
protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16);
protected ByteBuffer projectionBlockBuffer = BufferUtils.createByteBuffer(ProjectionBlock.BYTES);
protected ByteBuffer unprojectionBlockBuffer = BufferUtils.createByteBuffer(UnprojectionBlock.BYTES);
protected ByteBuffer lightBlockBuffer = BufferUtils.createByteBuffer(LightBlock.BYTES); | protected ByteBuffer materialBlockBuffer = BufferUtils.createByteBuffer(MaterialBlock.BYTES); |
integeruser/jgltut | src/integeruser/jglsdk/glimg/ImageCreator.java | // Path: src/integeruser/jglsdk/glimg/ImageFormat.java
// enum PixelDataType {
// NORM_UNSIGNED_INTEGER, // Image data are unsigned integers that are mapped to floats on the range [0, 1].
// NORM_SIGNED_INTEGER, // Image data are signed integers that are mapped to floats on the range [-1, 1].
// UNSIGNED_INTEGRAL, // Image data are unsigned integers.
// SIGNED_INTEGRAL, // Image data are signed integers.
// FLOAT, // Image data are individual floating-point numbers.
// SHARED_EXP_FLOAT, // Image data are floats, but each pixel uses the same exponent.
// NUM_UNCOMPRESSED_TYPES,
//
// COMPRESSED_BC1, // Image data is compressed with DXT1/BC1 compression. Unsigned normalized integers.
// COMPRESSED_BC2, // Image data is compressed with DXT3/BC2 compression. Unsigned normalized integers.
// COMPRESSED_BC3, // Image data is compressed with DXT5/BC3 compression. Unsigned normalized integers.
// COMPRESSED_UNSIGNED_BC4, // Image is compressed with BC4 compression (1-component), with unsigned normalized integers.
// COMPRESSED_SIGNED_BC4, // Image is compressed with BC4 compression (1-component), with signed normalized integers.
// COMPRESSED_UNSIGNED_BC5, // Image is compressed with BC5 compression (2-component), with unsigned normalized integers.
// COMPRESSED_SIGNED_BC5, // Image is compressed with BC5 compression (2-component), with signed normalized integers.
// COMPRESSED_UNSIGNED_BC6H, // Image is compressed with BC6H compression, with unsigned floats [0, +inf).
// COMPRESSED_SIGNED_BC6H, // Image is compressed with BC6H compression, with floats.
// COMPRESSED_BC7, // Image data is compressed with BC7 compression. Unsigned normalized integers.
//
// NUM_TYPES
// }
//
// Path: src/integeruser/jglsdk/glimg/ImageSet.java
// public static class Dimensions {
// public int numDimensions; // The number of dimensions of an image. Can be 1, 2, or 3.
// public int width; // The width of the image. Always valid.
// public int height; // The height of the image. Only valid if numDimensions is 2 or 3.
// public int depth; // The depth of the image. Only valid if numDimensions is 3.
//
// ////////////////////////////////
// public Dimensions() {
// }
//
// public Dimensions(Dimensions dimensions) {
// numDimensions = dimensions.numDimensions;
// width = dimensions.width;
// height = dimensions.height;
// depth = dimensions.depth;
// }
//
// ////////////////////////////////
// // Computes the number of rows of pixel data in the image.
// public int calcNumLines() {
// switch (numDimensions) {
// case 1:
// return 1;
//
// case 2:
// return height;
//
// case 3:
// return depth * height;
// }
// // Should not be possible.
// return -1;
// }
// }
//
// Path: src/integeruser/jglsdk/glimg/Util.java
// static class CompressedBlockData {
// Dimensions dimensions; // The dimensionality of a block.
// int byteCount; // Number of bytes in a block.
// }
| import integeruser.jglsdk.glimg.ImageFormat.PixelDataType;
import integeruser.jglsdk.glimg.ImageSet.Dimensions;
import integeruser.jglsdk.glimg.Util.CompressedBlockData;
import java.util.ArrayList;
import java.util.Arrays; | throw new RuntimeException("Not implemented.");
} else {
int imageDataOffset = ((arrayIx * faceCount) + faceIx) * imageSizes[mipmapLevel];
copyImageFlipped(sourceData, imageData, imageDataOffset, mipmapLevel);
}
}
ImageSet createImage() {
if (imageData.isEmpty()) throw new RuntimeException("ImageSet already created.");
return new ImageSet(imageFormat, imageDimensions, mipmapCount, arrayCount, faceCount, imageData, imageSizes);
}
////////////////////////////////
private ImageFormat imageFormat;
private Dimensions imageDimensions;
private int mipmapCount;
private int arrayCount;
private int faceCount;
private ArrayList<byte[]> imageData;
private int[] imageSizes;
////////////////////////////////
private void copyImageFlipped(byte[] sourceData, byte[] imageData, int imageDataOffset, int mipmapLevel) {
assert (sourceData.length * faceCount * arrayCount) == imageData.length;
Dimensions mipmapImageDimensions = Util.calcMipmapLevelDimensions(new Dimensions(imageDimensions), mipmapLevel);
| // Path: src/integeruser/jglsdk/glimg/ImageFormat.java
// enum PixelDataType {
// NORM_UNSIGNED_INTEGER, // Image data are unsigned integers that are mapped to floats on the range [0, 1].
// NORM_SIGNED_INTEGER, // Image data are signed integers that are mapped to floats on the range [-1, 1].
// UNSIGNED_INTEGRAL, // Image data are unsigned integers.
// SIGNED_INTEGRAL, // Image data are signed integers.
// FLOAT, // Image data are individual floating-point numbers.
// SHARED_EXP_FLOAT, // Image data are floats, but each pixel uses the same exponent.
// NUM_UNCOMPRESSED_TYPES,
//
// COMPRESSED_BC1, // Image data is compressed with DXT1/BC1 compression. Unsigned normalized integers.
// COMPRESSED_BC2, // Image data is compressed with DXT3/BC2 compression. Unsigned normalized integers.
// COMPRESSED_BC3, // Image data is compressed with DXT5/BC3 compression. Unsigned normalized integers.
// COMPRESSED_UNSIGNED_BC4, // Image is compressed with BC4 compression (1-component), with unsigned normalized integers.
// COMPRESSED_SIGNED_BC4, // Image is compressed with BC4 compression (1-component), with signed normalized integers.
// COMPRESSED_UNSIGNED_BC5, // Image is compressed with BC5 compression (2-component), with unsigned normalized integers.
// COMPRESSED_SIGNED_BC5, // Image is compressed with BC5 compression (2-component), with signed normalized integers.
// COMPRESSED_UNSIGNED_BC6H, // Image is compressed with BC6H compression, with unsigned floats [0, +inf).
// COMPRESSED_SIGNED_BC6H, // Image is compressed with BC6H compression, with floats.
// COMPRESSED_BC7, // Image data is compressed with BC7 compression. Unsigned normalized integers.
//
// NUM_TYPES
// }
//
// Path: src/integeruser/jglsdk/glimg/ImageSet.java
// public static class Dimensions {
// public int numDimensions; // The number of dimensions of an image. Can be 1, 2, or 3.
// public int width; // The width of the image. Always valid.
// public int height; // The height of the image. Only valid if numDimensions is 2 or 3.
// public int depth; // The depth of the image. Only valid if numDimensions is 3.
//
// ////////////////////////////////
// public Dimensions() {
// }
//
// public Dimensions(Dimensions dimensions) {
// numDimensions = dimensions.numDimensions;
// width = dimensions.width;
// height = dimensions.height;
// depth = dimensions.depth;
// }
//
// ////////////////////////////////
// // Computes the number of rows of pixel data in the image.
// public int calcNumLines() {
// switch (numDimensions) {
// case 1:
// return 1;
//
// case 2:
// return height;
//
// case 3:
// return depth * height;
// }
// // Should not be possible.
// return -1;
// }
// }
//
// Path: src/integeruser/jglsdk/glimg/Util.java
// static class CompressedBlockData {
// Dimensions dimensions; // The dimensionality of a block.
// int byteCount; // Number of bytes in a block.
// }
// Path: src/integeruser/jglsdk/glimg/ImageCreator.java
import integeruser.jglsdk.glimg.ImageFormat.PixelDataType;
import integeruser.jglsdk.glimg.ImageSet.Dimensions;
import integeruser.jglsdk.glimg.Util.CompressedBlockData;
import java.util.ArrayList;
import java.util.Arrays;
throw new RuntimeException("Not implemented.");
} else {
int imageDataOffset = ((arrayIx * faceCount) + faceIx) * imageSizes[mipmapLevel];
copyImageFlipped(sourceData, imageData, imageDataOffset, mipmapLevel);
}
}
ImageSet createImage() {
if (imageData.isEmpty()) throw new RuntimeException("ImageSet already created.");
return new ImageSet(imageFormat, imageDimensions, mipmapCount, arrayCount, faceCount, imageData, imageSizes);
}
////////////////////////////////
private ImageFormat imageFormat;
private Dimensions imageDimensions;
private int mipmapCount;
private int arrayCount;
private int faceCount;
private ArrayList<byte[]> imageData;
private int[] imageSizes;
////////////////////////////////
private void copyImageFlipped(byte[] sourceData, byte[] imageData, int imageDataOffset, int mipmapLevel) {
assert (sourceData.length * faceCount * arrayCount) == imageData.length;
Dimensions mipmapImageDimensions = Util.calcMipmapLevelDimensions(new Dimensions(imageDimensions), mipmapLevel);
| if (imageFormat.getPixelDataType().ordinal() < PixelDataType.NUM_UNCOMPRESSED_TYPES.ordinal()) { |
integeruser/jgltut | src/integeruser/jglsdk/glimg/ImageCreator.java | // Path: src/integeruser/jglsdk/glimg/ImageFormat.java
// enum PixelDataType {
// NORM_UNSIGNED_INTEGER, // Image data are unsigned integers that are mapped to floats on the range [0, 1].
// NORM_SIGNED_INTEGER, // Image data are signed integers that are mapped to floats on the range [-1, 1].
// UNSIGNED_INTEGRAL, // Image data are unsigned integers.
// SIGNED_INTEGRAL, // Image data are signed integers.
// FLOAT, // Image data are individual floating-point numbers.
// SHARED_EXP_FLOAT, // Image data are floats, but each pixel uses the same exponent.
// NUM_UNCOMPRESSED_TYPES,
//
// COMPRESSED_BC1, // Image data is compressed with DXT1/BC1 compression. Unsigned normalized integers.
// COMPRESSED_BC2, // Image data is compressed with DXT3/BC2 compression. Unsigned normalized integers.
// COMPRESSED_BC3, // Image data is compressed with DXT5/BC3 compression. Unsigned normalized integers.
// COMPRESSED_UNSIGNED_BC4, // Image is compressed with BC4 compression (1-component), with unsigned normalized integers.
// COMPRESSED_SIGNED_BC4, // Image is compressed with BC4 compression (1-component), with signed normalized integers.
// COMPRESSED_UNSIGNED_BC5, // Image is compressed with BC5 compression (2-component), with unsigned normalized integers.
// COMPRESSED_SIGNED_BC5, // Image is compressed with BC5 compression (2-component), with signed normalized integers.
// COMPRESSED_UNSIGNED_BC6H, // Image is compressed with BC6H compression, with unsigned floats [0, +inf).
// COMPRESSED_SIGNED_BC6H, // Image is compressed with BC6H compression, with floats.
// COMPRESSED_BC7, // Image data is compressed with BC7 compression. Unsigned normalized integers.
//
// NUM_TYPES
// }
//
// Path: src/integeruser/jglsdk/glimg/ImageSet.java
// public static class Dimensions {
// public int numDimensions; // The number of dimensions of an image. Can be 1, 2, or 3.
// public int width; // The width of the image. Always valid.
// public int height; // The height of the image. Only valid if numDimensions is 2 or 3.
// public int depth; // The depth of the image. Only valid if numDimensions is 3.
//
// ////////////////////////////////
// public Dimensions() {
// }
//
// public Dimensions(Dimensions dimensions) {
// numDimensions = dimensions.numDimensions;
// width = dimensions.width;
// height = dimensions.height;
// depth = dimensions.depth;
// }
//
// ////////////////////////////////
// // Computes the number of rows of pixel data in the image.
// public int calcNumLines() {
// switch (numDimensions) {
// case 1:
// return 1;
//
// case 2:
// return height;
//
// case 3:
// return depth * height;
// }
// // Should not be possible.
// return -1;
// }
// }
//
// Path: src/integeruser/jglsdk/glimg/Util.java
// static class CompressedBlockData {
// Dimensions dimensions; // The dimensionality of a block.
// int byteCount; // Number of bytes in a block.
// }
| import integeruser.jglsdk.glimg.ImageFormat.PixelDataType;
import integeruser.jglsdk.glimg.ImageSet.Dimensions;
import integeruser.jglsdk.glimg.Util.CompressedBlockData;
import java.util.ArrayList;
import java.util.Arrays; | }
}
private void copyPixelsFlipped(ImageFormat imageFormat, byte[] sourceData, byte[] imageData, int imageDataOffset,
int imageSize, Dimensions imageDimensions) {
// Flip the data. Copy line by line.
final int numLines = imageDimensions.calcNumLines();
final int lineSize = imageFormat.alignByteCount(Util.calcBytesPerPixel(imageFormat) * imageDimensions.width);
// Flipped: start from last line of source, going backward
int sourceLineOffset = imageSize - lineSize; // start from last line
int imageDataLineOffset = imageDataOffset; // start from imageDataOffset
for (int line = 0; line < numLines; line++) {
byte[] sourceLine = Arrays.copyOfRange(sourceData, sourceLineOffset, sourceLineOffset + lineSize);
// Copy the source line into imageData
System.arraycopy(sourceLine, 0, imageData, imageDataLineOffset, lineSize);
// Update indices
sourceLineOffset -= lineSize;
imageDataLineOffset += lineSize;
}
}
private void copyBCFlipped(ImageFormat imageFormat, byte[] sourceData, byte[] imageData, int imageDataOffset,
int imageSize, Dimensions imageDimensions, FlippingFunc flippingFunc) {
// No support for 3D compressed formats.
assert imageDimensions.numDimensions != 3 : "No support for 3D compressed formats.";
| // Path: src/integeruser/jglsdk/glimg/ImageFormat.java
// enum PixelDataType {
// NORM_UNSIGNED_INTEGER, // Image data are unsigned integers that are mapped to floats on the range [0, 1].
// NORM_SIGNED_INTEGER, // Image data are signed integers that are mapped to floats on the range [-1, 1].
// UNSIGNED_INTEGRAL, // Image data are unsigned integers.
// SIGNED_INTEGRAL, // Image data are signed integers.
// FLOAT, // Image data are individual floating-point numbers.
// SHARED_EXP_FLOAT, // Image data are floats, but each pixel uses the same exponent.
// NUM_UNCOMPRESSED_TYPES,
//
// COMPRESSED_BC1, // Image data is compressed with DXT1/BC1 compression. Unsigned normalized integers.
// COMPRESSED_BC2, // Image data is compressed with DXT3/BC2 compression. Unsigned normalized integers.
// COMPRESSED_BC3, // Image data is compressed with DXT5/BC3 compression. Unsigned normalized integers.
// COMPRESSED_UNSIGNED_BC4, // Image is compressed with BC4 compression (1-component), with unsigned normalized integers.
// COMPRESSED_SIGNED_BC4, // Image is compressed with BC4 compression (1-component), with signed normalized integers.
// COMPRESSED_UNSIGNED_BC5, // Image is compressed with BC5 compression (2-component), with unsigned normalized integers.
// COMPRESSED_SIGNED_BC5, // Image is compressed with BC5 compression (2-component), with signed normalized integers.
// COMPRESSED_UNSIGNED_BC6H, // Image is compressed with BC6H compression, with unsigned floats [0, +inf).
// COMPRESSED_SIGNED_BC6H, // Image is compressed with BC6H compression, with floats.
// COMPRESSED_BC7, // Image data is compressed with BC7 compression. Unsigned normalized integers.
//
// NUM_TYPES
// }
//
// Path: src/integeruser/jglsdk/glimg/ImageSet.java
// public static class Dimensions {
// public int numDimensions; // The number of dimensions of an image. Can be 1, 2, or 3.
// public int width; // The width of the image. Always valid.
// public int height; // The height of the image. Only valid if numDimensions is 2 or 3.
// public int depth; // The depth of the image. Only valid if numDimensions is 3.
//
// ////////////////////////////////
// public Dimensions() {
// }
//
// public Dimensions(Dimensions dimensions) {
// numDimensions = dimensions.numDimensions;
// width = dimensions.width;
// height = dimensions.height;
// depth = dimensions.depth;
// }
//
// ////////////////////////////////
// // Computes the number of rows of pixel data in the image.
// public int calcNumLines() {
// switch (numDimensions) {
// case 1:
// return 1;
//
// case 2:
// return height;
//
// case 3:
// return depth * height;
// }
// // Should not be possible.
// return -1;
// }
// }
//
// Path: src/integeruser/jglsdk/glimg/Util.java
// static class CompressedBlockData {
// Dimensions dimensions; // The dimensionality of a block.
// int byteCount; // Number of bytes in a block.
// }
// Path: src/integeruser/jglsdk/glimg/ImageCreator.java
import integeruser.jglsdk.glimg.ImageFormat.PixelDataType;
import integeruser.jglsdk.glimg.ImageSet.Dimensions;
import integeruser.jglsdk.glimg.Util.CompressedBlockData;
import java.util.ArrayList;
import java.util.Arrays;
}
}
private void copyPixelsFlipped(ImageFormat imageFormat, byte[] sourceData, byte[] imageData, int imageDataOffset,
int imageSize, Dimensions imageDimensions) {
// Flip the data. Copy line by line.
final int numLines = imageDimensions.calcNumLines();
final int lineSize = imageFormat.alignByteCount(Util.calcBytesPerPixel(imageFormat) * imageDimensions.width);
// Flipped: start from last line of source, going backward
int sourceLineOffset = imageSize - lineSize; // start from last line
int imageDataLineOffset = imageDataOffset; // start from imageDataOffset
for (int line = 0; line < numLines; line++) {
byte[] sourceLine = Arrays.copyOfRange(sourceData, sourceLineOffset, sourceLineOffset + lineSize);
// Copy the source line into imageData
System.arraycopy(sourceLine, 0, imageData, imageDataLineOffset, lineSize);
// Update indices
sourceLineOffset -= lineSize;
imageDataLineOffset += lineSize;
}
}
private void copyBCFlipped(ImageFormat imageFormat, byte[] sourceData, byte[] imageData, int imageDataOffset,
int imageSize, Dimensions imageDimensions, FlippingFunc flippingFunc) {
// No support for 3D compressed formats.
assert imageDimensions.numDimensions != 3 : "No support for 3D compressed formats.";
| CompressedBlockData blockData = Util.getBlockCompressionData(imageFormat.getPixelDataType()); |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/data/DefaultSurgebindingData.java | // Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
// public enum Order {
// WINDRUNNERS(ADHESION, GRAVITATION),
// SKYBREAKERS(GRAVITATION, DIVISION),
// DUSTBRINGERS(DIVISION, ABRASION),
// EDGEDANCERS(ABRASION, PROGRESSION),
// TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
// LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
// ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
// WILLSHAPERS(TRANSPORTATION, COHESION),
// STONEWARDS(COHESION, TENSION),
// BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
//
//
// private final Surge first;
// private final Surge second;
// private final Ideal blade_gate;
// private final Ideal first_gate;
// private final Ideal second_gate;
//
// Order(Surge fst, Surge snd) {
// this(fst, snd, FIRST, FIRST, FIRST);
// }
//
// Order(Surge fst, Surge snd, Ideal blade, Ideal first, Ideal second) {
// this.first = fst;
// this.second = snd;
// this.blade_gate = blade;
// this.first_gate = first;
// this.second_gate = second;
// }
//
// public static Order getOrNull(int index) {
// for (Order order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// return null;
// }
//
// public Surge getFirst() {
// return first;
// }
//
// public Surge getSecond() {
// return second;
// }
//
// public Ideal getFirstIdeal() {return first_gate;}
//
// public Ideal getSecondIdeal() {return second_gate;}
//
// public Ideal getBladeIdeal() {return blade_gate;}
//
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public String getSingularName() {
// String name = this.getName();
// return name.substring(0, name.length() - 1);
// }
//
// public int getIndex() {
// return ordinal();
// }
//
// public boolean hasSurge(Surge surge) {
// return first == surge || second == surge;
// }
// }
| import com.legobmw99.stormlight.api.ISurgebindingData;
import com.legobmw99.stormlight.util.Ideal;
import com.legobmw99.stormlight.util.Order;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.UUID; | package com.legobmw99.stormlight.modules.powers.data;
public class DefaultSurgebindingData implements ISurgebindingData {
private Order order; | // Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
// public enum Order {
// WINDRUNNERS(ADHESION, GRAVITATION),
// SKYBREAKERS(GRAVITATION, DIVISION),
// DUSTBRINGERS(DIVISION, ABRASION),
// EDGEDANCERS(ABRASION, PROGRESSION),
// TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
// LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
// ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
// WILLSHAPERS(TRANSPORTATION, COHESION),
// STONEWARDS(COHESION, TENSION),
// BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
//
//
// private final Surge first;
// private final Surge second;
// private final Ideal blade_gate;
// private final Ideal first_gate;
// private final Ideal second_gate;
//
// Order(Surge fst, Surge snd) {
// this(fst, snd, FIRST, FIRST, FIRST);
// }
//
// Order(Surge fst, Surge snd, Ideal blade, Ideal first, Ideal second) {
// this.first = fst;
// this.second = snd;
// this.blade_gate = blade;
// this.first_gate = first;
// this.second_gate = second;
// }
//
// public static Order getOrNull(int index) {
// for (Order order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// return null;
// }
//
// public Surge getFirst() {
// return first;
// }
//
// public Surge getSecond() {
// return second;
// }
//
// public Ideal getFirstIdeal() {return first_gate;}
//
// public Ideal getSecondIdeal() {return second_gate;}
//
// public Ideal getBladeIdeal() {return blade_gate;}
//
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public String getSingularName() {
// String name = this.getName();
// return name.substring(0, name.length() - 1);
// }
//
// public int getIndex() {
// return ordinal();
// }
//
// public boolean hasSurge(Surge surge) {
// return first == surge || second == surge;
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/DefaultSurgebindingData.java
import com.legobmw99.stormlight.api.ISurgebindingData;
import com.legobmw99.stormlight.util.Ideal;
import com.legobmw99.stormlight.util.Order;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.UUID;
package com.legobmw99.stormlight.modules.powers.data;
public class DefaultSurgebindingData implements ISurgebindingData {
private Order order; | private Ideal ideal; |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/network/packets/SurgebindingDataPacket.java | // Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
//
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
// public class SurgebindingCapability {
//
// public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
// });
//
// public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data");
//
//
// public static void registerCapability(final RegisterCapabilitiesEvent event) {
// event.register(ISurgebindingData.class);
// }
//
// }
| import com.legobmw99.stormlight.api.ISurgebindingData;
import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkEvent;
import java.util.UUID;
import java.util.function.Supplier; | package com.legobmw99.stormlight.network.packets;
public class SurgebindingDataPacket {
private final CompoundTag nbt;
private final UUID uuid;
| // Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
//
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
// public class SurgebindingCapability {
//
// public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
// });
//
// public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data");
//
//
// public static void registerCapability(final RegisterCapabilitiesEvent event) {
// event.register(ISurgebindingData.class);
// }
//
// }
// Path: src/main/java/com/legobmw99/stormlight/network/packets/SurgebindingDataPacket.java
import com.legobmw99.stormlight.api.ISurgebindingData;
import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkEvent;
import java.util.UUID;
import java.util.function.Supplier;
package com.legobmw99.stormlight.network.packets;
public class SurgebindingDataPacket {
private final CompoundTag nbt;
private final UUID uuid;
| public SurgebindingDataPacket(ISurgebindingData data, Player player) { |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/network/packets/SurgebindingDataPacket.java | // Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
//
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
// public class SurgebindingCapability {
//
// public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
// });
//
// public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data");
//
//
// public static void registerCapability(final RegisterCapabilitiesEvent event) {
// event.register(ISurgebindingData.class);
// }
//
// }
| import com.legobmw99.stormlight.api.ISurgebindingData;
import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkEvent;
import java.util.UUID;
import java.util.function.Supplier; | package com.legobmw99.stormlight.network.packets;
public class SurgebindingDataPacket {
private final CompoundTag nbt;
private final UUID uuid;
public SurgebindingDataPacket(ISurgebindingData data, Player player) {
this.uuid = player.getUUID();
this.nbt = (data != null) ? data.save() : new CompoundTag();
}
private SurgebindingDataPacket(CompoundTag data, UUID uuid) {
this.nbt = data;
this.uuid = uuid;
}
public static SurgebindingDataPacket decode(FriendlyByteBuf buf) {
return new SurgebindingDataPacket(buf.readNbt(), buf.readUUID());
}
public void encode(FriendlyByteBuf buf) {
buf.writeNbt(this.nbt);
buf.writeUUID(this.uuid);
}
public void handle(Supplier<NetworkEvent.Context> ctx) {
ctx.get().enqueueWork(() -> {
Player player = Minecraft.getInstance().level.getPlayerByUUID(this.uuid); | // Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
//
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
// public class SurgebindingCapability {
//
// public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
// });
//
// public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data");
//
//
// public static void registerCapability(final RegisterCapabilitiesEvent event) {
// event.register(ISurgebindingData.class);
// }
//
// }
// Path: src/main/java/com/legobmw99/stormlight/network/packets/SurgebindingDataPacket.java
import com.legobmw99.stormlight.api.ISurgebindingData;
import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.network.NetworkEvent;
import java.util.UUID;
import java.util.function.Supplier;
package com.legobmw99.stormlight.network.packets;
public class SurgebindingDataPacket {
private final CompoundTag nbt;
private final UUID uuid;
public SurgebindingDataPacket(ISurgebindingData data, Player player) {
this.uuid = player.getUUID();
this.nbt = (data != null) ? data.save() : new CompoundTag();
}
private SurgebindingDataPacket(CompoundTag data, UUID uuid) {
this.nbt = data;
this.uuid = uuid;
}
public static SurgebindingDataPacket decode(FriendlyByteBuf buf) {
return new SurgebindingDataPacket(buf.readNbt(), buf.readUUID());
}
public void encode(FriendlyByteBuf buf) {
buf.writeNbt(this.nbt);
buf.writeUUID(this.uuid);
}
public void handle(Supplier<NetworkEvent.Context> ctx) {
ctx.get().enqueueWork(() -> {
Player player = Minecraft.getInstance().level.getPlayerByUUID(this.uuid); | if (player != null && SurgebindingCapability.PLAYER_CAP != null) { |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/container/PortableCraftingContainer.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.CraftingMenu; | package com.legobmw99.stormlight.modules.powers.container;
public class PortableCraftingContainer extends CraftingMenu {
public PortableCraftingContainer(int p_i50089_1_, Inventory p_i50089_2_) {
super(p_i50089_1_, p_i50089_2_);
}
@Override
public boolean stillValid(Player player) { | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/container/PortableCraftingContainer.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.CraftingMenu;
package com.legobmw99.stormlight.modules.powers.container;
public class PortableCraftingContainer extends CraftingMenu {
public PortableCraftingContainer(int p_i50089_1_, Inventory p_i50089_2_) {
super(p_i50089_1_, p_i50089_2_);
}
@Override
public boolean stillValid(Player player) { | return player.hasEffect(PowersSetup.STORMLIGHT.get()); |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/mixin/AbstractBlockstateMixin.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.EntityCollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; | package com.legobmw99.stormlight.modules.powers.mixin;
/**
* Primarily handles the Cohesion effect of phasing through blocks. Inspired by Origins
*/
@Mixin(BlockBehaviour.BlockStateBase.class)
public abstract class AbstractBlockstateMixin {
@Shadow(remap = false)
public abstract Block getBlock();
@Shadow(remap = false)
protected abstract BlockState asState();
@Inject(at = @At("HEAD"), method = "getCollisionShape(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/phys/shapes/CollisionContext;)Lnet/minecraft/world/phys/shapes/VoxelShape;", cancellable = true, remap = false)
private void noClip(BlockGetter world, BlockPos pos, CollisionContext context, CallbackInfoReturnable<VoxelShape> info) {
if (context instanceof EntityCollisionContext ectx) {
Entity entity = ectx.getEntity(); | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/mixin/AbstractBlockstateMixin.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.EntityCollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
package com.legobmw99.stormlight.modules.powers.mixin;
/**
* Primarily handles the Cohesion effect of phasing through blocks. Inspired by Origins
*/
@Mixin(BlockBehaviour.BlockStateBase.class)
public abstract class AbstractBlockstateMixin {
@Shadow(remap = false)
public abstract Block getBlock();
@Shadow(remap = false)
protected abstract BlockState asState();
@Inject(at = @At("HEAD"), method = "getCollisionShape(Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/phys/shapes/CollisionContext;)Lnet/minecraft/world/phys/shapes/VoxelShape;", cancellable = true, remap = false)
private void noClip(BlockGetter world, BlockPos pos, CollisionContext context, CallbackInfoReturnable<VoxelShape> info) {
if (context instanceof EntityCollisionContext ectx) {
Entity entity = ectx.getEntity(); | if (entity instanceof LivingEntity && ((LivingEntity) entity).hasEffect(PowersSetup.COHESION.get())) { |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java | // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
// public enum Order {
// WINDRUNNERS(ADHESION, GRAVITATION),
// SKYBREAKERS(GRAVITATION, DIVISION),
// DUSTBRINGERS(DIVISION, ABRASION),
// EDGEDANCERS(ABRASION, PROGRESSION),
// TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
// LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
// ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
// WILLSHAPERS(TRANSPORTATION, COHESION),
// STONEWARDS(COHESION, TENSION),
// BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
//
//
// private final Surge first;
// private final Surge second;
// private final Ideal blade_gate;
// private final Ideal first_gate;
// private final Ideal second_gate;
//
// Order(Surge fst, Surge snd) {
// this(fst, snd, FIRST, FIRST, FIRST);
// }
//
// Order(Surge fst, Surge snd, Ideal blade, Ideal first, Ideal second) {
// this.first = fst;
// this.second = snd;
// this.blade_gate = blade;
// this.first_gate = first;
// this.second_gate = second;
// }
//
// public static Order getOrNull(int index) {
// for (Order order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// return null;
// }
//
// public Surge getFirst() {
// return first;
// }
//
// public Surge getSecond() {
// return second;
// }
//
// public Ideal getFirstIdeal() {return first_gate;}
//
// public Ideal getSecondIdeal() {return second_gate;}
//
// public Ideal getBladeIdeal() {return blade_gate;}
//
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public String getSingularName() {
// String name = this.getName();
// return name.substring(0, name.length() - 1);
// }
//
// public int getIndex() {
// return ordinal();
// }
//
// public boolean hasSurge(Surge surge) {
// return first == surge || second == surge;
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
| import com.legobmw99.stormlight.util.Ideal;
import com.legobmw99.stormlight.util.Order;
import com.legobmw99.stormlight.util.Surge;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.UUID; | package com.legobmw99.stormlight.api;
public interface ISurgebindingData {
@Nullable | // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
// public enum Order {
// WINDRUNNERS(ADHESION, GRAVITATION),
// SKYBREAKERS(GRAVITATION, DIVISION),
// DUSTBRINGERS(DIVISION, ABRASION),
// EDGEDANCERS(ABRASION, PROGRESSION),
// TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
// LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
// ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
// WILLSHAPERS(TRANSPORTATION, COHESION),
// STONEWARDS(COHESION, TENSION),
// BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
//
//
// private final Surge first;
// private final Surge second;
// private final Ideal blade_gate;
// private final Ideal first_gate;
// private final Ideal second_gate;
//
// Order(Surge fst, Surge snd) {
// this(fst, snd, FIRST, FIRST, FIRST);
// }
//
// Order(Surge fst, Surge snd, Ideal blade, Ideal first, Ideal second) {
// this.first = fst;
// this.second = snd;
// this.blade_gate = blade;
// this.first_gate = first;
// this.second_gate = second;
// }
//
// public static Order getOrNull(int index) {
// for (Order order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// return null;
// }
//
// public Surge getFirst() {
// return first;
// }
//
// public Surge getSecond() {
// return second;
// }
//
// public Ideal getFirstIdeal() {return first_gate;}
//
// public Ideal getSecondIdeal() {return second_gate;}
//
// public Ideal getBladeIdeal() {return blade_gate;}
//
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public String getSingularName() {
// String name = this.getName();
// return name.substring(0, name.length() - 1);
// }
//
// public int getIndex() {
// return ordinal();
// }
//
// public boolean hasSurge(Surge surge) {
// return first == surge || second == surge;
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
// Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
import com.legobmw99.stormlight.util.Ideal;
import com.legobmw99.stormlight.util.Order;
import com.legobmw99.stormlight.util.Surge;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.UUID;
package com.legobmw99.stormlight.api;
public interface ISurgebindingData {
@Nullable | Order getOrder(); |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java | // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
// public enum Order {
// WINDRUNNERS(ADHESION, GRAVITATION),
// SKYBREAKERS(GRAVITATION, DIVISION),
// DUSTBRINGERS(DIVISION, ABRASION),
// EDGEDANCERS(ABRASION, PROGRESSION),
// TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
// LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
// ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
// WILLSHAPERS(TRANSPORTATION, COHESION),
// STONEWARDS(COHESION, TENSION),
// BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
//
//
// private final Surge first;
// private final Surge second;
// private final Ideal blade_gate;
// private final Ideal first_gate;
// private final Ideal second_gate;
//
// Order(Surge fst, Surge snd) {
// this(fst, snd, FIRST, FIRST, FIRST);
// }
//
// Order(Surge fst, Surge snd, Ideal blade, Ideal first, Ideal second) {
// this.first = fst;
// this.second = snd;
// this.blade_gate = blade;
// this.first_gate = first;
// this.second_gate = second;
// }
//
// public static Order getOrNull(int index) {
// for (Order order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// return null;
// }
//
// public Surge getFirst() {
// return first;
// }
//
// public Surge getSecond() {
// return second;
// }
//
// public Ideal getFirstIdeal() {return first_gate;}
//
// public Ideal getSecondIdeal() {return second_gate;}
//
// public Ideal getBladeIdeal() {return blade_gate;}
//
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public String getSingularName() {
// String name = this.getName();
// return name.substring(0, name.length() - 1);
// }
//
// public int getIndex() {
// return ordinal();
// }
//
// public boolean hasSurge(Surge surge) {
// return first == surge || second == surge;
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
| import com.legobmw99.stormlight.util.Ideal;
import com.legobmw99.stormlight.util.Order;
import com.legobmw99.stormlight.util.Surge;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.UUID; | package com.legobmw99.stormlight.api;
public interface ISurgebindingData {
@Nullable
Order getOrder();
void setOrder(Order order);
| // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
// public enum Order {
// WINDRUNNERS(ADHESION, GRAVITATION),
// SKYBREAKERS(GRAVITATION, DIVISION),
// DUSTBRINGERS(DIVISION, ABRASION),
// EDGEDANCERS(ABRASION, PROGRESSION),
// TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
// LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
// ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
// WILLSHAPERS(TRANSPORTATION, COHESION),
// STONEWARDS(COHESION, TENSION),
// BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
//
//
// private final Surge first;
// private final Surge second;
// private final Ideal blade_gate;
// private final Ideal first_gate;
// private final Ideal second_gate;
//
// Order(Surge fst, Surge snd) {
// this(fst, snd, FIRST, FIRST, FIRST);
// }
//
// Order(Surge fst, Surge snd, Ideal blade, Ideal first, Ideal second) {
// this.first = fst;
// this.second = snd;
// this.blade_gate = blade;
// this.first_gate = first;
// this.second_gate = second;
// }
//
// public static Order getOrNull(int index) {
// for (Order order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// return null;
// }
//
// public Surge getFirst() {
// return first;
// }
//
// public Surge getSecond() {
// return second;
// }
//
// public Ideal getFirstIdeal() {return first_gate;}
//
// public Ideal getSecondIdeal() {return second_gate;}
//
// public Ideal getBladeIdeal() {return blade_gate;}
//
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public String getSingularName() {
// String name = this.getName();
// return name.substring(0, name.length() - 1);
// }
//
// public int getIndex() {
// return ordinal();
// }
//
// public boolean hasSurge(Surge surge) {
// return first == surge || second == surge;
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
// Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
import com.legobmw99.stormlight.util.Ideal;
import com.legobmw99.stormlight.util.Order;
import com.legobmw99.stormlight.util.Surge;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.UUID;
package com.legobmw99.stormlight.api;
public interface ISurgebindingData {
@Nullable
Order getOrder();
void setOrder(Order order);
| Ideal getIdeal(); |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/mixin/IForgeBlockStateMixin.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.extensions.IForgeBlockState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import javax.annotation.Nullable; | package com.legobmw99.stormlight.modules.powers.mixin;
@Mixin(IForgeBlockState.class)
public interface IForgeBlockStateMixin {
@Shadow(remap = false)
private BlockState self() {
return null;
}
/**
* Add stormlight mod checks for slipperiness
*
* @author legobmw99
* @reason unable to inject into default interface method
*/
@Overwrite(remap = false)
default float getFriction(LevelReader world, BlockPos pos, @Nullable Entity entity) { | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/mixin/IForgeBlockStateMixin.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.common.extensions.IForgeBlockState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import javax.annotation.Nullable;
package com.legobmw99.stormlight.modules.powers.mixin;
@Mixin(IForgeBlockState.class)
public interface IForgeBlockStateMixin {
@Shadow(remap = false)
private BlockState self() {
return null;
}
/**
* Add stormlight mod checks for slipperiness
*
* @author legobmw99
* @reason unable to inject into default interface method
*/
@Overwrite(remap = false)
default float getFriction(LevelReader world, BlockPos pos, @Nullable Entity entity) { | if (entity instanceof LivingEntity p && p.hasEffect(PowersSetup.SLICKING.get())) { |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/effect/StormlightEffect.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.world.effect.MobEffectCategory;
import net.minecraft.world.entity.LivingEntity; | package com.legobmw99.stormlight.modules.powers.effect;
public class StormlightEffect extends GenericEffect {
public StormlightEffect(int color) {
super(MobEffectCategory.BENEFICIAL, color);
}
@Override
public void applyEffectTick(LivingEntity entity, int amplifier) { | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/effect/StormlightEffect.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.world.effect.MobEffectCategory;
import net.minecraft.world.entity.LivingEntity;
package com.legobmw99.stormlight.modules.powers.effect;
public class StormlightEffect extends GenericEffect {
public StormlightEffect(int color) {
super(MobEffectCategory.BENEFICIAL, color);
}
@Override
public void applyEffectTick(LivingEntity entity, int amplifier) { | if (!entity.hasEffect(PowersSetup.STORMLIGHT.get())) { |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/mixin/LivingEntityMixin.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.material.Fluid;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Optional; | package com.legobmw99.stormlight.modules.powers.mixin;
@Mixin(LivingEntity.class)
public abstract class LivingEntityMixin extends Entity {
@Shadow(remap = false)
private Optional<BlockPos> lastClimbablePos;
public LivingEntityMixin(EntityType<?> type, Level world) {
super(type, world);
}
// todo actually mixin to IForgeBlockState?
@Inject(at = @At("RETURN"), method = "onClimbable", cancellable = true, remap = false)
public void doCohesionClimb(CallbackInfoReturnable<Boolean> info) {
if (!info.getReturnValue()) {
LivingEntity entity = (LivingEntity) (Entity) this; | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/mixin/LivingEntityMixin.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.material.Fluid;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Optional;
package com.legobmw99.stormlight.modules.powers.mixin;
@Mixin(LivingEntity.class)
public abstract class LivingEntityMixin extends Entity {
@Shadow(remap = false)
private Optional<BlockPos> lastClimbablePos;
public LivingEntityMixin(EntityType<?> type, Level world) {
super(type, world);
}
// todo actually mixin to IForgeBlockState?
@Inject(at = @At("RETURN"), method = "onClimbable", cancellable = true, remap = false)
public void doCohesionClimb(CallbackInfoReturnable<Boolean> info) {
if (!info.getReturnValue()) {
LivingEntity entity = (LivingEntity) (Entity) this; | if (entity.hasEffect(PowersSetup.STICKING.get()) && entity.level.getBlockCollisions(entity, entity.getBoundingBox().inflate(0.15, 0, 0.15)).iterator().hasNext()) { |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/container/PortableStonecutterContainer.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.StonecutterMenu; | package com.legobmw99.stormlight.modules.powers.container;
public class PortableStonecutterContainer extends StonecutterMenu {
public PortableStonecutterContainer(int p_i50060_1_, Inventory p_i50060_2_) {
super(p_i50060_1_, p_i50060_2_);
}
@Override
public boolean stillValid(Player player) { | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/container/PortableStonecutterContainer.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.StonecutterMenu;
package com.legobmw99.stormlight.modules.powers.container;
public class PortableStonecutterContainer extends StonecutterMenu {
public PortableStonecutterContainer(int p_i50060_1_, Inventory p_i50060_2_) {
super(p_i50060_1_, p_i50060_2_);
}
@Override
public boolean stillValid(Player player) { | return player.hasEffect(PowersSetup.STORMLIGHT.get()); |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/client/PowerClientEventHandler.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.LiquidBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.event.InputEvent;
import net.minecraftforge.client.event.RenderLevelLastEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors; | package com.legobmw99.stormlight.modules.powers.client;
@OnlyIn(Dist.CLIENT)
public class PowerClientEventHandler {
private static final Minecraft mc = Minecraft.getInstance();
private static final Map<BlockPos, BlockState> savedStates = new HashMap<>();
@SubscribeEvent
public static void onKeyInput(final InputEvent.KeyInputEvent event) {
if (event.getKey() == PowersClientSetup.firstSurge.getKey().getValue() || event.getKey() == PowersClientSetup.secondSurge.getKey().getValue() ||
event.getKey() == PowersClientSetup.blade.getKey().getValue()) {
ClientPowerUtils.acceptInput(event.getAction());
}
}
@SubscribeEvent
public static void onMouseInput(final InputEvent.MouseInputEvent event) {
// todo investigate
// ClientPowerUtils.acceptInput(event.getAction());
}
// Heavily inspired by Origins, but not a mixin
@SubscribeEvent
public static void renderLast(final RenderLevelLastEvent event) {
| // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/client/PowerClientEventHandler.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.LiquidBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.event.InputEvent;
import net.minecraftforge.client.event.RenderLevelLastEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
package com.legobmw99.stormlight.modules.powers.client;
@OnlyIn(Dist.CLIENT)
public class PowerClientEventHandler {
private static final Minecraft mc = Minecraft.getInstance();
private static final Map<BlockPos, BlockState> savedStates = new HashMap<>();
@SubscribeEvent
public static void onKeyInput(final InputEvent.KeyInputEvent event) {
if (event.getKey() == PowersClientSetup.firstSurge.getKey().getValue() || event.getKey() == PowersClientSetup.secondSurge.getKey().getValue() ||
event.getKey() == PowersClientSetup.blade.getKey().getValue()) {
ClientPowerUtils.acceptInput(event.getAction());
}
}
@SubscribeEvent
public static void onMouseInput(final InputEvent.MouseInputEvent event) {
// todo investigate
// ClientPowerUtils.acceptInput(event.getAction());
}
// Heavily inspired by Origins, but not a mixin
@SubscribeEvent
public static void renderLast(final RenderLevelLastEvent event) {
| if (mc.player != null && mc.player.hasEffect(PowersSetup.COHESION.get())) { |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingDataProvider.java | // Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
| import com.legobmw99.stormlight.api.ISurgebindingData;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable; | package com.legobmw99.stormlight.modules.powers.data;
public class SurgebindingDataProvider implements ICapabilitySerializable<CompoundTag> {
private final DefaultSurgebindingData data = new DefaultSurgebindingData(); | // Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingDataProvider.java
import com.legobmw99.stormlight.api.ISurgebindingData;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.common.util.LazyOptional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
package com.legobmw99.stormlight.modules.powers.data;
public class SurgebindingDataProvider implements ICapabilitySerializable<CompoundTag> {
private final DefaultSurgebindingData data = new DefaultSurgebindingData(); | private final LazyOptional<ISurgebindingData> dataOptional = LazyOptional.of(() -> this.data); |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/effect/EffectHelper.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player; | if (player.hasEffect(effect)) {
player.removeEffect(effect);
return false;
} else {
player.addEffect(new MobEffectInstance(effect, MAX_TIME, level, ambient, false, showicon));
return true;
}
}
public static int increasePermanentEffect(Player player, MobEffect effect, int max) {
int level = player.hasEffect(effect) ? player.getEffect(effect).getAmplifier() : -1;
level = level < max ? level + 1 : max;
player.addEffect(new MobEffectInstance(effect, MAX_TIME, level, true, false, true));
return level;
}
public static int decreasePermanentEffect(Player player, MobEffect effect) {
if (!player.hasEffect(effect)) {
return -1;
}
int level = player.getEffect(effect).getAmplifier() - 1;
player.removeEffect(effect);
if (level >= 0) {
player.addEffect(new MobEffectInstance(effect, MAX_TIME, level, true, false, true));
}
return level;
}
public static boolean drainStormlight(LivingEntity entity, int duration) { | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/effect/EffectHelper.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
if (player.hasEffect(effect)) {
player.removeEffect(effect);
return false;
} else {
player.addEffect(new MobEffectInstance(effect, MAX_TIME, level, ambient, false, showicon));
return true;
}
}
public static int increasePermanentEffect(Player player, MobEffect effect, int max) {
int level = player.hasEffect(effect) ? player.getEffect(effect).getAmplifier() : -1;
level = level < max ? level + 1 : max;
player.addEffect(new MobEffectInstance(effect, MAX_TIME, level, true, false, true));
return level;
}
public static int decreasePermanentEffect(Player player, MobEffect effect) {
if (!player.hasEffect(effect)) {
return -1;
}
int level = player.getEffect(effect).getAmplifier() - 1;
player.removeEffect(effect);
if (level >= 0) {
player.addEffect(new MobEffectInstance(effect, MAX_TIME, level, true, false, true));
}
return level;
}
public static boolean drainStormlight(LivingEntity entity, int duration) { | MobEffect stormlight = PowersSetup.STORMLIGHT.get(); |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java | // Path: src/main/java/com/legobmw99/stormlight/Stormlight.java
// @Mod(Stormlight.MODID)
// public class Stormlight {
// public static final String MODID = "stormlight";
// public static final Logger LOGGER = LogManager.getLogger();
//
// public static final CreativeModeTab stormlight_group = new CreativeModeTab(Stormlight.MODID) {
// @Override
// public ItemStack makeIcon() {
// int type = (int) (System.currentTimeMillis() / (1000 * 60)) % 10;
// return new ItemStack(CombatSetup.SHARDBLADES.get(type).get());
// }
// };
//
// public static Stormlight instance;
//
// public Stormlight() {
// instance = this;
// FMLJavaModLoadingContext.get().getModEventBus().addListener(Stormlight::init);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(Stormlight::clientInit);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(EntityType.class, WorldSetup::onEntityRegister);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(WorldSetup::onEntityAttribute);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(SurgebindingCapability::registerCapability);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(WorldSetup::registerEntityModels);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(WorldSetup::registerEntityRenders);
// MinecraftForge.EVENT_BUS.addListener(Stormlight::registerCommands);
//
// PowersSetup.register();
// WorldSetup.register();
// CombatSetup.register();
// }
//
// public static Item.Properties createStandardItemProperties() {
// return new Item.Properties().tab(stormlight_group).stacksTo(64);
// }
//
// public static void clientInit(final FMLClientSetupEvent e) {
// PowersClientSetup.clientInit(e);
// WorldSetup.clientInit(e);
// CombatSetup.clientInit(e);
// }
//
// public static void registerCommands(final RegisterCommandsEvent e) {
// StormlightCommand.register(e.getDispatcher());
// }
//
// public static void init(final FMLCommonSetupEvent e) {
// PowersSetup.init(e);
// Network.registerPackets();
// }
//
//
// }
//
// Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
| import com.legobmw99.stormlight.Stormlight;
import com.legobmw99.stormlight.api.ISurgebindingData;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; | package com.legobmw99.stormlight.modules.powers.data;
public class SurgebindingCapability {
public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
});
| // Path: src/main/java/com/legobmw99/stormlight/Stormlight.java
// @Mod(Stormlight.MODID)
// public class Stormlight {
// public static final String MODID = "stormlight";
// public static final Logger LOGGER = LogManager.getLogger();
//
// public static final CreativeModeTab stormlight_group = new CreativeModeTab(Stormlight.MODID) {
// @Override
// public ItemStack makeIcon() {
// int type = (int) (System.currentTimeMillis() / (1000 * 60)) % 10;
// return new ItemStack(CombatSetup.SHARDBLADES.get(type).get());
// }
// };
//
// public static Stormlight instance;
//
// public Stormlight() {
// instance = this;
// FMLJavaModLoadingContext.get().getModEventBus().addListener(Stormlight::init);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(Stormlight::clientInit);
// FMLJavaModLoadingContext.get().getModEventBus().addGenericListener(EntityType.class, WorldSetup::onEntityRegister);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(WorldSetup::onEntityAttribute);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(SurgebindingCapability::registerCapability);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(WorldSetup::registerEntityModels);
// FMLJavaModLoadingContext.get().getModEventBus().addListener(WorldSetup::registerEntityRenders);
// MinecraftForge.EVENT_BUS.addListener(Stormlight::registerCommands);
//
// PowersSetup.register();
// WorldSetup.register();
// CombatSetup.register();
// }
//
// public static Item.Properties createStandardItemProperties() {
// return new Item.Properties().tab(stormlight_group).stacksTo(64);
// }
//
// public static void clientInit(final FMLClientSetupEvent e) {
// PowersClientSetup.clientInit(e);
// WorldSetup.clientInit(e);
// CombatSetup.clientInit(e);
// }
//
// public static void registerCommands(final RegisterCommandsEvent e) {
// StormlightCommand.register(e.getDispatcher());
// }
//
// public static void init(final FMLCommonSetupEvent e) {
// PowersSetup.init(e);
// Network.registerPackets();
// }
//
//
// }
//
// Path: src/main/java/com/legobmw99/stormlight/api/ISurgebindingData.java
// public interface ISurgebindingData {
//
// @Nullable
// Order getOrder();
//
// void setOrder(Order order);
//
// Ideal getIdeal();
//
// void setIdeal(Ideal ideal);
//
// void storeBlade(@Nonnull ItemStack blade);
//
//
// boolean isBladeStored();
//
// boolean addBladeToInventory(Player player);
//
// UUID getSprenID();
//
// void setSprenID(UUID sprenID);
//
//
// default boolean isKnight() {
// return getOrder() != null && getIdeal() != Ideal.UNINVESTED && getIdeal() != Ideal.TRAITOR;
// }
//
// default Ideal progressIdeal() {
// Ideal next = getIdeal().progressIdeal();
// setIdeal(next);
// return next;
// }
//
// default Ideal regressIdeal() {
// Ideal next = getIdeal().regressIdeal();
// setIdeal(next);
// return next;
// }
//
// default boolean earnedBlade() {
// Order order = getOrder();
// return order != null && order.getBladeIdeal().compareTo(getIdeal()) < 0;
// }
//
// default boolean canUseSurge(Surge surge) {
// Order order = getOrder();
// Ideal ideal = getIdeal();
// return order != null &&
// ((surge == order.getFirst() && order.getFirstIdeal().compareTo(ideal) < 0) || (surge == order.getSecond() && order.getSecondIdeal().compareTo(ideal) < 0));
// }
//
// void load(CompoundTag nbt);
//
// CompoundTag save();
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
import com.legobmw99.stormlight.Stormlight;
import com.legobmw99.stormlight.api.ISurgebindingData;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
package com.legobmw99.stormlight.modules.powers.data;
public class SurgebindingCapability {
public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
});
| public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data"); |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/block/AdhesionBlock.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.FaceAttachedHorizontalDirectionalBlock;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.AttachFace;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.material.PushReaction;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.Random; | public VoxelShape getVisualShape(BlockState state, BlockGetter reader, BlockPos pos, CollisionContext ctx) {
return Shapes.empty();
}
@OnlyIn(Dist.CLIENT)
@Override
public float getShadeBrightness(BlockState state, BlockGetter reader, BlockPos pos) {
return 1.0F;
}
@Override
public boolean propagatesSkylightDown(BlockState state, BlockGetter reader, BlockPos pos) {
return true;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(FACING, FACE);
}
@Override
public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) {
super.randomTick(state, world, pos, random);
world.setBlockAndUpdate(pos, Blocks.AIR.defaultBlockState());
}
@Override
public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/block/AdhesionBlock.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.FaceAttachedHorizontalDirectionalBlock;
import net.minecraft.world.level.block.SoundType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.AttachFace;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.material.PushReaction;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import java.util.Random;
public VoxelShape getVisualShape(BlockState state, BlockGetter reader, BlockPos pos, CollisionContext ctx) {
return Shapes.empty();
}
@OnlyIn(Dist.CLIENT)
@Override
public float getShadeBrightness(BlockState state, BlockGetter reader, BlockPos pos) {
return 1.0F;
}
@Override
public boolean propagatesSkylightDown(BlockState state, BlockGetter reader, BlockPos pos) {
return true;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(FACING, FACE);
}
@Override
public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) {
super.randomTick(state, world, pos, random);
world.setBlockAndUpdate(pos, Blocks.AIR.defaultBlockState());
}
@Override
public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { | if (!entity.isNoGravity() && (entity instanceof LivingEntity && !((LivingEntity) entity).hasEffect(PowersSetup.GRAVITATION.get()))) { |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/network/packets/SurgePacket.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
// public class SurgebindingCapability {
//
// public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
// });
//
// public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data");
//
//
// public static void registerCapability(final RegisterCapabilitiesEvent event) {
// event.register(ISurgebindingData.class);
// }
//
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability;
import com.legobmw99.stormlight.util.Surge;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import javax.annotation.Nullable;
import java.util.function.Supplier; | this.shiftHeld = shiftHeld;
}
public static SurgePacket decode(FriendlyByteBuf buf) {
return new SurgePacket(buf.readEnum(Surge.class), buf.readBoolean() ? buf.readBlockPos() : null, buf.readBoolean());
}
public void encode(FriendlyByteBuf buf) {
buf.writeEnum(surge);
boolean hasBlock = looking != null;
buf.writeBoolean(hasBlock);
if (hasBlock) {
buf.writeBlockPos(looking);
}
buf.writeBoolean(shiftHeld);
}
public void handle(Supplier<NetworkEvent.Context> ctx) {
if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_CLIENT) {
ctx.get().enqueueWork(() -> {
if (looking != null) {
surge.displayEffect(looking, shiftHeld);
}
});
ctx.get().setPacketHandled(true);
} else if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) {
ctx.get().enqueueWork(() -> {
ServerPlayer player = ctx.get().getSender();
if (player != null) { | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
// public class SurgebindingCapability {
//
// public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
// });
//
// public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data");
//
//
// public static void registerCapability(final RegisterCapabilitiesEvent event) {
// event.register(ISurgebindingData.class);
// }
//
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
// Path: src/main/java/com/legobmw99/stormlight/network/packets/SurgePacket.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability;
import com.legobmw99.stormlight.util.Surge;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import javax.annotation.Nullable;
import java.util.function.Supplier;
this.shiftHeld = shiftHeld;
}
public static SurgePacket decode(FriendlyByteBuf buf) {
return new SurgePacket(buf.readEnum(Surge.class), buf.readBoolean() ? buf.readBlockPos() : null, buf.readBoolean());
}
public void encode(FriendlyByteBuf buf) {
buf.writeEnum(surge);
boolean hasBlock = looking != null;
buf.writeBoolean(hasBlock);
if (hasBlock) {
buf.writeBlockPos(looking);
}
buf.writeBoolean(shiftHeld);
}
public void handle(Supplier<NetworkEvent.Context> ctx) {
if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_CLIENT) {
ctx.get().enqueueWork(() -> {
if (looking != null) {
surge.displayEffect(looking, shiftHeld);
}
});
ctx.get().setPacketHandled(true);
} else if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) {
ctx.get().enqueueWork(() -> {
ServerPlayer player = ctx.get().getSender();
if (player != null) { | if (player.getCapability(SurgebindingCapability.PLAYER_CAP).filter(data -> data.isKnight() && data.canUseSurge(surge)).isPresent() && |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/network/packets/SurgePacket.java | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
// public class SurgebindingCapability {
//
// public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
// });
//
// public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data");
//
//
// public static void registerCapability(final RegisterCapabilitiesEvent event) {
// event.register(ISurgebindingData.class);
// }
//
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
| import com.legobmw99.stormlight.modules.powers.PowersSetup;
import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability;
import com.legobmw99.stormlight.util.Surge;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import javax.annotation.Nullable;
import java.util.function.Supplier; | }
public static SurgePacket decode(FriendlyByteBuf buf) {
return new SurgePacket(buf.readEnum(Surge.class), buf.readBoolean() ? buf.readBlockPos() : null, buf.readBoolean());
}
public void encode(FriendlyByteBuf buf) {
buf.writeEnum(surge);
boolean hasBlock = looking != null;
buf.writeBoolean(hasBlock);
if (hasBlock) {
buf.writeBlockPos(looking);
}
buf.writeBoolean(shiftHeld);
}
public void handle(Supplier<NetworkEvent.Context> ctx) {
if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_CLIENT) {
ctx.get().enqueueWork(() -> {
if (looking != null) {
surge.displayEffect(looking, shiftHeld);
}
});
ctx.get().setPacketHandled(true);
} else if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) {
ctx.get().enqueueWork(() -> {
ServerPlayer player = ctx.get().getSender();
if (player != null) {
if (player.getCapability(SurgebindingCapability.PLAYER_CAP).filter(data -> data.isKnight() && data.canUseSurge(surge)).isPresent() && | // Path: src/main/java/com/legobmw99/stormlight/modules/powers/PowersSetup.java
// public class PowersSetup {
//
// public static final DeferredRegister<MobEffect> EFFECTS = DeferredRegister.create(ForgeRegistries.MOB_EFFECTS, Stormlight.MODID);
//
// public static final RegistryObject<MobEffect> STORMLIGHT = EFFECTS.register("stormlight", () -> new GenericEffect(MobEffectCategory.BENEFICIAL, 0));
// public static final RegistryObject<MobEffect> SLICKING = EFFECTS.register("slicking", () -> new StormlightEffect(16737535));
// public static final RegistryObject<MobEffect> STICKING = EFFECTS.register("sticking", () -> new StormlightEffect(6579455));
// public static final RegistryObject<MobEffect> COHESION = EFFECTS.register("cohesion", () -> new StormlightEffect(16777010));
// public static final RegistryObject<MobEffect> TENSION = EFFECTS.register("tension", () -> new StormlightEffect(16711780));
// public static final RegistryObject<MobEffect> GRAVITATION = EFFECTS.register("gravitation",
// () -> new StormlightEffect(6605055).addAttributeModifier(ForgeMod.ENTITY_GRAVITY.get(),
// "a81758d2-c355-11eb-8529-0242ac130003",
// -0.08,
// AttributeModifier.Operation.ADDITION));
//
//
// public static void register() {
// EFFECTS.register(FMLJavaModLoadingContext.get().getModEventBus());
// }
//
//
// public static void init(final FMLCommonSetupEvent e) {
// ArgumentTypes.register("stormlight_ideal", StormlightArgType.IdealType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.IdealType.INSTANCE));
// ArgumentTypes.register("stormlight_order", StormlightArgType.OrderType.class, new EmptyArgumentSerializer<>(() -> StormlightArgType.OrderType.INSTANCE));
//
// MinecraftForge.EVENT_BUS.register(PowersEventHandler.class);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/data/SurgebindingCapability.java
// public class SurgebindingCapability {
//
// public static final Capability<ISurgebindingData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {
// });
//
// public static final ResourceLocation IDENTIFIER = new ResourceLocation(Stormlight.MODID, "surgebinding_data");
//
//
// public static void registerCapability(final RegisterCapabilitiesEvent event) {
// event.register(ISurgebindingData.class);
// }
//
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
// Path: src/main/java/com/legobmw99/stormlight/network/packets/SurgePacket.java
import com.legobmw99.stormlight.modules.powers.PowersSetup;
import com.legobmw99.stormlight.modules.powers.data.SurgebindingCapability;
import com.legobmw99.stormlight.util.Surge;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import javax.annotation.Nullable;
import java.util.function.Supplier;
}
public static SurgePacket decode(FriendlyByteBuf buf) {
return new SurgePacket(buf.readEnum(Surge.class), buf.readBoolean() ? buf.readBlockPos() : null, buf.readBoolean());
}
public void encode(FriendlyByteBuf buf) {
buf.writeEnum(surge);
boolean hasBlock = looking != null;
buf.writeBoolean(hasBlock);
if (hasBlock) {
buf.writeBlockPos(looking);
}
buf.writeBoolean(shiftHeld);
}
public void handle(Supplier<NetworkEvent.Context> ctx) {
if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_CLIENT) {
ctx.get().enqueueWork(() -> {
if (looking != null) {
surge.displayEffect(looking, shiftHeld);
}
});
ctx.get().setPacketHandled(true);
} else if (ctx.get().getDirection() == NetworkDirection.PLAY_TO_SERVER) {
ctx.get().enqueueWork(() -> {
ServerPlayer player = ctx.get().getSender();
if (player != null) {
if (player.getCapability(SurgebindingCapability.PLAYER_CAP).filter(data -> data.isKnight() && data.canUseSurge(surge)).isPresent() && | player.hasEffect(PowersSetup.STORMLIGHT.get())) { |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/util/Order.java | // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
| import java.util.Locale;
import static com.legobmw99.stormlight.util.Ideal.*;
import static com.legobmw99.stormlight.util.Surge.*; | package com.legobmw99.stormlight.util;
public enum Order {
WINDRUNNERS(ADHESION, GRAVITATION),
SKYBREAKERS(GRAVITATION, DIVISION),
DUSTBRINGERS(DIVISION, ABRASION),
EDGEDANCERS(ABRASION, PROGRESSION),
TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
WILLSHAPERS(TRANSPORTATION, COHESION),
STONEWARDS(COHESION, TENSION),
BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
| // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
import java.util.Locale;
import static com.legobmw99.stormlight.util.Ideal.*;
import static com.legobmw99.stormlight.util.Surge.*;
package com.legobmw99.stormlight.util;
public enum Order {
WINDRUNNERS(ADHESION, GRAVITATION),
SKYBREAKERS(GRAVITATION, DIVISION),
DUSTBRINGERS(DIVISION, ABRASION),
EDGEDANCERS(ABRASION, PROGRESSION),
TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
WILLSHAPERS(TRANSPORTATION, COHESION),
STONEWARDS(COHESION, TENSION),
BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
| private final Surge first; |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/util/Order.java | // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
| import java.util.Locale;
import static com.legobmw99.stormlight.util.Ideal.*;
import static com.legobmw99.stormlight.util.Surge.*; | package com.legobmw99.stormlight.util;
public enum Order {
WINDRUNNERS(ADHESION, GRAVITATION),
SKYBREAKERS(GRAVITATION, DIVISION),
DUSTBRINGERS(DIVISION, ABRASION),
EDGEDANCERS(ABRASION, PROGRESSION),
TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
WILLSHAPERS(TRANSPORTATION, COHESION),
STONEWARDS(COHESION, TENSION),
BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
private final Surge first;
private final Surge second; | // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Surge.java
// public enum Surge {
// ADHESION(Surges::adhesion, 25, true, SurgeEffects::adhesionEffect),
// GRAVITATION(Surges::gravitation),
// DIVISION(Surges::division),
// ABRASION(Surges::abrasion),
// PROGRESSION(Surges::progression, SurgeEffects::progressionEffect),
// ILLUMINATION(Surges::illumination),
// TRANSFORMATION(Surges::transformation),
// TRANSPORTATION(Surges::transportation, 40F),
// COHESION(Surges::cohesion),
// TENSION(Surges::tension);
//
// private final ISurgePower surge;
// private final ISurgeEffect effect;
// private final float range;
// private final boolean repeating;
//
// Surge(ISurgePower surge) {
// this(surge, 30F, false, null);
// }
//
// Surge(ISurgePower surge, float range) {
// this(surge, range, false, null);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating) {
// this(surge, range, repeating, null);
// }
//
// Surge(ISurgePower surge, ISurgeEffect effect) {
// this(surge, 30F, false, effect);
// }
//
// Surge(ISurgePower surge, float range, boolean repeating, ISurgeEffect effect) {
// this.surge = surge;
// this.range = range;
// this.repeating = repeating;
// this.effect = effect;
// }
//
//
// public boolean hasEffect() {
// return effect != null;
// }
//
// public boolean isRepeating() {return repeating;}
//
// public float getRange() {
// return range;
// }
//
// public void fire(ServerPlayer player, @Nullable BlockPos looking, boolean modified) {
// surge.fire(player, looking, modified);
// }
//
// public void displayEffect(BlockPos looking, boolean modified) {
// if (hasEffect()) {
// effect.fire(looking, modified);
// }
// }
//
// }
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
import java.util.Locale;
import static com.legobmw99.stormlight.util.Ideal.*;
import static com.legobmw99.stormlight.util.Surge.*;
package com.legobmw99.stormlight.util;
public enum Order {
WINDRUNNERS(ADHESION, GRAVITATION),
SKYBREAKERS(GRAVITATION, DIVISION),
DUSTBRINGERS(DIVISION, ABRASION),
EDGEDANCERS(ABRASION, PROGRESSION),
TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
WILLSHAPERS(TRANSPORTATION, COHESION),
STONEWARDS(COHESION, TENSION),
BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
private final Surge first;
private final Surge second; | private final Ideal blade_gate; |
legobmw99/Stormlight | src/main/java/com/legobmw99/stormlight/modules/powers/command/StormlightArgType.java | // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
// public enum Order {
// WINDRUNNERS(ADHESION, GRAVITATION),
// SKYBREAKERS(GRAVITATION, DIVISION),
// DUSTBRINGERS(DIVISION, ABRASION),
// EDGEDANCERS(ABRASION, PROGRESSION),
// TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
// LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
// ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
// WILLSHAPERS(TRANSPORTATION, COHESION),
// STONEWARDS(COHESION, TENSION),
// BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
//
//
// private final Surge first;
// private final Surge second;
// private final Ideal blade_gate;
// private final Ideal first_gate;
// private final Ideal second_gate;
//
// Order(Surge fst, Surge snd) {
// this(fst, snd, FIRST, FIRST, FIRST);
// }
//
// Order(Surge fst, Surge snd, Ideal blade, Ideal first, Ideal second) {
// this.first = fst;
// this.second = snd;
// this.blade_gate = blade;
// this.first_gate = first;
// this.second_gate = second;
// }
//
// public static Order getOrNull(int index) {
// for (Order order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// return null;
// }
//
// public Surge getFirst() {
// return first;
// }
//
// public Surge getSecond() {
// return second;
// }
//
// public Ideal getFirstIdeal() {return first_gate;}
//
// public Ideal getSecondIdeal() {return second_gate;}
//
// public Ideal getBladeIdeal() {return blade_gate;}
//
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public String getSingularName() {
// String name = this.getName();
// return name.substring(0, name.length() - 1);
// }
//
// public int getIndex() {
// return ordinal();
// }
//
// public boolean hasSurge(Surge surge) {
// return first == surge || second == surge;
// }
// }
| import com.legobmw99.stormlight.util.Ideal;
import com.legobmw99.stormlight.util.Order;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.TranslatableComponent;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors; | package com.legobmw99.stormlight.modules.powers.command;
public class StormlightArgType {
public static class OrderType implements ArgumentType<Order> {
public static final OrderType INSTANCE = new OrderType();
private static final Set<String> types = Arrays.stream(Order.values()).map(Order::getName).collect(Collectors.toSet());
private static final DynamicCommandExceptionType unknown_power = new DynamicCommandExceptionType(
o -> new TranslatableComponent("commands.stormlight.unrecognized_order", o));
@Override
public Order parse(StringReader reader) throws CommandSyntaxException {
String in = reader.readUnquotedString();
if (types.contains(in)) {
return Order.valueOf(in.toUpperCase(Locale.ROOT));
}
throw unknown_power.create(in);
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
return SharedSuggestionProvider.suggest(types, builder).toCompletableFuture();
}
@Override
public Collection<String> getExamples() {
return types;
}
}
| // Path: src/main/java/com/legobmw99/stormlight/util/Ideal.java
// public enum Ideal {
//
// TRAITOR,
// UNINVESTED,
// FIRST,
// SECOND,
// THIRD,
// FOURTH,
// FIFTH;
//
// public static Ideal get(int index) {
// for (Ideal order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// throw new IllegalArgumentException("Bad ideal index");
// }
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public int getIndex() {
// return ordinal() - 1;
// }
//
// public Ideal progressIdeal() {
// int i = getIndex() + 1;
// if (i > 5) {
// i = 5;
// }
// return get(i);
// }
//
// public Ideal regressIdeal() {
// int i = getIndex() - 1;
// if (i < -1) {
// i = -1;
// }
// return get(i);
// }
// }
//
// Path: src/main/java/com/legobmw99/stormlight/util/Order.java
// public enum Order {
// WINDRUNNERS(ADHESION, GRAVITATION),
// SKYBREAKERS(GRAVITATION, DIVISION),
// DUSTBRINGERS(DIVISION, ABRASION),
// EDGEDANCERS(ABRASION, PROGRESSION),
// TRUTHWATCHERS(PROGRESSION, ILLUMINATION),
// LIGHTWEAVERS(ILLUMINATION, TRANSFORMATION),
// ELSECALLERS(TRANSFORMATION, TRANSPORTATION),
// WILLSHAPERS(TRANSPORTATION, COHESION),
// STONEWARDS(COHESION, TENSION),
// BONDSMITHS(TENSION, ADHESION, FIFTH, SECOND, THIRD);
//
//
// private final Surge first;
// private final Surge second;
// private final Ideal blade_gate;
// private final Ideal first_gate;
// private final Ideal second_gate;
//
// Order(Surge fst, Surge snd) {
// this(fst, snd, FIRST, FIRST, FIRST);
// }
//
// Order(Surge fst, Surge snd, Ideal blade, Ideal first, Ideal second) {
// this.first = fst;
// this.second = snd;
// this.blade_gate = blade;
// this.first_gate = first;
// this.second_gate = second;
// }
//
// public static Order getOrNull(int index) {
// for (Order order : values()) {
// if (order.getIndex() == index) {
// return order;
// }
// }
// return null;
// }
//
// public Surge getFirst() {
// return first;
// }
//
// public Surge getSecond() {
// return second;
// }
//
// public Ideal getFirstIdeal() {return first_gate;}
//
// public Ideal getSecondIdeal() {return second_gate;}
//
// public Ideal getBladeIdeal() {return blade_gate;}
//
//
// public String getName() {
// return name().toLowerCase(Locale.ROOT);
// }
//
// public String getSingularName() {
// String name = this.getName();
// return name.substring(0, name.length() - 1);
// }
//
// public int getIndex() {
// return ordinal();
// }
//
// public boolean hasSurge(Surge surge) {
// return first == surge || second == surge;
// }
// }
// Path: src/main/java/com/legobmw99/stormlight/modules/powers/command/StormlightArgType.java
import com.legobmw99.stormlight.util.Ideal;
import com.legobmw99.stormlight.util.Order;
import com.mojang.brigadier.StringReader;
import com.mojang.brigadier.arguments.ArgumentType;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.DynamicCommandExceptionType;
import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.commands.SharedSuggestionProvider;
import net.minecraft.network.chat.TranslatableComponent;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
package com.legobmw99.stormlight.modules.powers.command;
public class StormlightArgType {
public static class OrderType implements ArgumentType<Order> {
public static final OrderType INSTANCE = new OrderType();
private static final Set<String> types = Arrays.stream(Order.values()).map(Order::getName).collect(Collectors.toSet());
private static final DynamicCommandExceptionType unknown_power = new DynamicCommandExceptionType(
o -> new TranslatableComponent("commands.stormlight.unrecognized_order", o));
@Override
public Order parse(StringReader reader) throws CommandSyntaxException {
String in = reader.readUnquotedString();
if (types.contains(in)) {
return Order.valueOf(in.toUpperCase(Locale.ROOT));
}
throw unknown_power.create(in);
}
@Override
public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {
return SharedSuggestionProvider.suggest(types, builder).toCompletableFuture();
}
@Override
public Collection<String> getExamples() {
return types;
}
}
| public static class IdealType implements ArgumentType<Ideal> { |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/generator/hierarchies/EPackageHierarchy.java | // Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
| import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.ENamedElement;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcoreFactory;
import eme.properties.ExtractionProperties; | package eme.generator.hierarchies;
/**
* This class allows to build a package structure, a {@link EPackage} hierarchy for {@link EClassifier}s.
* @author Timur Saglam
*/
public class EPackageHierarchy {
protected final EPackage basePackage; | // Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
// Path: src/main/java/eme/generator/hierarchies/EPackageHierarchy.java
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.ENamedElement;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcoreFactory;
import eme.properties.ExtractionProperties;
package eme.generator.hierarchies;
/**
* This class allows to build a package structure, a {@link EPackage} hierarchy for {@link EClassifier}s.
* @author Timur Saglam
*/
public class EPackageHierarchy {
protected final EPackage basePackage; | protected final ExtractionProperties properties; |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/ui/providers/CheckStateProvider.java | // Path: src/main/java/eme/model/ExtractedElement.java
// public abstract class ExtractedElement implements Comparable<ExtractedElement> {
// protected String name;
// protected String parent;
// protected boolean selected; // selection for saving.
//
// /**
// * Basic constructor which extracts the name and the parents name from the full
// * name.
// * @param fullName is the full name.
// */
// public ExtractedElement(String fullName) {
// name = createName(fullName);
// parent = createPath(fullName);
// selected = true;
// }
//
// /**
// * @see Comparable#compareTo(Object)
// */
// @Override
// public int compareTo(ExtractedElement o) {
// if (o == null) {
// throw new IllegalArgumentException("Cannot compare " + toString() + " with null!");
// }
// return name.compareTo(o.getName());
// }
//
// /**
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this.getClass() == obj.getClass()) { // same class
// return getFullName().equals(((ExtractedElement) obj).getFullName()); // same full name
// }
// return false;
// }
//
// /**
// * Asccessor for the full element name.
// * @return the full name of the element, consisting out of the package path and
// * the element name separated by an dot.
// */
// public String getFullName() {
// if ("".equals(parent)) {
// return name;
// }
// return parent + '.' + name;
// }
//
// /**
// * accessor for the element name.
// * @return the element name.
// */
// public String getName() {
// return name;
// }
//
// /**
// * accessor for the name of the elements parent.
// * @return the parent name.
// */
// public String getParentName() {
// return parent;
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((getFullName() == null) ? 0 : getFullName().hashCode());
// return result;
// }
//
// /**
// * Checks whether the element is selected.
// * @return true if selected.
// */
// public boolean isSelected() {
// return selected;
// }
//
// /**
// * Sets whether is element is selected or not. All child elements like types or
// * subpackages will be (de)selected.
// * @param selected true to select the element, false to deselect.
// */
// public void setSelected(boolean selected) {
// this.selected = selected;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(" + getFullName() + ")";
// }
//
// /**
// * Calculates the index of the separator of a full qualified name.
// * @param fullName is the full qualified name.
// * @return the index of the separator.
// */
// private int separator(String fullName) {
// return fullName.lastIndexOf('.');
// }
//
// /**
// * Creates the name of a class or package from a full qualified name with both
// * path and name.
// * @param fullName is the full qualified name.
// * @return the name.
// */
// protected final String createName(String fullName) {
// if (fullName.contains(".")) {
// return fullName.substring(separator(fullName) + 1); // get name
// } else { // split name from parent package:
// return fullName; // already is name.
// }
// }
//
// /**
// * Creates the path of a class or package from a full qualified name with both
// * path and name.
// * @param fullName is the full qualified name.
// * @return the path.
// */
// protected final String createPath(String fullName) {
// if (fullName.contains(".")) {
// return fullName.substring(0, separator(fullName)); // get path
// } else { // split name from parent package:
// return ""; // has no parent.
// }
// }
// }
| import org.eclipse.jface.viewers.ICheckStateProvider;
import eme.model.ExtractedElement; | package eme.ui.providers;
/**
* Provides checked and grayed state information about intermediate model elements in trees or tables. Makes sure that
* any {@link ExtractedElement} in the tree view is initially checked or unchecked according to its selection status.
* @author Timur Saglam
*/
public class CheckStateProvider implements ICheckStateProvider {
@Override
public boolean isChecked(Object element) { | // Path: src/main/java/eme/model/ExtractedElement.java
// public abstract class ExtractedElement implements Comparable<ExtractedElement> {
// protected String name;
// protected String parent;
// protected boolean selected; // selection for saving.
//
// /**
// * Basic constructor which extracts the name and the parents name from the full
// * name.
// * @param fullName is the full name.
// */
// public ExtractedElement(String fullName) {
// name = createName(fullName);
// parent = createPath(fullName);
// selected = true;
// }
//
// /**
// * @see Comparable#compareTo(Object)
// */
// @Override
// public int compareTo(ExtractedElement o) {
// if (o == null) {
// throw new IllegalArgumentException("Cannot compare " + toString() + " with null!");
// }
// return name.compareTo(o.getName());
// }
//
// /**
// * @see java.lang.Object#equals(java.lang.Object)
// */
// @Override
// public boolean equals(Object obj) {
// if (this.getClass() == obj.getClass()) { // same class
// return getFullName().equals(((ExtractedElement) obj).getFullName()); // same full name
// }
// return false;
// }
//
// /**
// * Asccessor for the full element name.
// * @return the full name of the element, consisting out of the package path and
// * the element name separated by an dot.
// */
// public String getFullName() {
// if ("".equals(parent)) {
// return name;
// }
// return parent + '.' + name;
// }
//
// /**
// * accessor for the element name.
// * @return the element name.
// */
// public String getName() {
// return name;
// }
//
// /**
// * accessor for the name of the elements parent.
// * @return the parent name.
// */
// public String getParentName() {
// return parent;
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((getFullName() == null) ? 0 : getFullName().hashCode());
// return result;
// }
//
// /**
// * Checks whether the element is selected.
// * @return true if selected.
// */
// public boolean isSelected() {
// return selected;
// }
//
// /**
// * Sets whether is element is selected or not. All child elements like types or
// * subpackages will be (de)selected.
// * @param selected true to select the element, false to deselect.
// */
// public void setSelected(boolean selected) {
// this.selected = selected;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(" + getFullName() + ")";
// }
//
// /**
// * Calculates the index of the separator of a full qualified name.
// * @param fullName is the full qualified name.
// * @return the index of the separator.
// */
// private int separator(String fullName) {
// return fullName.lastIndexOf('.');
// }
//
// /**
// * Creates the name of a class or package from a full qualified name with both
// * path and name.
// * @param fullName is the full qualified name.
// * @return the name.
// */
// protected final String createName(String fullName) {
// if (fullName.contains(".")) {
// return fullName.substring(separator(fullName) + 1); // get name
// } else { // split name from parent package:
// return fullName; // already is name.
// }
// }
//
// /**
// * Creates the path of a class or package from a full qualified name with both
// * path and name.
// * @param fullName is the full qualified name.
// * @return the path.
// */
// protected final String createPath(String fullName) {
// if (fullName.contains(".")) {
// return fullName.substring(0, separator(fullName)); // get path
// } else { // split name from parent package:
// return ""; // has no parent.
// }
// }
// }
// Path: src/main/java/eme/ui/providers/CheckStateProvider.java
import org.eclipse.jface.viewers.ICheckStateProvider;
import eme.model.ExtractedElement;
package eme.ui.providers;
/**
* Provides checked and grayed state information about intermediate model elements in trees or tables. Makes sure that
* any {@link ExtractedElement} in the tree view is initially checked or unchecked according to its selection status.
* @author Timur Saglam
*/
public class CheckStateProvider implements ICheckStateProvider {
@Override
public boolean isChecked(Object element) { | if (element instanceof ExtractedElement) { // if is intermediate model element |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/handlers/WorkspaceHandler.java | // Path: src/main/java/eme/EcoreMetamodelExtraction.java
// public class EcoreMetamodelExtraction {
// private static final Logger logger = LogManager.getLogger(EcoreMetamodelExtraction.class.getName());
// private final JavaProjectExtractor extractor;
// private final EcoreMetamodelGenerator generator;
// private final ExtractionProperties properties;
//
// /**
// * Basic constructor. Builds {@link JavaProjectExtractor}, {@link EcoreMetamodelGenerator} and
// * {@link GenModelGenerator}.
// */
// public EcoreMetamodelExtraction() {
// logger.info("Started EME...");
// properties = new ExtractionProperties();
// extractor = new JavaProjectExtractor();
// generator = new EcoreMetamodelGenerator(properties);
// }
//
// /**
// * Starts the Ecore metamodel extraction for a specific {@link IProject}. The {@link IProject} will be parsed and an
// * Ecore metamodel will be build.
// * @param project is the specific {@link IProject} for the extraction.
// * @return the Ecore metamodel.
// */
// public GeneratedEcoreMetamodel extract(IProject project) {
// logger.info("Started extraction of project " + project.getName());
// check(project); // check if valid.
// IJavaProject javaProject = JavaCore.create(project); // create java project
// IntermediateModel model = extractor.buildIntermediateModel(javaProject);
// selectExtractionScope(model); // select scope if enabled in properties
// GeneratedEcoreMetamodel metamodel = generator.generateMetamodel(model);
// generator.saveMetamodel(); // save metamodel
// return metamodel;
// }
//
// /**
// * Grants access to the {@link ExtractionProperties}.
// * @return the {@link ExtractionProperties}.
// */
// public ExtractionProperties getProperties() {
// return properties;
// }
//
// /**
// * Checks whether a specific {@link IProject} is valid (neither null nor nonexistent)
// * @param project is the specific {@link IProject}.
// */
// private void check(IProject project) {
// if (project == null) {
// throw new IllegalArgumentException("Project can't be null!");
// } else if (!project.exists()) {
// throw new IllegalArgumentException("Project " + project.toString() + "does not exist!");
// }
// }
//
// /**
// * Opens a window for specifying a custom extraction scope. The scope is manifested in the correlating
// * {@link IntermediateModel} through enabling and disabling specific model elements.
// * @param model is the {@link IntermediateModel} for which the extraction scope is specified.
// */
// private void selectExtractionScope(IntermediateModel model) {
// if (properties.get(CUSTOM_EXTRACTION_SCOPE)) {
// new SelectionWindow().open(model);
// }
// }
// }
| import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import eme.EcoreMetamodelExtraction; | package eme.handlers;
/**
* Handler for calling an extraction method.
* @author Timur Saglam
*/
public class WorkspaceHandler extends MainHandler {
private IWorkbenchWindow window;
/**
* Accesses all the projects in the workspace and lets the user choose a project with a simple dialog.
* @return the chosen project.
*/
public IProject chooseProject() {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject[] projects = root.getProjects();
for (IProject project : projects) {
if (isJavaProject(project) && isChoosen(project)) {
return project;
}
}
return null;
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
IProject project = chooseProject();
if (project != null) { | // Path: src/main/java/eme/EcoreMetamodelExtraction.java
// public class EcoreMetamodelExtraction {
// private static final Logger logger = LogManager.getLogger(EcoreMetamodelExtraction.class.getName());
// private final JavaProjectExtractor extractor;
// private final EcoreMetamodelGenerator generator;
// private final ExtractionProperties properties;
//
// /**
// * Basic constructor. Builds {@link JavaProjectExtractor}, {@link EcoreMetamodelGenerator} and
// * {@link GenModelGenerator}.
// */
// public EcoreMetamodelExtraction() {
// logger.info("Started EME...");
// properties = new ExtractionProperties();
// extractor = new JavaProjectExtractor();
// generator = new EcoreMetamodelGenerator(properties);
// }
//
// /**
// * Starts the Ecore metamodel extraction for a specific {@link IProject}. The {@link IProject} will be parsed and an
// * Ecore metamodel will be build.
// * @param project is the specific {@link IProject} for the extraction.
// * @return the Ecore metamodel.
// */
// public GeneratedEcoreMetamodel extract(IProject project) {
// logger.info("Started extraction of project " + project.getName());
// check(project); // check if valid.
// IJavaProject javaProject = JavaCore.create(project); // create java project
// IntermediateModel model = extractor.buildIntermediateModel(javaProject);
// selectExtractionScope(model); // select scope if enabled in properties
// GeneratedEcoreMetamodel metamodel = generator.generateMetamodel(model);
// generator.saveMetamodel(); // save metamodel
// return metamodel;
// }
//
// /**
// * Grants access to the {@link ExtractionProperties}.
// * @return the {@link ExtractionProperties}.
// */
// public ExtractionProperties getProperties() {
// return properties;
// }
//
// /**
// * Checks whether a specific {@link IProject} is valid (neither null nor nonexistent)
// * @param project is the specific {@link IProject}.
// */
// private void check(IProject project) {
// if (project == null) {
// throw new IllegalArgumentException("Project can't be null!");
// } else if (!project.exists()) {
// throw new IllegalArgumentException("Project " + project.toString() + "does not exist!");
// }
// }
//
// /**
// * Opens a window for specifying a custom extraction scope. The scope is manifested in the correlating
// * {@link IntermediateModel} through enabling and disabling specific model elements.
// * @param model is the {@link IntermediateModel} for which the extraction scope is specified.
// */
// private void selectExtractionScope(IntermediateModel model) {
// if (properties.get(CUSTOM_EXTRACTION_SCOPE)) {
// new SelectionWindow().open(model);
// }
// }
// }
// Path: src/main/java/eme/handlers/WorkspaceHandler.java
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import eme.EcoreMetamodelExtraction;
package eme.handlers;
/**
* Handler for calling an extraction method.
* @author Timur Saglam
*/
public class WorkspaceHandler extends MainHandler {
private IWorkbenchWindow window;
/**
* Accesses all the projects in the workspace and lets the user choose a project with a simple dialog.
* @return the chosen project.
*/
public IProject chooseProject() {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IProject[] projects = root.getProjects();
for (IProject project : projects) {
if (isJavaProject(project) && isChoosen(project)) {
return project;
}
}
return null;
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
IProject project = chooseProject();
if (project != null) { | new EcoreMetamodelExtraction().extract(project); |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/generator/hierarchies/InnerTypeHierarchy.java | // Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
//
// Path: src/main/java/eme/properties/TextProperty.java
// public enum TextProperty implements ITextProperty {
// DATATYPE_PACKAGE("DataTypePackageName", "DATATYPES"),
// DEFAULT_PACKAGE("DefaultPackageName", "DEFAULT"),
// DUMMY_NAME("DummyClassName", "DUMMY"),
// ROOT_NAME("RootContainerName", "ROOT"),
// NESTED_TYPE_PACKAGE("NestedTypePackageSuffix", "InnerTypes"),
// PROJECT_SUFFIX("ProjectSuffix", "Model"),
// SAVING_STRATEGY("SavingStrategy", "NewProject");
//
// private final String defaultValue;
// private final String key;
//
// /**
// * Private constructor for enum values with key and default value of an extraction property.
// * @param key is the key of the property.
// * @param defaultValue is the default value of the property.
// */
// TextProperty(String key, String defaultValue) {
// this.key = key;
// this.defaultValue = defaultValue;
// }
//
// @Override
// public String getDefaultValue() {
// return defaultValue;
// }
//
// @Override
// public String getKey() {
// return key;
// }
// }
| import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EPackage;
import eme.properties.ExtractionProperties;
import eme.properties.TextProperty; | package eme.generator.hierarchies;
/**
* This class allows to build an inner type package hierarchy from EDataTypes.
* @author Timur Saglam
*/
public class InnerTypeHierarchy extends EPackageHierarchy {
/**
* Basic constructor.
* @param basePackage is the base {@link EPackage} of hierarchy. This is the package of the (most) outer type.
* @param properties is the instance of the {@link ExtractionProperties} class.
*/
public InnerTypeHierarchy(EPackage basePackage, ExtractionProperties properties) {
super(basePackage, properties);
}
/**
* Adds an {@link EClassifier} to the package hierarchy. Generates the missing packages for the hierarchy.
* @param classifier is the new {@link EClassifier}.
* @param relativePath is the relative path of the classifier to the base package. This is used to build the package
* hierarchy.
*/
public void add(EClassifier classifier, String relativePath) { | // Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
//
// Path: src/main/java/eme/properties/TextProperty.java
// public enum TextProperty implements ITextProperty {
// DATATYPE_PACKAGE("DataTypePackageName", "DATATYPES"),
// DEFAULT_PACKAGE("DefaultPackageName", "DEFAULT"),
// DUMMY_NAME("DummyClassName", "DUMMY"),
// ROOT_NAME("RootContainerName", "ROOT"),
// NESTED_TYPE_PACKAGE("NestedTypePackageSuffix", "InnerTypes"),
// PROJECT_SUFFIX("ProjectSuffix", "Model"),
// SAVING_STRATEGY("SavingStrategy", "NewProject");
//
// private final String defaultValue;
// private final String key;
//
// /**
// * Private constructor for enum values with key and default value of an extraction property.
// * @param key is the key of the property.
// * @param defaultValue is the default value of the property.
// */
// TextProperty(String key, String defaultValue) {
// this.key = key;
// this.defaultValue = defaultValue;
// }
//
// @Override
// public String getDefaultValue() {
// return defaultValue;
// }
//
// @Override
// public String getKey() {
// return key;
// }
// }
// Path: src/main/java/eme/generator/hierarchies/InnerTypeHierarchy.java
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EPackage;
import eme.properties.ExtractionProperties;
import eme.properties.TextProperty;
package eme.generator.hierarchies;
/**
* This class allows to build an inner type package hierarchy from EDataTypes.
* @author Timur Saglam
*/
public class InnerTypeHierarchy extends EPackageHierarchy {
/**
* Basic constructor.
* @param basePackage is the base {@link EPackage} of hierarchy. This is the package of the (most) outer type.
* @param properties is the instance of the {@link ExtractionProperties} class.
*/
public InnerTypeHierarchy(EPackage basePackage, ExtractionProperties properties) {
super(basePackage, properties);
}
/**
* Adds an {@link EClassifier} to the package hierarchy. Generates the missing packages for the hierarchy.
* @param classifier is the new {@link EClassifier}.
* @param relativePath is the relative path of the classifier to the base package. This is used to build the package
* hierarchy.
*/
public void add(EClassifier classifier, String relativePath) { | String suffix = properties.get(TextProperty.NESTED_TYPE_PACKAGE); |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/generator/saving/NewProjectSaving.java | // Path: src/main/java/eme/generator/EMFProjectGenerator.java
// public final class EMFProjectGenerator {
// private static final String JAVA_VERSION = "JavaSE-1.8";
// private static final Logger logger = LogManager.getLogger(EMFProjectGenerator.class.getName());
//
// private EMFProjectGenerator() {
// // private constructor.
// }
//
// /**
// * Generate a new empty EMFProjectGeneratorproject with a specified name. If a project with that name already exits
// * the new project uses the same name and a number. The actual used name can be received from the returned IProject.
// * @param projectName is the name of the new project.
// * @return the project as IProject object.
// */
// public static IProject createProject(String projectName) {
// IProject project = null;
// IWorkspace workspace = ResourcesPlugin.getWorkspace();
// int version = 2;
// String finalName = projectName;
// project = workspace.getRoot().getProject(projectName);
// while (project.exists()) { // to avoid duplicates:
// finalName = projectName + version;
// version++;
// project = workspace.getRoot().getProject(finalName);
// }
// IJavaProject javaProject = JavaCore.create(project);
// IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(finalName);
// description.setLocation(null);
// try {
// project.create(description, null);
// } catch (CoreException exception) {
// logger.error("Error while creating project resource in workspace", exception);
// }
// List<IClasspathEntry> classpathEntries = new ArrayList<IClasspathEntry>();
// description.setNatureIds(new String[] { JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature" });
// ICommand java = description.newCommand();
// java.setBuilderName(JavaCore.BUILDER_ID);
// ICommand manifest = description.newCommand();
// manifest.setBuilderName("org.eclipse.pde.ManifestBuilder");
// ICommand schema = description.newCommand();
// schema.setBuilderName("org.eclipse.pde.SchemaBuilder");
// ICommand oaw = description.newCommand();
// description.setBuildSpec(new ICommand[] { java, manifest, schema, oaw });
// IFolder srcContainer = null;
// try {
// project.open(null);
// project.setDescription(description, null);
// srcContainer = project.getFolder("src");
// if (!srcContainer.exists()) {
// srcContainer.create(false, true, null);
// }
// } catch (CoreException exception) {
// logger.error("Error while building project description & source folder", exception);
// }
// IClasspathEntry srcClasspathEntry = JavaCore.newSourceEntry(srcContainer.getFullPath());
// classpathEntries.add(0, srcClasspathEntry);
// classpathEntries.add(JavaCore.newContainerEntry(
// new Path("org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/" + JAVA_VERSION)));
// classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins")));
// try {
// javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), null);
// javaProject.setOutputLocation(new Path("/" + finalName + "/bin"), null);
// } catch (JavaModelException exception) {
// logger.error("Error while building classpath & output location", exception);
// }
// createManifest(finalName, project);
// return project;
// }
//
// private static IFile createFile(String name, IContainer container, String content, String charSet) throws CoreException, IOException {
// IFile file = container.getFile(new Path(name));
// InputStream stream = new ByteArrayInputStream(content.getBytes(file.getCharset()));
// if (file.exists()) {
// file.setContents(stream, true, true, null);
// } else {
// file.create(stream, true, null);
// }
// stream.close();
// if (file != null && charSet != null) {
// file.setCharset(charSet, null);
// }
// return file;
// }
//
// private static void createManifest(String projectName, IProject project) {
// StringBuilder manifestContent = new StringBuilder("Manifest-Version: 1.0\n");
// manifestContent.append("Bundle-ManifestVersion: 2\n");
// manifestContent.append("Bundle-Name: " + projectName + "\n");
// manifestContent.append("Bundle-SymbolicName: " + projectName + "; singleton:=true\n");
// manifestContent.append("Bundle-Version: 1.0.0\n");
// manifestContent.append("Require-Bundle: ");
// manifestContent.append(" org.eclipse.emf.ecore\n");
// manifestContent.append("Bundle-RequiredExecutionEnvironment: " + JAVA_VERSION + "\n");
// IFolder metaInf = project.getFolder("META-INF");
// try {
// metaInf.create(false, true, null);
// createFile("MANIFEST.MF", metaInf, manifestContent.toString(), null);
// } catch (CoreException exception) {
// logger.error("Error while creating the manifest file: ", exception);
// } catch (IOException exception) {
// logger.error("Error while creating the manifest file: ", exception);
// }
// }
// }
| import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import eme.generator.EMFProjectGenerator; | package eme.generator.saving;
/**
* Saving strategy that creates a new project for every saved ecore file.
* @author Timur Saglam
*/
public class NewProjectSaving extends AbstractSavingStrategy {
private String fileName;
private String generatedProjectName;
/**
* Basic constructor.
*/
public NewProjectSaving() {
super(true);
}
/*
* @see eme.generator.saving.AbstractSavingStrategy#beforeSaving()
*/
@Override
protected void beforeSaving(String projectName) {
fileName = projectName; | // Path: src/main/java/eme/generator/EMFProjectGenerator.java
// public final class EMFProjectGenerator {
// private static final String JAVA_VERSION = "JavaSE-1.8";
// private static final Logger logger = LogManager.getLogger(EMFProjectGenerator.class.getName());
//
// private EMFProjectGenerator() {
// // private constructor.
// }
//
// /**
// * Generate a new empty EMFProjectGeneratorproject with a specified name. If a project with that name already exits
// * the new project uses the same name and a number. The actual used name can be received from the returned IProject.
// * @param projectName is the name of the new project.
// * @return the project as IProject object.
// */
// public static IProject createProject(String projectName) {
// IProject project = null;
// IWorkspace workspace = ResourcesPlugin.getWorkspace();
// int version = 2;
// String finalName = projectName;
// project = workspace.getRoot().getProject(projectName);
// while (project.exists()) { // to avoid duplicates:
// finalName = projectName + version;
// version++;
// project = workspace.getRoot().getProject(finalName);
// }
// IJavaProject javaProject = JavaCore.create(project);
// IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(finalName);
// description.setLocation(null);
// try {
// project.create(description, null);
// } catch (CoreException exception) {
// logger.error("Error while creating project resource in workspace", exception);
// }
// List<IClasspathEntry> classpathEntries = new ArrayList<IClasspathEntry>();
// description.setNatureIds(new String[] { JavaCore.NATURE_ID, "org.eclipse.pde.PluginNature" });
// ICommand java = description.newCommand();
// java.setBuilderName(JavaCore.BUILDER_ID);
// ICommand manifest = description.newCommand();
// manifest.setBuilderName("org.eclipse.pde.ManifestBuilder");
// ICommand schema = description.newCommand();
// schema.setBuilderName("org.eclipse.pde.SchemaBuilder");
// ICommand oaw = description.newCommand();
// description.setBuildSpec(new ICommand[] { java, manifest, schema, oaw });
// IFolder srcContainer = null;
// try {
// project.open(null);
// project.setDescription(description, null);
// srcContainer = project.getFolder("src");
// if (!srcContainer.exists()) {
// srcContainer.create(false, true, null);
// }
// } catch (CoreException exception) {
// logger.error("Error while building project description & source folder", exception);
// }
// IClasspathEntry srcClasspathEntry = JavaCore.newSourceEntry(srcContainer.getFullPath());
// classpathEntries.add(0, srcClasspathEntry);
// classpathEntries.add(JavaCore.newContainerEntry(
// new Path("org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/" + JAVA_VERSION)));
// classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins")));
// try {
// javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), null);
// javaProject.setOutputLocation(new Path("/" + finalName + "/bin"), null);
// } catch (JavaModelException exception) {
// logger.error("Error while building classpath & output location", exception);
// }
// createManifest(finalName, project);
// return project;
// }
//
// private static IFile createFile(String name, IContainer container, String content, String charSet) throws CoreException, IOException {
// IFile file = container.getFile(new Path(name));
// InputStream stream = new ByteArrayInputStream(content.getBytes(file.getCharset()));
// if (file.exists()) {
// file.setContents(stream, true, true, null);
// } else {
// file.create(stream, true, null);
// }
// stream.close();
// if (file != null && charSet != null) {
// file.setCharset(charSet, null);
// }
// return file;
// }
//
// private static void createManifest(String projectName, IProject project) {
// StringBuilder manifestContent = new StringBuilder("Manifest-Version: 1.0\n");
// manifestContent.append("Bundle-ManifestVersion: 2\n");
// manifestContent.append("Bundle-Name: " + projectName + "\n");
// manifestContent.append("Bundle-SymbolicName: " + projectName + "; singleton:=true\n");
// manifestContent.append("Bundle-Version: 1.0.0\n");
// manifestContent.append("Require-Bundle: ");
// manifestContent.append(" org.eclipse.emf.ecore\n");
// manifestContent.append("Bundle-RequiredExecutionEnvironment: " + JAVA_VERSION + "\n");
// IFolder metaInf = project.getFolder("META-INF");
// try {
// metaInf.create(false, true, null);
// createFile("MANIFEST.MF", metaInf, manifestContent.toString(), null);
// } catch (CoreException exception) {
// logger.error("Error while creating the manifest file: ", exception);
// } catch (IOException exception) {
// logger.error("Error while creating the manifest file: ", exception);
// }
// }
// }
// Path: src/main/java/eme/generator/saving/NewProjectSaving.java
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import eme.generator.EMFProjectGenerator;
package eme.generator.saving;
/**
* Saving strategy that creates a new project for every saved ecore file.
* @author Timur Saglam
*/
public class NewProjectSaving extends AbstractSavingStrategy {
private String fileName;
private String generatedProjectName;
/**
* Basic constructor.
*/
public NewProjectSaving() {
super(true);
}
/*
* @see eme.generator.saving.AbstractSavingStrategy#beforeSaving()
*/
@Override
protected void beforeSaving(String projectName) {
fileName = projectName; | IProject newProject = EMFProjectGenerator.createProject(projectName + createSuffix(projectName, "Model")); |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/handlers/ProjectHandler.java | // Path: src/main/java/eme/EcoreMetamodelExtraction.java
// public class EcoreMetamodelExtraction {
// private static final Logger logger = LogManager.getLogger(EcoreMetamodelExtraction.class.getName());
// private final JavaProjectExtractor extractor;
// private final EcoreMetamodelGenerator generator;
// private final ExtractionProperties properties;
//
// /**
// * Basic constructor. Builds {@link JavaProjectExtractor}, {@link EcoreMetamodelGenerator} and
// * {@link GenModelGenerator}.
// */
// public EcoreMetamodelExtraction() {
// logger.info("Started EME...");
// properties = new ExtractionProperties();
// extractor = new JavaProjectExtractor();
// generator = new EcoreMetamodelGenerator(properties);
// }
//
// /**
// * Starts the Ecore metamodel extraction for a specific {@link IProject}. The {@link IProject} will be parsed and an
// * Ecore metamodel will be build.
// * @param project is the specific {@link IProject} for the extraction.
// * @return the Ecore metamodel.
// */
// public GeneratedEcoreMetamodel extract(IProject project) {
// logger.info("Started extraction of project " + project.getName());
// check(project); // check if valid.
// IJavaProject javaProject = JavaCore.create(project); // create java project
// IntermediateModel model = extractor.buildIntermediateModel(javaProject);
// selectExtractionScope(model); // select scope if enabled in properties
// GeneratedEcoreMetamodel metamodel = generator.generateMetamodel(model);
// generator.saveMetamodel(); // save metamodel
// return metamodel;
// }
//
// /**
// * Grants access to the {@link ExtractionProperties}.
// * @return the {@link ExtractionProperties}.
// */
// public ExtractionProperties getProperties() {
// return properties;
// }
//
// /**
// * Checks whether a specific {@link IProject} is valid (neither null nor nonexistent)
// * @param project is the specific {@link IProject}.
// */
// private void check(IProject project) {
// if (project == null) {
// throw new IllegalArgumentException("Project can't be null!");
// } else if (!project.exists()) {
// throw new IllegalArgumentException("Project " + project.toString() + "does not exist!");
// }
// }
//
// /**
// * Opens a window for specifying a custom extraction scope. The scope is manifested in the correlating
// * {@link IntermediateModel} through enabling and disabling specific model elements.
// * @param model is the {@link IntermediateModel} for which the extraction scope is specified.
// */
// private void selectExtractionScope(IntermediateModel model) {
// if (properties.get(CUSTOM_EXTRACTION_SCOPE)) {
// new SelectionWindow().open(model);
// }
// }
// }
//
// Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
| import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import eme.EcoreMetamodelExtraction;
import eme.properties.ExtractionProperties; | Object element = ((IStructuredSelection) selection).getFirstElement();
if (element instanceof IProject) {
IProject project = (IProject) element;
if (isJavaProject(project)) {
startExtraction((IProject) element);
} else {
projectMessage(event);
}
} else if (element instanceof IJavaProject) {
startExtraction(((IJavaProject) element).getProject());
} else {
throw new IllegalStateException("Invalid selection: " + element + " is not a project.");
}
}
return null;
}
/**
* Warning message in case of a non-Java project.
*/
private void projectMessage(ExecutionEvent event) throws ExecutionException {
String message = "This project is not a Java project. Therefore, a metamodel cannot be extracted.";
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(window.getShell(), title, message);
}
/**
* Allows the configuration of the {@link ExtractionProperties} of the {@link EcoreMetamodelExtraction}.
* @param properties are the {@link ExtractionProperties}.
*/ | // Path: src/main/java/eme/EcoreMetamodelExtraction.java
// public class EcoreMetamodelExtraction {
// private static final Logger logger = LogManager.getLogger(EcoreMetamodelExtraction.class.getName());
// private final JavaProjectExtractor extractor;
// private final EcoreMetamodelGenerator generator;
// private final ExtractionProperties properties;
//
// /**
// * Basic constructor. Builds {@link JavaProjectExtractor}, {@link EcoreMetamodelGenerator} and
// * {@link GenModelGenerator}.
// */
// public EcoreMetamodelExtraction() {
// logger.info("Started EME...");
// properties = new ExtractionProperties();
// extractor = new JavaProjectExtractor();
// generator = new EcoreMetamodelGenerator(properties);
// }
//
// /**
// * Starts the Ecore metamodel extraction for a specific {@link IProject}. The {@link IProject} will be parsed and an
// * Ecore metamodel will be build.
// * @param project is the specific {@link IProject} for the extraction.
// * @return the Ecore metamodel.
// */
// public GeneratedEcoreMetamodel extract(IProject project) {
// logger.info("Started extraction of project " + project.getName());
// check(project); // check if valid.
// IJavaProject javaProject = JavaCore.create(project); // create java project
// IntermediateModel model = extractor.buildIntermediateModel(javaProject);
// selectExtractionScope(model); // select scope if enabled in properties
// GeneratedEcoreMetamodel metamodel = generator.generateMetamodel(model);
// generator.saveMetamodel(); // save metamodel
// return metamodel;
// }
//
// /**
// * Grants access to the {@link ExtractionProperties}.
// * @return the {@link ExtractionProperties}.
// */
// public ExtractionProperties getProperties() {
// return properties;
// }
//
// /**
// * Checks whether a specific {@link IProject} is valid (neither null nor nonexistent)
// * @param project is the specific {@link IProject}.
// */
// private void check(IProject project) {
// if (project == null) {
// throw new IllegalArgumentException("Project can't be null!");
// } else if (!project.exists()) {
// throw new IllegalArgumentException("Project " + project.toString() + "does not exist!");
// }
// }
//
// /**
// * Opens a window for specifying a custom extraction scope. The scope is manifested in the correlating
// * {@link IntermediateModel} through enabling and disabling specific model elements.
// * @param model is the {@link IntermediateModel} for which the extraction scope is specified.
// */
// private void selectExtractionScope(IntermediateModel model) {
// if (properties.get(CUSTOM_EXTRACTION_SCOPE)) {
// new SelectionWindow().open(model);
// }
// }
// }
//
// Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
// Path: src/main/java/eme/handlers/ProjectHandler.java
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import eme.EcoreMetamodelExtraction;
import eme.properties.ExtractionProperties;
Object element = ((IStructuredSelection) selection).getFirstElement();
if (element instanceof IProject) {
IProject project = (IProject) element;
if (isJavaProject(project)) {
startExtraction((IProject) element);
} else {
projectMessage(event);
}
} else if (element instanceof IJavaProject) {
startExtraction(((IJavaProject) element).getProject());
} else {
throw new IllegalStateException("Invalid selection: " + element + " is not a project.");
}
}
return null;
}
/**
* Warning message in case of a non-Java project.
*/
private void projectMessage(ExecutionEvent event) throws ExecutionException {
String message = "This project is not a Java project. Therefore, a metamodel cannot be extracted.";
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(window.getShell(), title, message);
}
/**
* Allows the configuration of the {@link ExtractionProperties} of the {@link EcoreMetamodelExtraction}.
* @param properties are the {@link ExtractionProperties}.
*/ | protected void configure(ExtractionProperties properties) { |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/handlers/ProjectHandler.java | // Path: src/main/java/eme/EcoreMetamodelExtraction.java
// public class EcoreMetamodelExtraction {
// private static final Logger logger = LogManager.getLogger(EcoreMetamodelExtraction.class.getName());
// private final JavaProjectExtractor extractor;
// private final EcoreMetamodelGenerator generator;
// private final ExtractionProperties properties;
//
// /**
// * Basic constructor. Builds {@link JavaProjectExtractor}, {@link EcoreMetamodelGenerator} and
// * {@link GenModelGenerator}.
// */
// public EcoreMetamodelExtraction() {
// logger.info("Started EME...");
// properties = new ExtractionProperties();
// extractor = new JavaProjectExtractor();
// generator = new EcoreMetamodelGenerator(properties);
// }
//
// /**
// * Starts the Ecore metamodel extraction for a specific {@link IProject}. The {@link IProject} will be parsed and an
// * Ecore metamodel will be build.
// * @param project is the specific {@link IProject} for the extraction.
// * @return the Ecore metamodel.
// */
// public GeneratedEcoreMetamodel extract(IProject project) {
// logger.info("Started extraction of project " + project.getName());
// check(project); // check if valid.
// IJavaProject javaProject = JavaCore.create(project); // create java project
// IntermediateModel model = extractor.buildIntermediateModel(javaProject);
// selectExtractionScope(model); // select scope if enabled in properties
// GeneratedEcoreMetamodel metamodel = generator.generateMetamodel(model);
// generator.saveMetamodel(); // save metamodel
// return metamodel;
// }
//
// /**
// * Grants access to the {@link ExtractionProperties}.
// * @return the {@link ExtractionProperties}.
// */
// public ExtractionProperties getProperties() {
// return properties;
// }
//
// /**
// * Checks whether a specific {@link IProject} is valid (neither null nor nonexistent)
// * @param project is the specific {@link IProject}.
// */
// private void check(IProject project) {
// if (project == null) {
// throw new IllegalArgumentException("Project can't be null!");
// } else if (!project.exists()) {
// throw new IllegalArgumentException("Project " + project.toString() + "does not exist!");
// }
// }
//
// /**
// * Opens a window for specifying a custom extraction scope. The scope is manifested in the correlating
// * {@link IntermediateModel} through enabling and disabling specific model elements.
// * @param model is the {@link IntermediateModel} for which the extraction scope is specified.
// */
// private void selectExtractionScope(IntermediateModel model) {
// if (properties.get(CUSTOM_EXTRACTION_SCOPE)) {
// new SelectionWindow().open(model);
// }
// }
// }
//
// Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
| import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import eme.EcoreMetamodelExtraction;
import eme.properties.ExtractionProperties; | startExtraction(((IJavaProject) element).getProject());
} else {
throw new IllegalStateException("Invalid selection: " + element + " is not a project.");
}
}
return null;
}
/**
* Warning message in case of a non-Java project.
*/
private void projectMessage(ExecutionEvent event) throws ExecutionException {
String message = "This project is not a Java project. Therefore, a metamodel cannot be extracted.";
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(window.getShell(), title, message);
}
/**
* Allows the configuration of the {@link ExtractionProperties} of the {@link EcoreMetamodelExtraction}.
* @param properties are the {@link ExtractionProperties}.
*/
protected void configure(ExtractionProperties properties) {
// Default: do nothing, use default properties.
}
/**
* Starts the extraction by calling an extraction method from the class {@link EcoreMetamodelExtraction}.
* @param project is the parameter for the methods that is called.
*/
protected void startExtraction(IProject project) { | // Path: src/main/java/eme/EcoreMetamodelExtraction.java
// public class EcoreMetamodelExtraction {
// private static final Logger logger = LogManager.getLogger(EcoreMetamodelExtraction.class.getName());
// private final JavaProjectExtractor extractor;
// private final EcoreMetamodelGenerator generator;
// private final ExtractionProperties properties;
//
// /**
// * Basic constructor. Builds {@link JavaProjectExtractor}, {@link EcoreMetamodelGenerator} and
// * {@link GenModelGenerator}.
// */
// public EcoreMetamodelExtraction() {
// logger.info("Started EME...");
// properties = new ExtractionProperties();
// extractor = new JavaProjectExtractor();
// generator = new EcoreMetamodelGenerator(properties);
// }
//
// /**
// * Starts the Ecore metamodel extraction for a specific {@link IProject}. The {@link IProject} will be parsed and an
// * Ecore metamodel will be build.
// * @param project is the specific {@link IProject} for the extraction.
// * @return the Ecore metamodel.
// */
// public GeneratedEcoreMetamodel extract(IProject project) {
// logger.info("Started extraction of project " + project.getName());
// check(project); // check if valid.
// IJavaProject javaProject = JavaCore.create(project); // create java project
// IntermediateModel model = extractor.buildIntermediateModel(javaProject);
// selectExtractionScope(model); // select scope if enabled in properties
// GeneratedEcoreMetamodel metamodel = generator.generateMetamodel(model);
// generator.saveMetamodel(); // save metamodel
// return metamodel;
// }
//
// /**
// * Grants access to the {@link ExtractionProperties}.
// * @return the {@link ExtractionProperties}.
// */
// public ExtractionProperties getProperties() {
// return properties;
// }
//
// /**
// * Checks whether a specific {@link IProject} is valid (neither null nor nonexistent)
// * @param project is the specific {@link IProject}.
// */
// private void check(IProject project) {
// if (project == null) {
// throw new IllegalArgumentException("Project can't be null!");
// } else if (!project.exists()) {
// throw new IllegalArgumentException("Project " + project.toString() + "does not exist!");
// }
// }
//
// /**
// * Opens a window for specifying a custom extraction scope. The scope is manifested in the correlating
// * {@link IntermediateModel} through enabling and disabling specific model elements.
// * @param model is the {@link IntermediateModel} for which the extraction scope is specified.
// */
// private void selectExtractionScope(IntermediateModel model) {
// if (properties.get(CUSTOM_EXTRACTION_SCOPE)) {
// new SelectionWindow().open(model);
// }
// }
// }
//
// Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
// Path: src/main/java/eme/handlers/ProjectHandler.java
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import eme.EcoreMetamodelExtraction;
import eme.properties.ExtractionProperties;
startExtraction(((IJavaProject) element).getProject());
} else {
throw new IllegalStateException("Invalid selection: " + element + " is not a project.");
}
}
return null;
}
/**
* Warning message in case of a non-Java project.
*/
private void projectMessage(ExecutionEvent event) throws ExecutionException {
String message = "This project is not a Java project. Therefore, a metamodel cannot be extracted.";
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(window.getShell(), title, message);
}
/**
* Allows the configuration of the {@link ExtractionProperties} of the {@link EcoreMetamodelExtraction}.
* @param properties are the {@link ExtractionProperties}.
*/
protected void configure(ExtractionProperties properties) {
// Default: do nothing, use default properties.
}
/**
* Starts the extraction by calling an extraction method from the class {@link EcoreMetamodelExtraction}.
* @param project is the parameter for the methods that is called.
*/
protected void startExtraction(IProject project) { | EcoreMetamodelExtraction extraction = new EcoreMetamodelExtraction(); // EME instance |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/model/ExtractedClass.java | // Path: src/main/java/eme/model/datatypes/ExtractedDataType.java
// public class ExtractedDataType {
// private final int arrayDimension;
// private String fullTypeName;
// private List<ExtractedDataType> genericArguments;
// private String typeName;
// private WildcardStatus wildcardStatus;
//
// /**
// * Basic constructor, takes the full and the simple name.
// * @param fullName is the full name of the data type, like "java.lang.String",
// * "java.util.list" and "char".
// * @param arrayDimension is the amount of array dimensions, should be 0 if it is
// * not an array.
// */
// public ExtractedDataType(String fullName, int arrayDimension) {
// this.fullTypeName = fullName;
// this.arrayDimension = arrayDimension;
// genericArguments = new LinkedList<ExtractedDataType>();
// wildcardStatus = WildcardStatus.NO_WILDCARD;
// buildNames(); // build full and simple name
// }
//
// /**
// * accessor for the array dimension.
// * @return the array dimension, 0 if the type is not an array.
// */
// public int getArrayDimension() {
// return arrayDimension;
// }
//
// /**
// * accessor for the full array type name, which includes the packages but NOT
// * array brackets.
// * @return the full type name.
// */
// public String getFullArrayType() { // TODO (MEDIUM) remove this and move [] naming to generator.
// if (isArray()) {
// return fullTypeName.substring(0, fullTypeName.length() - 2 * arrayDimension);
// }
// return fullTypeName;
// }
//
// /**
// * accessor for the full type name, which includes the packages and the array
// * brackets.
// * @return the full type name.
// */
// public String getFullType() {
// return fullTypeName;
// }
//
// /**
// * accessor for the generic arguments.
// * @return the List of generic arguments of this data type.
// */
// public List<ExtractedDataType> getGenericArguments() {
// return genericArguments;
// }
//
// /**
// * accessor for the simple type name, which is the basic name. If it is an array
// * it is the special array name which does not match the Java code (e.g.
// * intArray2D).
// * @return the simple type name or, if it is an array type, the array type name.
// */
// public String getType() {
// return typeName;
// }
//
// /**
// * Generates a type string for this {@link ExtractedDataType}. It contains
// * information about the data type and its generic arguments. For example
// * "Map<String, Object>".
// * @return the type string.
// */
// public String getTypeString() {
// String result = fullTypeName;
// if (!genericArguments.isEmpty()) {
// result += '<';
// for (ExtractedDataType argument : genericArguments) {
// result += argument.getFullType() + ", ";
// }
// result = result.substring(0, result.length() - 2) + '>';
// }
// return result;
// }
//
// /**
// * accessor for the wild card status.
// * @return the wild card status.
// */
// public WildcardStatus getWildcardStatus() {
// return wildcardStatus;
// }
//
// /**
// * Checks whether the data type is an array.
// * @return true if it is an array.
// */
// public boolean isArray() {
// return arrayDimension > 0;
// }
//
// /**
// * Checks whether the data type is a generic type.
// * @return true if it is generic.
// */
// public boolean isGeneric() {
// return !genericArguments.isEmpty();
// }
//
// /**
// * Checks whether the data type is a list type, which means it is of type
// * {@link List}.
// * @return true if it is.
// */
// public boolean isListType() {
// return List.class.getName().equals(fullTypeName) && genericArguments.size() == 1;
// }
//
// /**
// * Checks whether the data type is an wild card.
// * @return true if it is an wild card.
// */
// public boolean isWildcard() {
// return wildcardStatus != WildcardStatus.NO_WILDCARD;
// }
//
// /**
// * mutator for the generic arguments.
// * @param genericArguments is the list of generic arguments.
// */
// public void setGenericArguments(List<ExtractedDataType> genericArguments) {
// this.genericArguments = genericArguments;
// }
//
// /**
// * Sets the wild card status of the data type.
// * @param status is the status to set.
// */
// public void setWildcardStatus(WildcardStatus status) {
// wildcardStatus = status;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(" + getTypeString() + ")";
// }
//
// /**
// * Builds the full and simple name from the initial full name. The full name has
// * to be set.
// */
// private void buildNames() {
// typeName = fullTypeName.contains(".") ? fullTypeName.substring(fullTypeName.lastIndexOf('.') + 1) : fullTypeName;
// typeName = isArray() ? typeName + "Array" : typeName; // add "Array" if is array
// typeName = arrayDimension > 1 ? typeName + arrayDimension + "D" : typeName; // add dimension
// for (int i = 0; i < arrayDimension; i++) { // adjust array names to dimension
// this.fullTypeName += "[]";
// }
// }
// }
| import eme.model.datatypes.ExtractedDataType; | package eme.model;
/**
* Represents a class in the {@link IntermediateModel}.
* @author Timur Saglam
*/
public class ExtractedClass extends ExtractedType {
private final boolean abstractClass;
private final boolean throwable;
/**
* Basic constructor.
* @param fullName is the full name, containing name and package name.
* @param abstractClass determines whether the class is abstract or not.
* @param throwable determines whether the class inherits from {@link java.lang.Throwable}
*/
public ExtractedClass(String fullName, boolean abstractClass, boolean throwable) {
super(fullName);
this.abstractClass = abstractClass;
this.throwable = throwable;
}
/**
* accessor for the super class.
* @return the super class.
*/ | // Path: src/main/java/eme/model/datatypes/ExtractedDataType.java
// public class ExtractedDataType {
// private final int arrayDimension;
// private String fullTypeName;
// private List<ExtractedDataType> genericArguments;
// private String typeName;
// private WildcardStatus wildcardStatus;
//
// /**
// * Basic constructor, takes the full and the simple name.
// * @param fullName is the full name of the data type, like "java.lang.String",
// * "java.util.list" and "char".
// * @param arrayDimension is the amount of array dimensions, should be 0 if it is
// * not an array.
// */
// public ExtractedDataType(String fullName, int arrayDimension) {
// this.fullTypeName = fullName;
// this.arrayDimension = arrayDimension;
// genericArguments = new LinkedList<ExtractedDataType>();
// wildcardStatus = WildcardStatus.NO_WILDCARD;
// buildNames(); // build full and simple name
// }
//
// /**
// * accessor for the array dimension.
// * @return the array dimension, 0 if the type is not an array.
// */
// public int getArrayDimension() {
// return arrayDimension;
// }
//
// /**
// * accessor for the full array type name, which includes the packages but NOT
// * array brackets.
// * @return the full type name.
// */
// public String getFullArrayType() { // TODO (MEDIUM) remove this and move [] naming to generator.
// if (isArray()) {
// return fullTypeName.substring(0, fullTypeName.length() - 2 * arrayDimension);
// }
// return fullTypeName;
// }
//
// /**
// * accessor for the full type name, which includes the packages and the array
// * brackets.
// * @return the full type name.
// */
// public String getFullType() {
// return fullTypeName;
// }
//
// /**
// * accessor for the generic arguments.
// * @return the List of generic arguments of this data type.
// */
// public List<ExtractedDataType> getGenericArguments() {
// return genericArguments;
// }
//
// /**
// * accessor for the simple type name, which is the basic name. If it is an array
// * it is the special array name which does not match the Java code (e.g.
// * intArray2D).
// * @return the simple type name or, if it is an array type, the array type name.
// */
// public String getType() {
// return typeName;
// }
//
// /**
// * Generates a type string for this {@link ExtractedDataType}. It contains
// * information about the data type and its generic arguments. For example
// * "Map<String, Object>".
// * @return the type string.
// */
// public String getTypeString() {
// String result = fullTypeName;
// if (!genericArguments.isEmpty()) {
// result += '<';
// for (ExtractedDataType argument : genericArguments) {
// result += argument.getFullType() + ", ";
// }
// result = result.substring(0, result.length() - 2) + '>';
// }
// return result;
// }
//
// /**
// * accessor for the wild card status.
// * @return the wild card status.
// */
// public WildcardStatus getWildcardStatus() {
// return wildcardStatus;
// }
//
// /**
// * Checks whether the data type is an array.
// * @return true if it is an array.
// */
// public boolean isArray() {
// return arrayDimension > 0;
// }
//
// /**
// * Checks whether the data type is a generic type.
// * @return true if it is generic.
// */
// public boolean isGeneric() {
// return !genericArguments.isEmpty();
// }
//
// /**
// * Checks whether the data type is a list type, which means it is of type
// * {@link List}.
// * @return true if it is.
// */
// public boolean isListType() {
// return List.class.getName().equals(fullTypeName) && genericArguments.size() == 1;
// }
//
// /**
// * Checks whether the data type is an wild card.
// * @return true if it is an wild card.
// */
// public boolean isWildcard() {
// return wildcardStatus != WildcardStatus.NO_WILDCARD;
// }
//
// /**
// * mutator for the generic arguments.
// * @param genericArguments is the list of generic arguments.
// */
// public void setGenericArguments(List<ExtractedDataType> genericArguments) {
// this.genericArguments = genericArguments;
// }
//
// /**
// * Sets the wild card status of the data type.
// * @param status is the status to set.
// */
// public void setWildcardStatus(WildcardStatus status) {
// wildcardStatus = status;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "(" + getTypeString() + ")";
// }
//
// /**
// * Builds the full and simple name from the initial full name. The full name has
// * to be set.
// */
// private void buildNames() {
// typeName = fullTypeName.contains(".") ? fullTypeName.substring(fullTypeName.lastIndexOf('.') + 1) : fullTypeName;
// typeName = isArray() ? typeName + "Array" : typeName; // add "Array" if is array
// typeName = arrayDimension > 1 ? typeName + arrayDimension + "D" : typeName; // add dimension
// for (int i = 0; i < arrayDimension; i++) { // adjust array names to dimension
// this.fullTypeName += "[]";
// }
// }
// }
// Path: src/main/java/eme/model/ExtractedClass.java
import eme.model.datatypes.ExtractedDataType;
package eme.model;
/**
* Represents a class in the {@link IntermediateModel}.
* @author Timur Saglam
*/
public class ExtractedClass extends ExtractedType {
private final boolean abstractClass;
private final boolean throwable;
/**
* Basic constructor.
* @param fullName is the full name, containing name and package name.
* @param abstractClass determines whether the class is abstract or not.
* @param throwable determines whether the class inherits from {@link java.lang.Throwable}
*/
public ExtractedClass(String fullName, boolean abstractClass, boolean throwable) {
super(fullName);
this.abstractClass = abstractClass;
this.throwable = throwable;
}
/**
* accessor for the super class.
* @return the super class.
*/ | public ExtractedDataType getSuperClass() { |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/extractor/JDTUtil.java | // Path: src/main/java/eme/model/datatypes/AccessLevelModifier.java
// public enum AccessLevelModifier {
// /**
// * Represents the default Java modifier.
// */
// NO_MODIFIER,
//
// /**
// * Represents the Java modifier <code>private</code>.
// */
// PRIVATE,
//
// /**
// * Represents the Java modifier <code>protected</code>.
// */
// PROTECTED,
//
// /**
// * Represents the Java modifier <code>public</code>.
// */
// PUBLIC;
// }
//
// Path: src/main/java/eme/model/datatypes/WildcardStatus.java
// public enum WildcardStatus {
// /**
// * Is not a wild card data type.
// */
// NO_WILDCARD,
//
// /**
// * Is a basic wild card data type like <code>?</code>
// */
// UNBOUND,
//
// /**
// * Is a wild card data type with lower bound like <code>? super SomeClass/<code>
// */
// LOWER_BOUND,
//
// /**
// * Is a wild card data type with upper bound like <code>? extends SomeClass/<code>
// */
// UPPER_BOUND;
// }
| import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import eme.model.datatypes.AccessLevelModifier;
import eme.model.datatypes.WildcardStatus; | package eme.extractor;
/**
* This class offers simple adapter methods for JDT functionality that makes code unreadable.
* @author Timur Saglam
*/
public final class JDTUtil {
/**
* Private constructor for static class.
*/
private JDTUtil() {
// Private constructor.
}
/**
* Determines the access level modifier of an {@link IMember} and returns it as {@link AccessLevelModifier}.
* @param member is the {@link IMember}.
* @return the {@link AccessLevelModifier}.
* @throws JavaModelException if there is a problem with the JDT API.
*/ | // Path: src/main/java/eme/model/datatypes/AccessLevelModifier.java
// public enum AccessLevelModifier {
// /**
// * Represents the default Java modifier.
// */
// NO_MODIFIER,
//
// /**
// * Represents the Java modifier <code>private</code>.
// */
// PRIVATE,
//
// /**
// * Represents the Java modifier <code>protected</code>.
// */
// PROTECTED,
//
// /**
// * Represents the Java modifier <code>public</code>.
// */
// PUBLIC;
// }
//
// Path: src/main/java/eme/model/datatypes/WildcardStatus.java
// public enum WildcardStatus {
// /**
// * Is not a wild card data type.
// */
// NO_WILDCARD,
//
// /**
// * Is a basic wild card data type like <code>?</code>
// */
// UNBOUND,
//
// /**
// * Is a wild card data type with lower bound like <code>? super SomeClass/<code>
// */
// LOWER_BOUND,
//
// /**
// * Is a wild card data type with upper bound like <code>? extends SomeClass/<code>
// */
// UPPER_BOUND;
// }
// Path: src/main/java/eme/extractor/JDTUtil.java
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import eme.model.datatypes.AccessLevelModifier;
import eme.model.datatypes.WildcardStatus;
package eme.extractor;
/**
* This class offers simple adapter methods for JDT functionality that makes code unreadable.
* @author Timur Saglam
*/
public final class JDTUtil {
/**
* Private constructor for static class.
*/
private JDTUtil() {
// Private constructor.
}
/**
* Determines the access level modifier of an {@link IMember} and returns it as {@link AccessLevelModifier}.
* @param member is the {@link IMember}.
* @return the {@link AccessLevelModifier}.
* @throws JavaModelException if there is a problem with the JDT API.
*/ | public static AccessLevelModifier getModifier(IMember member) throws JavaModelException { |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/extractor/JDTUtil.java | // Path: src/main/java/eme/model/datatypes/AccessLevelModifier.java
// public enum AccessLevelModifier {
// /**
// * Represents the default Java modifier.
// */
// NO_MODIFIER,
//
// /**
// * Represents the Java modifier <code>private</code>.
// */
// PRIVATE,
//
// /**
// * Represents the Java modifier <code>protected</code>.
// */
// PROTECTED,
//
// /**
// * Represents the Java modifier <code>public</code>.
// */
// PUBLIC;
// }
//
// Path: src/main/java/eme/model/datatypes/WildcardStatus.java
// public enum WildcardStatus {
// /**
// * Is not a wild card data type.
// */
// NO_WILDCARD,
//
// /**
// * Is a basic wild card data type like <code>?</code>
// */
// UNBOUND,
//
// /**
// * Is a wild card data type with lower bound like <code>? super SomeClass/<code>
// */
// LOWER_BOUND,
//
// /**
// * Is a wild card data type with upper bound like <code>? extends SomeClass/<code>
// */
// UPPER_BOUND;
// }
| import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import eme.model.datatypes.AccessLevelModifier;
import eme.model.datatypes.WildcardStatus; | package eme.extractor;
/**
* This class offers simple adapter methods for JDT functionality that makes code unreadable.
* @author Timur Saglam
*/
public final class JDTUtil {
/**
* Private constructor for static class.
*/
private JDTUtil() {
// Private constructor.
}
/**
* Determines the access level modifier of an {@link IMember} and returns it as {@link AccessLevelModifier}.
* @param member is the {@link IMember}.
* @return the {@link AccessLevelModifier}.
* @throws JavaModelException if there is a problem with the JDT API.
*/
public static AccessLevelModifier getModifier(IMember member) throws JavaModelException {
int flags = member.getFlags();
if (Flags.isPublic(flags)) {
return AccessLevelModifier.PUBLIC;
} else if (Flags.isPrivate(flags)) {
return AccessLevelModifier.PRIVATE;
} else if (Flags.isProtected(flags)) {
return AccessLevelModifier.PROTECTED;
} else if (member.getDeclaringType().isInterface()) {
return AccessLevelModifier.PUBLIC; // default visibility in interface is public.
}
return AccessLevelModifier.NO_MODIFIER; // default visibility in any other case is package visibility.
}
/**
* Returns the fully qualified name of an {@link IType}, including qualification for any containing types and
* packages. The character '.' is used as enclosing type separator.
* @param type is the {@link IType}.
* @return the fully qualified name.
* @see eme.generator.saving.AbstractSavingStrategy#filePath()
*/
public static String getName(IType type) {
return type.getFullyQualifiedName('.');
}
/**
* Determines the {@link WildcardStatus} of an signature string.
* @param signature is the signature string.
* @return the {@link WildcardStatus}.
*/ | // Path: src/main/java/eme/model/datatypes/AccessLevelModifier.java
// public enum AccessLevelModifier {
// /**
// * Represents the default Java modifier.
// */
// NO_MODIFIER,
//
// /**
// * Represents the Java modifier <code>private</code>.
// */
// PRIVATE,
//
// /**
// * Represents the Java modifier <code>protected</code>.
// */
// PROTECTED,
//
// /**
// * Represents the Java modifier <code>public</code>.
// */
// PUBLIC;
// }
//
// Path: src/main/java/eme/model/datatypes/WildcardStatus.java
// public enum WildcardStatus {
// /**
// * Is not a wild card data type.
// */
// NO_WILDCARD,
//
// /**
// * Is a basic wild card data type like <code>?</code>
// */
// UNBOUND,
//
// /**
// * Is a wild card data type with lower bound like <code>? super SomeClass/<code>
// */
// LOWER_BOUND,
//
// /**
// * Is a wild card data type with upper bound like <code>? extends SomeClass/<code>
// */
// UPPER_BOUND;
// }
// Path: src/main/java/eme/extractor/JDTUtil.java
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import eme.model.datatypes.AccessLevelModifier;
import eme.model.datatypes.WildcardStatus;
package eme.extractor;
/**
* This class offers simple adapter methods for JDT functionality that makes code unreadable.
* @author Timur Saglam
*/
public final class JDTUtil {
/**
* Private constructor for static class.
*/
private JDTUtil() {
// Private constructor.
}
/**
* Determines the access level modifier of an {@link IMember} and returns it as {@link AccessLevelModifier}.
* @param member is the {@link IMember}.
* @return the {@link AccessLevelModifier}.
* @throws JavaModelException if there is a problem with the JDT API.
*/
public static AccessLevelModifier getModifier(IMember member) throws JavaModelException {
int flags = member.getFlags();
if (Flags.isPublic(flags)) {
return AccessLevelModifier.PUBLIC;
} else if (Flags.isPrivate(flags)) {
return AccessLevelModifier.PRIVATE;
} else if (Flags.isProtected(flags)) {
return AccessLevelModifier.PROTECTED;
} else if (member.getDeclaringType().isInterface()) {
return AccessLevelModifier.PUBLIC; // default visibility in interface is public.
}
return AccessLevelModifier.NO_MODIFIER; // default visibility in any other case is package visibility.
}
/**
* Returns the fully qualified name of an {@link IType}, including qualification for any containing types and
* packages. The character '.' is used as enclosing type separator.
* @param type is the {@link IType}.
* @return the fully qualified name.
* @see eme.generator.saving.AbstractSavingStrategy#filePath()
*/
public static String getName(IType type) {
return type.getFullyQualifiedName('.');
}
/**
* Determines the {@link WildcardStatus} of an signature string.
* @param signature is the signature string.
* @return the {@link WildcardStatus}.
*/ | public static WildcardStatus getWildcardStatus(String signature) { |
tsaglam/EcoreMetamodelExtraction | src/main/java/eme/generator/hierarchies/ExternalTypeHierarchy.java | // Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
//
// Path: src/main/java/eme/properties/TextProperty.java
// public enum TextProperty implements ITextProperty {
// DATATYPE_PACKAGE("DataTypePackageName", "DATATYPES"),
// DEFAULT_PACKAGE("DefaultPackageName", "DEFAULT"),
// DUMMY_NAME("DummyClassName", "DUMMY"),
// ROOT_NAME("RootContainerName", "ROOT"),
// NESTED_TYPE_PACKAGE("NestedTypePackageSuffix", "InnerTypes"),
// PROJECT_SUFFIX("ProjectSuffix", "Model"),
// SAVING_STRATEGY("SavingStrategy", "NewProject");
//
// private final String defaultValue;
// private final String key;
//
// /**
// * Private constructor for enum values with key and default value of an extraction property.
// * @param key is the key of the property.
// * @param defaultValue is the default value of the property.
// */
// TextProperty(String key, String defaultValue) {
// this.key = key;
// this.defaultValue = defaultValue;
// }
//
// @Override
// public String getDefaultValue() {
// return defaultValue;
// }
//
// @Override
// public String getKey() {
// return key;
// }
// }
| import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EPackage;
import eme.properties.ExtractionProperties;
import eme.properties.TextProperty; | package eme.generator.hierarchies;
/**
* This class allows to build an external type package hierarchy from EDataTypes.
* @author Timur Saglam
*/
public class ExternalTypeHierarchy extends EPackageHierarchy {
/**
* Simple constructor, builds the base for the hierarchy.
* @param root is the root {@link EPackage} of the metamodel.
* @param properties is the instance of the {@link ExtractionProperties} class.
*/
public ExternalTypeHierarchy(EPackage root, ExtractionProperties properties) { | // Path: src/main/java/eme/properties/ExtractionProperties.java
// public class ExtractionProperties extends AbstractProperties<TextProperty, BinaryProperty> {
// /**
// * Basic constructor, sets the file name, file description and symbolic bundle name.
// */
// public ExtractionProperties() {
// super("user.properties", "Use this file to configure the Ecore metamodel extraction.", "EcoreMetamodelExtraction");
// }
// }
//
// Path: src/main/java/eme/properties/TextProperty.java
// public enum TextProperty implements ITextProperty {
// DATATYPE_PACKAGE("DataTypePackageName", "DATATYPES"),
// DEFAULT_PACKAGE("DefaultPackageName", "DEFAULT"),
// DUMMY_NAME("DummyClassName", "DUMMY"),
// ROOT_NAME("RootContainerName", "ROOT"),
// NESTED_TYPE_PACKAGE("NestedTypePackageSuffix", "InnerTypes"),
// PROJECT_SUFFIX("ProjectSuffix", "Model"),
// SAVING_STRATEGY("SavingStrategy", "NewProject");
//
// private final String defaultValue;
// private final String key;
//
// /**
// * Private constructor for enum values with key and default value of an extraction property.
// * @param key is the key of the property.
// * @param defaultValue is the default value of the property.
// */
// TextProperty(String key, String defaultValue) {
// this.key = key;
// this.defaultValue = defaultValue;
// }
//
// @Override
// public String getDefaultValue() {
// return defaultValue;
// }
//
// @Override
// public String getKey() {
// return key;
// }
// }
// Path: src/main/java/eme/generator/hierarchies/ExternalTypeHierarchy.java
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EPackage;
import eme.properties.ExtractionProperties;
import eme.properties.TextProperty;
package eme.generator.hierarchies;
/**
* This class allows to build an external type package hierarchy from EDataTypes.
* @author Timur Saglam
*/
public class ExternalTypeHierarchy extends EPackageHierarchy {
/**
* Simple constructor, builds the base for the hierarchy.
* @param root is the root {@link EPackage} of the metamodel.
* @param properties is the instance of the {@link ExtractionProperties} class.
*/
public ExternalTypeHierarchy(EPackage root, ExtractionProperties properties) { | super(generatePackage(properties.get(TextProperty.DATATYPE_PACKAGE), root), properties); |
hufeiya/CoolSignIn | Server/src/com/hufeiya/DAO/CourseDAO.java | // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
| import java.util.List;
import java.util.Set;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.Course; | package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for
* Course entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see com.hufeiya.DAO.Course
* @author MyEclipse Persistence Tools
*/
public class CourseDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(CourseDAO.class);
// property constants
public static final String COURSE_NAME = "courseName";
public static final String START_DATES = "startDates";
public static final String NUMBER_OF_WEEKS = "numberOfWeeks";
| // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
// Path: Server/src/com/hufeiya/DAO/CourseDAO.java
import java.util.List;
import java.util.Set;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.Course;
package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for
* Course entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see com.hufeiya.DAO.Course
* @author MyEclipse Persistence Tools
*/
public class CourseDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(CourseDAO.class);
// property constants
public static final String COURSE_NAME = "courseName";
public static final String START_DATES = "startDates";
public static final String NUMBER_OF_WEEKS = "numberOfWeeks";
| public void save(Course transientInstance) { |
hufeiya/CoolSignIn | Server/src/com/hufeiya/jsonObject/JsonSignInfo.java | // Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
| import com.hufeiya.entity.SignInfo; | package com.hufeiya.jsonObject;
/**
* SignInfo entity. @author MyEclipse Persistence Tools
*/
public class JsonSignInfo {
// Fields
private Integer signId;
private String studentName;
private String studengNo;
private String signDetail;
private Integer signTimes;
private String lastSignPhoto;
// Constructors
/** default constructor */
public JsonSignInfo() {
}
/** full constructor */
public JsonSignInfo(String studentName,String studentNo, String signDetail,
Integer signTimes, String lastSignPhoto) {
this.setStudentName(studentName);
this.setStudengNo(studentNo);
this.signDetail = signDetail;
this.signTimes = signTimes;
this.lastSignPhoto = lastSignPhoto;
}
| // Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
// Path: Server/src/com/hufeiya/jsonObject/JsonSignInfo.java
import com.hufeiya.entity.SignInfo;
package com.hufeiya.jsonObject;
/**
* SignInfo entity. @author MyEclipse Persistence Tools
*/
public class JsonSignInfo {
// Fields
private Integer signId;
private String studentName;
private String studengNo;
private String signDetail;
private Integer signTimes;
private String lastSignPhoto;
// Constructors
/** default constructor */
public JsonSignInfo() {
}
/** full constructor */
public JsonSignInfo(String studentName,String studentNo, String signDetail,
Integer signTimes, String lastSignPhoto) {
this.setStudentName(studentName);
this.setStudengNo(studentNo);
this.signDetail = signDetail;
this.signTimes = signTimes;
this.lastSignPhoto = lastSignPhoto;
}
| public JsonSignInfo(SignInfo s) { |
hufeiya/CoolSignIn | AndroidClient/app/src/main/java/com/hufeiya/SignIn/adapter/AvatarAdapter.java | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/Avatar.java
// public enum Avatar {
//
// ONE(R.drawable.avatar_1),
// TWO(R.drawable.avatar_2),
// THREE(R.drawable.avatar_3),
// FOUR(R.drawable.avatar_4),
// FIVE(R.drawable.avatar_5),
// SIX(R.drawable.avatar_6),
// SEVEN(R.drawable.avatar_7),
// EIGHT(R.drawable.avatar_8),
// NINE(R.drawable.avatar_9),
// TEN(R.drawable.avatar_10),
// ELEVEN(R.drawable.avatar_11),
// TWELVE(R.drawable.avatar_12),
// THIRTEEN(R.drawable.avatar_13),
// FOURTEEN(R.drawable.avatar_14),
// FIFTEEN(R.drawable.avatar_15),
// SIXTEEN(R.drawable.avatar_16);
//
// private static final String TAG = "Avatar";
//
// private final int mResId;
//
// Avatar(@DrawableRes final int resId) {
// mResId = resId;
// }
//
// @DrawableRes
// public int getDrawableId() {
// return mResId;
// }
//
// public String getNameForAccessibility() {
// return TAG + " " + ordinal() + 1;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/AvatarView.java
// public class AvatarView extends ImageView implements Checkable {
//
// private boolean mChecked;
//
// public AvatarView(Context context) {
// this(context, null);
// }
//
// public AvatarView(Context context, AttributeSet attrs) {
// this(context, attrs, 0);
// }
//
// public AvatarView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @Override
// public boolean isChecked() {
// return mChecked;
// }
//
// @Override
// public void setChecked(boolean b) {
// mChecked = b;
// invalidate();
// }
//
// @Override
// public void toggle() {
// setChecked(!mChecked);
// }
//
// /**
// * Set the image for this avatar. Will be used to create a round version of this avatar.
// *
// * @param resId The image's resource id.
// */
// @SuppressLint("NewApi")
// public void setAvatar(@DrawableRes int resId) {
// if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
// setClipToOutline(true);
// setImageResource(resId);
// } else {
// setAvatarPreLollipop(resId);
// }
// }
//
// private void setAvatarPreLollipop(@DrawableRes int resId) {
// Drawable drawable = ResourcesCompat.getDrawable(getResources(), resId,
// getContext().getTheme());
// BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
// @SuppressWarnings("ConstantConditions")
// RoundedBitmapDrawable roundedDrawable = RoundedBitmapDrawableFactory.create(getResources(),
// bitmapDrawable.getBitmap());
// roundedDrawable.setCircular(true);
// setImageDrawable(roundedDrawable);
// }
//
// @Override
// protected void onDraw(@NonNull Canvas canvas) {
// super.onDraw(canvas);
// if (mChecked) {
// Drawable border = ContextCompat.getDrawable(getContext(), R.drawable.selector_avatar);
// border.setBounds(0, 0, getWidth(), getHeight());
// border.draw(canvas);
// }
// }
//
// @Override
// @SuppressLint("NewApi")
// protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// super.onSizeChanged(w, h, oldw, oldh);
// if (ApiLevelHelper.isLowerThan(Build.VERSION_CODES.LOLLIPOP)) {
// return;
// }
// if (w > 0 && h > 0) {
// setOutlineProvider(new RoundOutlineProvider(Math.min(w, h)));
// }
// }
// }
| import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.hufeiya.SignIn.R;
import com.hufeiya.SignIn.model.Avatar;
import com.hufeiya.SignIn.widget.AvatarView; | /*
* Copyright 2015 Google Inc.
*
* 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.hufeiya.SignIn.adapter;
/**
* Adapter to display {@link Avatar} icons.
*/
public class AvatarAdapter extends BaseAdapter {
private static final Avatar[] mAvatars = Avatar.values();
private final LayoutInflater mLayoutInflater;
public AvatarAdapter(Context context) {
mLayoutInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = mLayoutInflater.inflate(R.layout.item_avatar, parent, false);
} | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/Avatar.java
// public enum Avatar {
//
// ONE(R.drawable.avatar_1),
// TWO(R.drawable.avatar_2),
// THREE(R.drawable.avatar_3),
// FOUR(R.drawable.avatar_4),
// FIVE(R.drawable.avatar_5),
// SIX(R.drawable.avatar_6),
// SEVEN(R.drawable.avatar_7),
// EIGHT(R.drawable.avatar_8),
// NINE(R.drawable.avatar_9),
// TEN(R.drawable.avatar_10),
// ELEVEN(R.drawable.avatar_11),
// TWELVE(R.drawable.avatar_12),
// THIRTEEN(R.drawable.avatar_13),
// FOURTEEN(R.drawable.avatar_14),
// FIFTEEN(R.drawable.avatar_15),
// SIXTEEN(R.drawable.avatar_16);
//
// private static final String TAG = "Avatar";
//
// private final int mResId;
//
// Avatar(@DrawableRes final int resId) {
// mResId = resId;
// }
//
// @DrawableRes
// public int getDrawableId() {
// return mResId;
// }
//
// public String getNameForAccessibility() {
// return TAG + " " + ordinal() + 1;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/AvatarView.java
// public class AvatarView extends ImageView implements Checkable {
//
// private boolean mChecked;
//
// public AvatarView(Context context) {
// this(context, null);
// }
//
// public AvatarView(Context context, AttributeSet attrs) {
// this(context, attrs, 0);
// }
//
// public AvatarView(Context context, AttributeSet attrs, int defStyle) {
// super(context, attrs, defStyle);
// }
//
// @Override
// public boolean isChecked() {
// return mChecked;
// }
//
// @Override
// public void setChecked(boolean b) {
// mChecked = b;
// invalidate();
// }
//
// @Override
// public void toggle() {
// setChecked(!mChecked);
// }
//
// /**
// * Set the image for this avatar. Will be used to create a round version of this avatar.
// *
// * @param resId The image's resource id.
// */
// @SuppressLint("NewApi")
// public void setAvatar(@DrawableRes int resId) {
// if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
// setClipToOutline(true);
// setImageResource(resId);
// } else {
// setAvatarPreLollipop(resId);
// }
// }
//
// private void setAvatarPreLollipop(@DrawableRes int resId) {
// Drawable drawable = ResourcesCompat.getDrawable(getResources(), resId,
// getContext().getTheme());
// BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
// @SuppressWarnings("ConstantConditions")
// RoundedBitmapDrawable roundedDrawable = RoundedBitmapDrawableFactory.create(getResources(),
// bitmapDrawable.getBitmap());
// roundedDrawable.setCircular(true);
// setImageDrawable(roundedDrawable);
// }
//
// @Override
// protected void onDraw(@NonNull Canvas canvas) {
// super.onDraw(canvas);
// if (mChecked) {
// Drawable border = ContextCompat.getDrawable(getContext(), R.drawable.selector_avatar);
// border.setBounds(0, 0, getWidth(), getHeight());
// border.draw(canvas);
// }
// }
//
// @Override
// @SuppressLint("NewApi")
// protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// super.onSizeChanged(w, h, oldw, oldh);
// if (ApiLevelHelper.isLowerThan(Build.VERSION_CODES.LOLLIPOP)) {
// return;
// }
// if (w > 0 && h > 0) {
// setOutlineProvider(new RoundOutlineProvider(Math.min(w, h)));
// }
// }
// }
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/adapter/AvatarAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.hufeiya.SignIn.R;
import com.hufeiya.SignIn.model.Avatar;
import com.hufeiya.SignIn.widget.AvatarView;
/*
* Copyright 2015 Google Inc.
*
* 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.hufeiya.SignIn.adapter;
/**
* Adapter to display {@link Avatar} icons.
*/
public class AvatarAdapter extends BaseAdapter {
private static final Avatar[] mAvatars = Avatar.values();
private final LayoutInflater mLayoutInflater;
public AvatarAdapter(Context context) {
mLayoutInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
convertView = mLayoutInflater.inflate(R.layout.item_avatar, parent, false);
} | setAvatar((AvatarView) convertView, mAvatars[position]); |
hufeiya/CoolSignIn | AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/TextSharedElementCallback.java | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/ViewUtils.java
// public class ViewUtils {
//
// /**
// * Allows changes to the text size in transitions and animations.
// * Using this with something else than {@link ChangeBounds}
// * can result in a severe performance penalty due to layout passes.
// */
// public static final Property<TextView, Float> PROPERTY_TEXT_SIZE =
// new FloatProperty<TextView>("textSize") {
// @Override
// public Float get(TextView view) {
// return view.getTextSize();
// }
//
// @Override
// public void setValue(TextView view, float textSize) {
// view.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
// }
// };
// /**
// * Allows making changes to the start padding of a view.
// * Using this with something else than {@link ChangeBounds}
// * can result in a severe performance penalty due to layout passes.
// */
// public static final Property<TextView, Integer> PROPERTY_TEXT_PADDING_START =
// new IntProperty<TextView>("paddingStart") {
// @Override
// public Integer get(TextView view) {
// return ViewCompat.getPaddingStart(view);
// }
//
// @Override
// public void setValue(TextView view, int paddingStart) {
// ViewCompat.setPaddingRelative(view, paddingStart, view.getPaddingTop(),
// ViewCompat.getPaddingEnd(view), view.getPaddingBottom());
// }
// };
//
// private ViewUtils() {
// //no instance
// }
//
// public static void setPaddingStart(TextView target, int paddingStart) {
// ViewCompat.setPaddingRelative(target, paddingStart, target.getPaddingTop(),
// ViewCompat.getPaddingEnd(target), target.getPaddingBottom());
// }
//
// public static abstract class IntProperty<T> extends Property<T, Integer> {
//
// public IntProperty(String name) {
// super(Integer.class, name);
// }
//
// /**
// * A type-specific override of the {@link #set(Object, Integer)} that is faster when
// * dealing
// * with fields of type <code>int</code>.
// */
// public abstract void setValue(T object, int value);
//
// @Override
// final public void set(T object, Integer value) {
// //noinspection UnnecessaryUnboxing
// setValue(object, value.intValue());
// }
// }
//
// public static abstract class FloatProperty<T> extends Property<T, Float> {
//
// public FloatProperty(String name) {
// super(Float.class, name);
// }
//
// /**
// * A type-specific override of the {@link #set(Object, Float)} that is faster when dealing
// * with fields of type <code>int</code>.
// */
// public abstract void setValue(T object, float value);
//
// @Override
// final public void set(T object, Float value) {
// //noinspection UnnecessaryUnboxing
// setValue(object, value.floatValue());
// }
// }
//
// }
| import android.annotation.TargetApi;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.app.SharedElementCallback;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;
import com.hufeiya.SignIn.helper.ViewUtils;
import java.util.List; | /*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.hufeiya.SignIn.widget;
/**
* This callback allows a shared TextView to resize text and start padding during transition.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class TextSharedElementCallback extends SharedElementCallback {
private static final String TAG = "TextResize";
private final int mInitialPaddingStart;
private final float mInitialTextSize;
private float mTargetViewTextSize;
private int mTargetViewPaddingStart;
public TextSharedElementCallback(float initialTextSize, int initialPaddingStart) {
mInitialTextSize = initialTextSize;
mInitialPaddingStart = initialPaddingStart;
}
@Override
public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements,
List<View> sharedElementSnapshots) {
TextView targetView = getTextView(sharedElements);
if (targetView == null) {
Log.w(TAG, "onSharedElementStart: No shared TextView, skipping.");
return;
}
mTargetViewTextSize = targetView.getTextSize();
mTargetViewPaddingStart = targetView.getPaddingStart();
// Setup the TextView's start values.
targetView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mInitialTextSize); | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/ViewUtils.java
// public class ViewUtils {
//
// /**
// * Allows changes to the text size in transitions and animations.
// * Using this with something else than {@link ChangeBounds}
// * can result in a severe performance penalty due to layout passes.
// */
// public static final Property<TextView, Float> PROPERTY_TEXT_SIZE =
// new FloatProperty<TextView>("textSize") {
// @Override
// public Float get(TextView view) {
// return view.getTextSize();
// }
//
// @Override
// public void setValue(TextView view, float textSize) {
// view.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
// }
// };
// /**
// * Allows making changes to the start padding of a view.
// * Using this with something else than {@link ChangeBounds}
// * can result in a severe performance penalty due to layout passes.
// */
// public static final Property<TextView, Integer> PROPERTY_TEXT_PADDING_START =
// new IntProperty<TextView>("paddingStart") {
// @Override
// public Integer get(TextView view) {
// return ViewCompat.getPaddingStart(view);
// }
//
// @Override
// public void setValue(TextView view, int paddingStart) {
// ViewCompat.setPaddingRelative(view, paddingStart, view.getPaddingTop(),
// ViewCompat.getPaddingEnd(view), view.getPaddingBottom());
// }
// };
//
// private ViewUtils() {
// //no instance
// }
//
// public static void setPaddingStart(TextView target, int paddingStart) {
// ViewCompat.setPaddingRelative(target, paddingStart, target.getPaddingTop(),
// ViewCompat.getPaddingEnd(target), target.getPaddingBottom());
// }
//
// public static abstract class IntProperty<T> extends Property<T, Integer> {
//
// public IntProperty(String name) {
// super(Integer.class, name);
// }
//
// /**
// * A type-specific override of the {@link #set(Object, Integer)} that is faster when
// * dealing
// * with fields of type <code>int</code>.
// */
// public abstract void setValue(T object, int value);
//
// @Override
// final public void set(T object, Integer value) {
// //noinspection UnnecessaryUnboxing
// setValue(object, value.intValue());
// }
// }
//
// public static abstract class FloatProperty<T> extends Property<T, Float> {
//
// public FloatProperty(String name) {
// super(Float.class, name);
// }
//
// /**
// * A type-specific override of the {@link #set(Object, Float)} that is faster when dealing
// * with fields of type <code>int</code>.
// */
// public abstract void setValue(T object, float value);
//
// @Override
// final public void set(T object, Float value) {
// //noinspection UnnecessaryUnboxing
// setValue(object, value.floatValue());
// }
// }
//
// }
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/TextSharedElementCallback.java
import android.annotation.TargetApi;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v4.app.SharedElementCallback;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;
import com.hufeiya.SignIn.helper.ViewUtils;
import java.util.List;
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.hufeiya.SignIn.widget;
/**
* This callback allows a shared TextView to resize text and start padding during transition.
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class TextSharedElementCallback extends SharedElementCallback {
private static final String TAG = "TextResize";
private final int mInitialPaddingStart;
private final float mInitialTextSize;
private float mTargetViewTextSize;
private int mTargetViewPaddingStart;
public TextSharedElementCallback(float initialTextSize, int initialPaddingStart) {
mInitialTextSize = initialTextSize;
mInitialPaddingStart = initialPaddingStart;
}
@Override
public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements,
List<View> sharedElementSnapshots) {
TextView targetView = getTextView(sharedElements);
if (targetView == null) {
Log.w(TAG, "onSharedElementStart: No shared TextView, skipping.");
return;
}
mTargetViewTextSize = targetView.getTextSize();
mTargetViewPaddingStart = targetView.getPaddingStart();
// Setup the TextView's start values.
targetView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mInitialTextSize); | ViewUtils.setPaddingStart(targetView, mInitialPaddingStart); |
hufeiya/CoolSignIn | Server/src/com/hufeiya/DAO/UserDAO.java | // Path: Server/src/com/hufeiya/entity/User.java
// public class User implements java.io.Serializable {
//
// // Fields
//
// private Integer uid;
// private String username;
// private String pass;
// private String userNo;
// private String phone;
// private Boolean userType;
// private Set studentSheets = new HashSet(0);
// private Set courses = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public User() {
// }
//
// /** full constructor */
// public User(String username, String pass, String userNo, String phone,
// Boolean userType, Set studentSheets, Set courses) {
// this.username = username;
// this.pass = pass;
// this.userNo = userNo;
// this.phone = phone;
// this.userType = userType;
// this.studentSheets = studentSheets;
// this.courses = courses;
// }
//
// /**Login constructor*/
// public User(String phone,String pass){
// this.phone = phone;
// this.pass = pass;
// }
// // Property accessors
//
// public Integer getUid() {
// return this.uid;
// }
//
// public void setUid(Integer uid) {
// this.uid = uid;
// }
//
// public String getUsername() {
// return this.username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPass() {
// return this.pass;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public String getUserNo() {
// return this.userNo;
// }
//
// public void setUserNo(String userNo) {
// this.userNo = userNo;
// }
//
// public String getPhone() {
// return this.phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public Boolean getUserType() {
// return this.userType;
// }
//
// public void setUserType(Boolean userType) {
// this.userType = userType;
// }
//
// public Set getStudentSheets() {
// return this.studentSheets;
// }
//
// public void setStudentSheets(Set studentSheets) {
// this.studentSheets = studentSheets;
// }
//
// public Set getCourses() {
// return this.courses;
// }
//
// public void setCourses(Set courses) {
// this.courses = courses;
// }
//
// }
| import java.util.List;
import java.util.Set;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.User; | package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for User
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see com.hufeiya.DAO.User
* @author MyEclipse Persistence Tools
*/
public class UserDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(UserDAO.class);
// property constants
public static final String USERNAME = "username";
public static final String PASS = "pass";
public static final String USER_NO = "userNo";
public static final String PHONE = "phone";
public static final String USER_TYPE = "userType";
| // Path: Server/src/com/hufeiya/entity/User.java
// public class User implements java.io.Serializable {
//
// // Fields
//
// private Integer uid;
// private String username;
// private String pass;
// private String userNo;
// private String phone;
// private Boolean userType;
// private Set studentSheets = new HashSet(0);
// private Set courses = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public User() {
// }
//
// /** full constructor */
// public User(String username, String pass, String userNo, String phone,
// Boolean userType, Set studentSheets, Set courses) {
// this.username = username;
// this.pass = pass;
// this.userNo = userNo;
// this.phone = phone;
// this.userType = userType;
// this.studentSheets = studentSheets;
// this.courses = courses;
// }
//
// /**Login constructor*/
// public User(String phone,String pass){
// this.phone = phone;
// this.pass = pass;
// }
// // Property accessors
//
// public Integer getUid() {
// return this.uid;
// }
//
// public void setUid(Integer uid) {
// this.uid = uid;
// }
//
// public String getUsername() {
// return this.username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPass() {
// return this.pass;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public String getUserNo() {
// return this.userNo;
// }
//
// public void setUserNo(String userNo) {
// this.userNo = userNo;
// }
//
// public String getPhone() {
// return this.phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public Boolean getUserType() {
// return this.userType;
// }
//
// public void setUserType(Boolean userType) {
// this.userType = userType;
// }
//
// public Set getStudentSheets() {
// return this.studentSheets;
// }
//
// public void setStudentSheets(Set studentSheets) {
// this.studentSheets = studentSheets;
// }
//
// public Set getCourses() {
// return this.courses;
// }
//
// public void setCourses(Set courses) {
// this.courses = courses;
// }
//
// }
// Path: Server/src/com/hufeiya/DAO/UserDAO.java
import java.util.List;
import java.util.Set;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.User;
package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for User
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see com.hufeiya.DAO.User
* @author MyEclipse Persistence Tools
*/
public class UserDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(UserDAO.class);
// property constants
public static final String USERNAME = "username";
public static final String PASS = "pass";
public static final String USER_NO = "userNo";
public static final String PHONE = "phone";
public static final String USER_TYPE = "userType";
| public void save(User transientInstance) { |
hufeiya/CoolSignIn | AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/AvatarView.java | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/ApiLevelHelper.java
// public class ApiLevelHelper {
//
// private ApiLevelHelper() {
// //no instance
// }
//
// /**
// * Checks if the current api level is at least the provided value.
// *
// * @param apiLevel One of the values within {@link Build.VERSION_CODES}.
// * @return <code>true</code> if the calling version is at least <code>apiLevel</code>.
// * Else <code>false</code> is returned.
// */
// public static boolean isAtLeast(int apiLevel) {
// return Build.VERSION.SDK_INT >= apiLevel;
// }
//
// /**
// * Checks if the current api level is at lower than the provided value.
// *
// * @param apiLevel One of the values within {@link Build.VERSION_CODES}.
// * @return <code>true</code> if the calling version is lower than <code>apiLevel</code>.
// * Else <code>false</code> is returned.
// */
// public static boolean isLowerThan(int apiLevel) {
// return Build.VERSION.SDK_INT < apiLevel;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/outlineprovider/RoundOutlineProvider.java
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public class RoundOutlineProvider extends ViewOutlineProvider {
//
// private final int mSize;
//
// public RoundOutlineProvider(int size) {
// if (0 > size) {
// throw new IllegalArgumentException("size needs to be > 0. Actually was " + size);
// }
// mSize = size;
// }
//
// @Override
// public final void getOutline(View view, Outline outline) {
// outline.setOval(0, 0, mSize, mSize);
// }
//
// }
| import android.widget.ImageView;
import com.hufeiya.SignIn.R;
import com.hufeiya.SignIn.helper.ApiLevelHelper;
import com.hufeiya.SignIn.widget.outlineprovider.RoundOutlineProvider;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.AttributeSet;
import android.widget.Checkable; | /*
* Copyright 2015 Google Inc.
*
* 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.hufeiya.SignIn.widget;
/**
* A simple view that wraps an avatar.
*/
public class AvatarView extends ImageView implements Checkable {
private boolean mChecked;
public AvatarView(Context context) {
this(context, null);
}
public AvatarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AvatarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void setChecked(boolean b) {
mChecked = b;
invalidate();
}
@Override
public void toggle() {
setChecked(!mChecked);
}
/**
* Set the image for this avatar. Will be used to create a round version of this avatar.
*
* @param resId The image's resource id.
*/
@SuppressLint("NewApi")
public void setAvatar(@DrawableRes int resId) { | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/ApiLevelHelper.java
// public class ApiLevelHelper {
//
// private ApiLevelHelper() {
// //no instance
// }
//
// /**
// * Checks if the current api level is at least the provided value.
// *
// * @param apiLevel One of the values within {@link Build.VERSION_CODES}.
// * @return <code>true</code> if the calling version is at least <code>apiLevel</code>.
// * Else <code>false</code> is returned.
// */
// public static boolean isAtLeast(int apiLevel) {
// return Build.VERSION.SDK_INT >= apiLevel;
// }
//
// /**
// * Checks if the current api level is at lower than the provided value.
// *
// * @param apiLevel One of the values within {@link Build.VERSION_CODES}.
// * @return <code>true</code> if the calling version is lower than <code>apiLevel</code>.
// * Else <code>false</code> is returned.
// */
// public static boolean isLowerThan(int apiLevel) {
// return Build.VERSION.SDK_INT < apiLevel;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/outlineprovider/RoundOutlineProvider.java
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public class RoundOutlineProvider extends ViewOutlineProvider {
//
// private final int mSize;
//
// public RoundOutlineProvider(int size) {
// if (0 > size) {
// throw new IllegalArgumentException("size needs to be > 0. Actually was " + size);
// }
// mSize = size;
// }
//
// @Override
// public final void getOutline(View view, Outline outline) {
// outline.setOval(0, 0, mSize, mSize);
// }
//
// }
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/AvatarView.java
import android.widget.ImageView;
import com.hufeiya.SignIn.R;
import com.hufeiya.SignIn.helper.ApiLevelHelper;
import com.hufeiya.SignIn.widget.outlineprovider.RoundOutlineProvider;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.AttributeSet;
import android.widget.Checkable;
/*
* Copyright 2015 Google Inc.
*
* 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.hufeiya.SignIn.widget;
/**
* A simple view that wraps an avatar.
*/
public class AvatarView extends ImageView implements Checkable {
private boolean mChecked;
public AvatarView(Context context) {
this(context, null);
}
public AvatarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AvatarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void setChecked(boolean b) {
mChecked = b;
invalidate();
}
@Override
public void toggle() {
setChecked(!mChecked);
}
/**
* Set the image for this avatar. Will be used to create a round version of this avatar.
*
* @param resId The image's resource id.
*/
@SuppressLint("NewApi")
public void setAvatar(@DrawableRes int resId) { | if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) { |
hufeiya/CoolSignIn | AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/AvatarView.java | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/ApiLevelHelper.java
// public class ApiLevelHelper {
//
// private ApiLevelHelper() {
// //no instance
// }
//
// /**
// * Checks if the current api level is at least the provided value.
// *
// * @param apiLevel One of the values within {@link Build.VERSION_CODES}.
// * @return <code>true</code> if the calling version is at least <code>apiLevel</code>.
// * Else <code>false</code> is returned.
// */
// public static boolean isAtLeast(int apiLevel) {
// return Build.VERSION.SDK_INT >= apiLevel;
// }
//
// /**
// * Checks if the current api level is at lower than the provided value.
// *
// * @param apiLevel One of the values within {@link Build.VERSION_CODES}.
// * @return <code>true</code> if the calling version is lower than <code>apiLevel</code>.
// * Else <code>false</code> is returned.
// */
// public static boolean isLowerThan(int apiLevel) {
// return Build.VERSION.SDK_INT < apiLevel;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/outlineprovider/RoundOutlineProvider.java
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public class RoundOutlineProvider extends ViewOutlineProvider {
//
// private final int mSize;
//
// public RoundOutlineProvider(int size) {
// if (0 > size) {
// throw new IllegalArgumentException("size needs to be > 0. Actually was " + size);
// }
// mSize = size;
// }
//
// @Override
// public final void getOutline(View view, Outline outline) {
// outline.setOval(0, 0, mSize, mSize);
// }
//
// }
| import android.widget.ImageView;
import com.hufeiya.SignIn.R;
import com.hufeiya.SignIn.helper.ApiLevelHelper;
import com.hufeiya.SignIn.widget.outlineprovider.RoundOutlineProvider;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.AttributeSet;
import android.widget.Checkable; |
private void setAvatarPreLollipop(@DrawableRes int resId) {
Drawable drawable = ResourcesCompat.getDrawable(getResources(), resId,
getContext().getTheme());
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
@SuppressWarnings("ConstantConditions")
RoundedBitmapDrawable roundedDrawable = RoundedBitmapDrawableFactory.create(getResources(),
bitmapDrawable.getBitmap());
roundedDrawable.setCircular(true);
setImageDrawable(roundedDrawable);
}
@Override
protected void onDraw(@NonNull Canvas canvas) {
super.onDraw(canvas);
if (mChecked) {
Drawable border = ContextCompat.getDrawable(getContext(), R.drawable.selector_avatar);
border.setBounds(0, 0, getWidth(), getHeight());
border.draw(canvas);
}
}
@Override
@SuppressLint("NewApi")
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (ApiLevelHelper.isLowerThan(Build.VERSION_CODES.LOLLIPOP)) {
return;
}
if (w > 0 && h > 0) { | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/ApiLevelHelper.java
// public class ApiLevelHelper {
//
// private ApiLevelHelper() {
// //no instance
// }
//
// /**
// * Checks if the current api level is at least the provided value.
// *
// * @param apiLevel One of the values within {@link Build.VERSION_CODES}.
// * @return <code>true</code> if the calling version is at least <code>apiLevel</code>.
// * Else <code>false</code> is returned.
// */
// public static boolean isAtLeast(int apiLevel) {
// return Build.VERSION.SDK_INT >= apiLevel;
// }
//
// /**
// * Checks if the current api level is at lower than the provided value.
// *
// * @param apiLevel One of the values within {@link Build.VERSION_CODES}.
// * @return <code>true</code> if the calling version is lower than <code>apiLevel</code>.
// * Else <code>false</code> is returned.
// */
// public static boolean isLowerThan(int apiLevel) {
// return Build.VERSION.SDK_INT < apiLevel;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/outlineprovider/RoundOutlineProvider.java
// @TargetApi(Build.VERSION_CODES.LOLLIPOP)
// public class RoundOutlineProvider extends ViewOutlineProvider {
//
// private final int mSize;
//
// public RoundOutlineProvider(int size) {
// if (0 > size) {
// throw new IllegalArgumentException("size needs to be > 0. Actually was " + size);
// }
// mSize = size;
// }
//
// @Override
// public final void getOutline(View view, Outline outline) {
// outline.setOval(0, 0, mSize, mSize);
// }
//
// }
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/AvatarView.java
import android.widget.ImageView;
import com.hufeiya.SignIn.R;
import com.hufeiya.SignIn.helper.ApiLevelHelper;
import com.hufeiya.SignIn.widget.outlineprovider.RoundOutlineProvider;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.AttributeSet;
import android.widget.Checkable;
private void setAvatarPreLollipop(@DrawableRes int resId) {
Drawable drawable = ResourcesCompat.getDrawable(getResources(), resId,
getContext().getTheme());
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
@SuppressWarnings("ConstantConditions")
RoundedBitmapDrawable roundedDrawable = RoundedBitmapDrawableFactory.create(getResources(),
bitmapDrawable.getBitmap());
roundedDrawable.setCircular(true);
setImageDrawable(roundedDrawable);
}
@Override
protected void onDraw(@NonNull Canvas canvas) {
super.onDraw(canvas);
if (mChecked) {
Drawable border = ContextCompat.getDrawable(getContext(), R.drawable.selector_avatar);
border.setBounds(0, 0, getWidth(), getHeight());
border.draw(canvas);
}
}
@Override
@SuppressLint("NewApi")
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (ApiLevelHelper.isLowerThan(Build.VERSION_CODES.LOLLIPOP)) {
return;
}
if (w > 0 && h > 0) { | setOutlineProvider(new RoundOutlineProvider(Math.min(w, h))); |
hufeiya/CoolSignIn | Server/src/com/hufeiya/controller/UptokenServlet.java | // Path: Server/src/com/hufeiya/utils/CookieUtils.java
// public class CookieUtils {
// private static final Boolean IS_STUDENT = true;
// public static final int INVALID_VALUE = -1;
// public static void addCookieToRespose(HttpServletResponse response, int id) {
// Cookie cookie = new Cookie("uid", AESUtils.encrypt(id));
// System.out.println(cookie.getValue());//debug the cookie
// response.addCookie(cookie);
// }
//
// public static int getUidFromCookies(Cookie[] cookies) {
// int decryptedCookieValue = INVALID_VALUE;
// if (cookies != null) {
// for (Cookie cookie : cookies) {
// if (cookie.getName().equals("uid")) {
// int tempDecrypted = AESUtils.decrypt(cookie.getValue());
// if (tempDecrypted != INVALID_VALUE) {
// decryptedCookieValue = tempDecrypted;
// break;
// }
// }
// }
// }
// return decryptedCookieValue;
// }
// }
| import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hufeiya.utils.CookieUtils;
import com.qiniu.util.Auth; | package com.hufeiya.controller;
public class UptokenServlet extends HttpServlet {
private static Auth auth = Auth.create("8VTgVpzoGcxeuMR0df4te3qH9JE8xDy0XqZCqTLR", "b11rZxCn7f4JPMW2kQUMPS7A5q2F4UVo13smFbfv");
// 覆盖上传
private String getUpToken(String signId){
return auth.uploadToken("coolsignin",signId);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=UTF-8");
res.setCharacterEncoding("UTF-8");
String signId = req.getParameter("signid");
System.out.println(signId);
PrintWriter out = res.getWriter(); | // Path: Server/src/com/hufeiya/utils/CookieUtils.java
// public class CookieUtils {
// private static final Boolean IS_STUDENT = true;
// public static final int INVALID_VALUE = -1;
// public static void addCookieToRespose(HttpServletResponse response, int id) {
// Cookie cookie = new Cookie("uid", AESUtils.encrypt(id));
// System.out.println(cookie.getValue());//debug the cookie
// response.addCookie(cookie);
// }
//
// public static int getUidFromCookies(Cookie[] cookies) {
// int decryptedCookieValue = INVALID_VALUE;
// if (cookies != null) {
// for (Cookie cookie : cookies) {
// if (cookie.getName().equals("uid")) {
// int tempDecrypted = AESUtils.decrypt(cookie.getValue());
// if (tempDecrypted != INVALID_VALUE) {
// decryptedCookieValue = tempDecrypted;
// break;
// }
// }
// }
// }
// return decryptedCookieValue;
// }
// }
// Path: Server/src/com/hufeiya/controller/UptokenServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hufeiya.utils.CookieUtils;
import com.qiniu.util.Auth;
package com.hufeiya.controller;
public class UptokenServlet extends HttpServlet {
private static Auth auth = Auth.create("8VTgVpzoGcxeuMR0df4te3qH9JE8xDy0XqZCqTLR", "b11rZxCn7f4JPMW2kQUMPS7A5q2F4UVo13smFbfv");
// 覆盖上传
private String getUpToken(String signId){
return auth.uploadToken("coolsignin",signId);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=UTF-8");
res.setCharacterEncoding("UTF-8");
String signId = req.getParameter("signid");
System.out.println(signId);
PrintWriter out = res.getWriter(); | int uidFromCookies = CookieUtils.getUidFromCookies(req.getCookies()); |
hufeiya/CoolSignIn | Server/src/com/hufeiya/DAO/SignInfoDAO.java | // Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
| import java.util.List;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.SignInfo; | package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for
* SignInfo entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see com.hufeiya.DAO.SignInfo
* @author MyEclipse Persistence Tools
*/
public class SignInfoDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory
.getLogger(SignInfoDAO.class);
// property constants
public static final String SIGN_DETAIL = "signDetail";
public static final String SIGN_TIMES = "signTimes";
public static final String LAST_SIGN_PHOTO = "lastSignPhoto";
| // Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
// Path: Server/src/com/hufeiya/DAO/SignInfoDAO.java
import java.util.List;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.SignInfo;
package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for
* SignInfo entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see com.hufeiya.DAO.SignInfo
* @author MyEclipse Persistence Tools
*/
public class SignInfoDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory
.getLogger(SignInfoDAO.class);
// property constants
public static final String SIGN_DETAIL = "signDetail";
public static final String SIGN_TIMES = "signTimes";
public static final String LAST_SIGN_PHOTO = "lastSignPhoto";
| public void save(SignInfo transientInstance) { |
hufeiya/CoolSignIn | AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/PreferencesHelper.java | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/Avatar.java
// public enum Avatar {
//
// ONE(R.drawable.avatar_1),
// TWO(R.drawable.avatar_2),
// THREE(R.drawable.avatar_3),
// FOUR(R.drawable.avatar_4),
// FIVE(R.drawable.avatar_5),
// SIX(R.drawable.avatar_6),
// SEVEN(R.drawable.avatar_7),
// EIGHT(R.drawable.avatar_8),
// NINE(R.drawable.avatar_9),
// TEN(R.drawable.avatar_10),
// ELEVEN(R.drawable.avatar_11),
// TWELVE(R.drawable.avatar_12),
// THIRTEEN(R.drawable.avatar_13),
// FOURTEEN(R.drawable.avatar_14),
// FIFTEEN(R.drawable.avatar_15),
// SIXTEEN(R.drawable.avatar_16);
//
// private static final String TAG = "Avatar";
//
// private final int mResId;
//
// Avatar(@DrawableRes final int resId) {
// mResId = resId;
// }
//
// @DrawableRes
// public int getDrawableId() {
// return mResId;
// }
//
// public String getNameForAccessibility() {
// return TAG + " " + ordinal() + 1;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/User.java
// public class User implements Parcelable {
//
// public static final Creator<User> CREATOR = new Creator<User>() {
// @Override
// public User createFromParcel(Parcel in) {
// return new User(in);
// }
//
// @Override
// public User[] newArray(int size) {
// return new User[size];
// }
// };
// private final String mPhone;
// private final String mPass;
// private final Avatar mAvatar;
//
// public User(String phone, String pass, Avatar avatar) {
// mPhone = phone;
// mPass = pass;
// mAvatar = avatar;
// }
//
// protected User(Parcel in) {
// mPhone = in.readString();
// mPass = in.readString();
// mAvatar = Avatar.values()[in.readInt()];
// }
//
// public String getPhone() {
// return mPhone;
// }
//
// public String getPass() {
// return mPass;
// }
//
// public Avatar getAvatar() {
// return mAvatar;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mPhone);
// dest.writeString(mPass);
// dest.writeInt(mAvatar.ordinal());
// }
//
// @SuppressWarnings("RedundantIfStatement")
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// User user = (User) o;
//
// if (mAvatar != user.mAvatar) {
// return false;
// }
// if (!mPhone.equals(user.mPhone)) {
// return false;
// }
// if (!mPass.equals(user.mPass)) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = mPhone.hashCode();
// result = 31 * result + mPass.hashCode();
// result = 31 * result + mAvatar.hashCode();
// return result;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import com.hufeiya.SignIn.model.Avatar;
import com.hufeiya.SignIn.model.User; | /*
* Copyright 2015 Google Inc.
*
* 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.hufeiya.SignIn.helper;
/**
* Easy storage and retrieval of preferences.
*/
public class PreferencesHelper {
private static final String USER_PREFERENCES = "playerPreferences";
private static final String PREFERENCE_PHONE = USER_PREFERENCES + ".phone";
private static final String PREFERENCE_PASS = USER_PREFERENCES + ".pass";
private static final String PREFERENCE_AVATAR = USER_PREFERENCES + ".avatar";
private PreferencesHelper() {
//no instancer
}
/**
* Writes a {@link User} to preferences.
*
* @param context The Context which to obtain the SharedPreferences from.
* @param user The {@link User} to write.
*/ | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/Avatar.java
// public enum Avatar {
//
// ONE(R.drawable.avatar_1),
// TWO(R.drawable.avatar_2),
// THREE(R.drawable.avatar_3),
// FOUR(R.drawable.avatar_4),
// FIVE(R.drawable.avatar_5),
// SIX(R.drawable.avatar_6),
// SEVEN(R.drawable.avatar_7),
// EIGHT(R.drawable.avatar_8),
// NINE(R.drawable.avatar_9),
// TEN(R.drawable.avatar_10),
// ELEVEN(R.drawable.avatar_11),
// TWELVE(R.drawable.avatar_12),
// THIRTEEN(R.drawable.avatar_13),
// FOURTEEN(R.drawable.avatar_14),
// FIFTEEN(R.drawable.avatar_15),
// SIXTEEN(R.drawable.avatar_16);
//
// private static final String TAG = "Avatar";
//
// private final int mResId;
//
// Avatar(@DrawableRes final int resId) {
// mResId = resId;
// }
//
// @DrawableRes
// public int getDrawableId() {
// return mResId;
// }
//
// public String getNameForAccessibility() {
// return TAG + " " + ordinal() + 1;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/User.java
// public class User implements Parcelable {
//
// public static final Creator<User> CREATOR = new Creator<User>() {
// @Override
// public User createFromParcel(Parcel in) {
// return new User(in);
// }
//
// @Override
// public User[] newArray(int size) {
// return new User[size];
// }
// };
// private final String mPhone;
// private final String mPass;
// private final Avatar mAvatar;
//
// public User(String phone, String pass, Avatar avatar) {
// mPhone = phone;
// mPass = pass;
// mAvatar = avatar;
// }
//
// protected User(Parcel in) {
// mPhone = in.readString();
// mPass = in.readString();
// mAvatar = Avatar.values()[in.readInt()];
// }
//
// public String getPhone() {
// return mPhone;
// }
//
// public String getPass() {
// return mPass;
// }
//
// public Avatar getAvatar() {
// return mAvatar;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mPhone);
// dest.writeString(mPass);
// dest.writeInt(mAvatar.ordinal());
// }
//
// @SuppressWarnings("RedundantIfStatement")
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// User user = (User) o;
//
// if (mAvatar != user.mAvatar) {
// return false;
// }
// if (!mPhone.equals(user.mPhone)) {
// return false;
// }
// if (!mPass.equals(user.mPass)) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = mPhone.hashCode();
// result = 31 * result + mPass.hashCode();
// result = 31 * result + mAvatar.hashCode();
// return result;
// }
// }
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/PreferencesHelper.java
import android.content.Context;
import android.content.SharedPreferences;
import com.hufeiya.SignIn.model.Avatar;
import com.hufeiya.SignIn.model.User;
/*
* Copyright 2015 Google Inc.
*
* 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.hufeiya.SignIn.helper;
/**
* Easy storage and retrieval of preferences.
*/
public class PreferencesHelper {
private static final String USER_PREFERENCES = "playerPreferences";
private static final String PREFERENCE_PHONE = USER_PREFERENCES + ".phone";
private static final String PREFERENCE_PASS = USER_PREFERENCES + ".pass";
private static final String PREFERENCE_AVATAR = USER_PREFERENCES + ".avatar";
private PreferencesHelper() {
//no instancer
}
/**
* Writes a {@link User} to preferences.
*
* @param context The Context which to obtain the SharedPreferences from.
* @param user The {@link User} to write.
*/ | public static void writeToPreferences(Context context, User user) { |
hufeiya/CoolSignIn | AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/PreferencesHelper.java | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/Avatar.java
// public enum Avatar {
//
// ONE(R.drawable.avatar_1),
// TWO(R.drawable.avatar_2),
// THREE(R.drawable.avatar_3),
// FOUR(R.drawable.avatar_4),
// FIVE(R.drawable.avatar_5),
// SIX(R.drawable.avatar_6),
// SEVEN(R.drawable.avatar_7),
// EIGHT(R.drawable.avatar_8),
// NINE(R.drawable.avatar_9),
// TEN(R.drawable.avatar_10),
// ELEVEN(R.drawable.avatar_11),
// TWELVE(R.drawable.avatar_12),
// THIRTEEN(R.drawable.avatar_13),
// FOURTEEN(R.drawable.avatar_14),
// FIFTEEN(R.drawable.avatar_15),
// SIXTEEN(R.drawable.avatar_16);
//
// private static final String TAG = "Avatar";
//
// private final int mResId;
//
// Avatar(@DrawableRes final int resId) {
// mResId = resId;
// }
//
// @DrawableRes
// public int getDrawableId() {
// return mResId;
// }
//
// public String getNameForAccessibility() {
// return TAG + " " + ordinal() + 1;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/User.java
// public class User implements Parcelable {
//
// public static final Creator<User> CREATOR = new Creator<User>() {
// @Override
// public User createFromParcel(Parcel in) {
// return new User(in);
// }
//
// @Override
// public User[] newArray(int size) {
// return new User[size];
// }
// };
// private final String mPhone;
// private final String mPass;
// private final Avatar mAvatar;
//
// public User(String phone, String pass, Avatar avatar) {
// mPhone = phone;
// mPass = pass;
// mAvatar = avatar;
// }
//
// protected User(Parcel in) {
// mPhone = in.readString();
// mPass = in.readString();
// mAvatar = Avatar.values()[in.readInt()];
// }
//
// public String getPhone() {
// return mPhone;
// }
//
// public String getPass() {
// return mPass;
// }
//
// public Avatar getAvatar() {
// return mAvatar;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mPhone);
// dest.writeString(mPass);
// dest.writeInt(mAvatar.ordinal());
// }
//
// @SuppressWarnings("RedundantIfStatement")
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// User user = (User) o;
//
// if (mAvatar != user.mAvatar) {
// return false;
// }
// if (!mPhone.equals(user.mPhone)) {
// return false;
// }
// if (!mPass.equals(user.mPass)) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = mPhone.hashCode();
// result = 31 * result + mPass.hashCode();
// result = 31 * result + mAvatar.hashCode();
// return result;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import com.hufeiya.SignIn.model.Avatar;
import com.hufeiya.SignIn.model.User; | /*
* Copyright 2015 Google Inc.
*
* 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.hufeiya.SignIn.helper;
/**
* Easy storage and retrieval of preferences.
*/
public class PreferencesHelper {
private static final String USER_PREFERENCES = "playerPreferences";
private static final String PREFERENCE_PHONE = USER_PREFERENCES + ".phone";
private static final String PREFERENCE_PASS = USER_PREFERENCES + ".pass";
private static final String PREFERENCE_AVATAR = USER_PREFERENCES + ".avatar";
private PreferencesHelper() {
//no instancer
}
/**
* Writes a {@link User} to preferences.
*
* @param context The Context which to obtain the SharedPreferences from.
* @param user The {@link User} to write.
*/
public static void writeToPreferences(Context context, User user) {
SharedPreferences.Editor editor = getEditor(context);
editor.putString(PREFERENCE_PHONE, user.getPhone());
editor.putString(PREFERENCE_PASS, user.getPass());
editor.putString(PREFERENCE_AVATAR, user.getAvatar().name());
editor.apply();
}
/**
* Retrieves a {@link User} from preferences.
*
* @param context The Context which to obtain the SharedPreferences from.
* @return A previously saved player or <code>null</code> if none was saved previously.
*/
public static User getPlayer(Context context) {
SharedPreferences preferences = getSharedPreferences(context);
final String firstName = preferences.getString(PREFERENCE_PHONE, null);
final String lastInitial = preferences.getString(PREFERENCE_PASS, null);
final String avatarPreference = preferences.getString(PREFERENCE_AVATAR, null); | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/Avatar.java
// public enum Avatar {
//
// ONE(R.drawable.avatar_1),
// TWO(R.drawable.avatar_2),
// THREE(R.drawable.avatar_3),
// FOUR(R.drawable.avatar_4),
// FIVE(R.drawable.avatar_5),
// SIX(R.drawable.avatar_6),
// SEVEN(R.drawable.avatar_7),
// EIGHT(R.drawable.avatar_8),
// NINE(R.drawable.avatar_9),
// TEN(R.drawable.avatar_10),
// ELEVEN(R.drawable.avatar_11),
// TWELVE(R.drawable.avatar_12),
// THIRTEEN(R.drawable.avatar_13),
// FOURTEEN(R.drawable.avatar_14),
// FIFTEEN(R.drawable.avatar_15),
// SIXTEEN(R.drawable.avatar_16);
//
// private static final String TAG = "Avatar";
//
// private final int mResId;
//
// Avatar(@DrawableRes final int resId) {
// mResId = resId;
// }
//
// @DrawableRes
// public int getDrawableId() {
// return mResId;
// }
//
// public String getNameForAccessibility() {
// return TAG + " " + ordinal() + 1;
// }
// }
//
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/model/User.java
// public class User implements Parcelable {
//
// public static final Creator<User> CREATOR = new Creator<User>() {
// @Override
// public User createFromParcel(Parcel in) {
// return new User(in);
// }
//
// @Override
// public User[] newArray(int size) {
// return new User[size];
// }
// };
// private final String mPhone;
// private final String mPass;
// private final Avatar mAvatar;
//
// public User(String phone, String pass, Avatar avatar) {
// mPhone = phone;
// mPass = pass;
// mAvatar = avatar;
// }
//
// protected User(Parcel in) {
// mPhone = in.readString();
// mPass = in.readString();
// mAvatar = Avatar.values()[in.readInt()];
// }
//
// public String getPhone() {
// return mPhone;
// }
//
// public String getPass() {
// return mPass;
// }
//
// public Avatar getAvatar() {
// return mAvatar;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(mPhone);
// dest.writeString(mPass);
// dest.writeInt(mAvatar.ordinal());
// }
//
// @SuppressWarnings("RedundantIfStatement")
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
//
// User user = (User) o;
//
// if (mAvatar != user.mAvatar) {
// return false;
// }
// if (!mPhone.equals(user.mPhone)) {
// return false;
// }
// if (!mPass.equals(user.mPass)) {
// return false;
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = mPhone.hashCode();
// result = 31 * result + mPass.hashCode();
// result = 31 * result + mAvatar.hashCode();
// return result;
// }
// }
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/PreferencesHelper.java
import android.content.Context;
import android.content.SharedPreferences;
import com.hufeiya.SignIn.model.Avatar;
import com.hufeiya.SignIn.model.User;
/*
* Copyright 2015 Google Inc.
*
* 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.hufeiya.SignIn.helper;
/**
* Easy storage and retrieval of preferences.
*/
public class PreferencesHelper {
private static final String USER_PREFERENCES = "playerPreferences";
private static final String PREFERENCE_PHONE = USER_PREFERENCES + ".phone";
private static final String PREFERENCE_PASS = USER_PREFERENCES + ".pass";
private static final String PREFERENCE_AVATAR = USER_PREFERENCES + ".avatar";
private PreferencesHelper() {
//no instancer
}
/**
* Writes a {@link User} to preferences.
*
* @param context The Context which to obtain the SharedPreferences from.
* @param user The {@link User} to write.
*/
public static void writeToPreferences(Context context, User user) {
SharedPreferences.Editor editor = getEditor(context);
editor.putString(PREFERENCE_PHONE, user.getPhone());
editor.putString(PREFERENCE_PASS, user.getPass());
editor.putString(PREFERENCE_AVATAR, user.getAvatar().name());
editor.apply();
}
/**
* Retrieves a {@link User} from preferences.
*
* @param context The Context which to obtain the SharedPreferences from.
* @return A previously saved player or <code>null</code> if none was saved previously.
*/
public static User getPlayer(Context context) {
SharedPreferences preferences = getSharedPreferences(context);
final String firstName = preferences.getString(PREFERENCE_PHONE, null);
final String lastInitial = preferences.getString(PREFERENCE_PASS, null);
final String avatarPreference = preferences.getString(PREFERENCE_AVATAR, null); | final Avatar avatar; |
hufeiya/CoolSignIn | Server/src/com/hufeiya/DAO/BaseHibernateDAO.java | // Path: Server/src/com/hufeiya/HibernateSessionFactory.java
// public class HibernateSessionFactory {
//
// /**
// * Location of hibernate.cfg.xml file.
// * Location should be on the classpath as Hibernate uses
// * #resourceAsStream style lookup for its configuration file.
// * The default classpath location of the hibernate config file is
// * in the default package. Use #setConfigFile() to update
// * the location of the configuration file for the current session.
// */
// private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
// private static org.hibernate.SessionFactory sessionFactory;
//
// private static Configuration configuration = new Configuration();
// private static ServiceRegistry serviceRegistry;
//
// static {
// try {
// configuration.configure();
// serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
// sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// } catch (Exception e) {
// System.err.println("%%%% Error Creating SessionFactory %%%%");
// e.printStackTrace();
// }
// }
// private HibernateSessionFactory() {
// }
//
// /**
// * Returns the ThreadLocal Session instance. Lazy initialize
// * the <code>SessionFactory</code> if needed.
// *
// * @return Session
// * @throws HibernateException
// */
// public static Session getSession() throws HibernateException {
// Session session = (Session) threadLocal.get();
//
// if (session == null || !session.isOpen()) {
// if (sessionFactory == null) {
// rebuildSessionFactory();
// }
// session = (sessionFactory != null) ? sessionFactory.openSession()
// : null;
// threadLocal.set(session);
// }
//
// return session;
// }
//
// /**
// * Rebuild hibernate session factory
// *
// */
// public static void rebuildSessionFactory() {
// try {
// configuration.configure();
// serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
// sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// } catch (Exception e) {
// System.err.println("%%%% Error Creating SessionFactory %%%%");
// e.printStackTrace();
// }
// }
//
// /**
// * Close the single hibernate session instance.
// *
// * @throws HibernateException
// */
// public static void closeSession() throws HibernateException {
// Session session = (Session) threadLocal.get();
// threadLocal.set(null);
//
// if (session != null) {
// session.close();
// }
// }
//
// /**
// * return session factory
// *
// */
// public static org.hibernate.SessionFactory getSessionFactory() {
// return sessionFactory;
// }
// /**
// * return hibernate configuration
// *
// */
// public static Configuration getConfiguration() {
// return configuration;
// }
//
// }
| import com.hufeiya.HibernateSessionFactory;
import org.hibernate.Session;
| package com.hufeiya.DAO;
/**
* Data access object (DAO) for domain model
* @author MyEclipse Persistence Tools
*/
public class BaseHibernateDAO implements IBaseHibernateDAO {
public Session getSession() {
| // Path: Server/src/com/hufeiya/HibernateSessionFactory.java
// public class HibernateSessionFactory {
//
// /**
// * Location of hibernate.cfg.xml file.
// * Location should be on the classpath as Hibernate uses
// * #resourceAsStream style lookup for its configuration file.
// * The default classpath location of the hibernate config file is
// * in the default package. Use #setConfigFile() to update
// * the location of the configuration file for the current session.
// */
// private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
// private static org.hibernate.SessionFactory sessionFactory;
//
// private static Configuration configuration = new Configuration();
// private static ServiceRegistry serviceRegistry;
//
// static {
// try {
// configuration.configure();
// serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
// sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// } catch (Exception e) {
// System.err.println("%%%% Error Creating SessionFactory %%%%");
// e.printStackTrace();
// }
// }
// private HibernateSessionFactory() {
// }
//
// /**
// * Returns the ThreadLocal Session instance. Lazy initialize
// * the <code>SessionFactory</code> if needed.
// *
// * @return Session
// * @throws HibernateException
// */
// public static Session getSession() throws HibernateException {
// Session session = (Session) threadLocal.get();
//
// if (session == null || !session.isOpen()) {
// if (sessionFactory == null) {
// rebuildSessionFactory();
// }
// session = (sessionFactory != null) ? sessionFactory.openSession()
// : null;
// threadLocal.set(session);
// }
//
// return session;
// }
//
// /**
// * Rebuild hibernate session factory
// *
// */
// public static void rebuildSessionFactory() {
// try {
// configuration.configure();
// serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
// sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// } catch (Exception e) {
// System.err.println("%%%% Error Creating SessionFactory %%%%");
// e.printStackTrace();
// }
// }
//
// /**
// * Close the single hibernate session instance.
// *
// * @throws HibernateException
// */
// public static void closeSession() throws HibernateException {
// Session session = (Session) threadLocal.get();
// threadLocal.set(null);
//
// if (session != null) {
// session.close();
// }
// }
//
// /**
// * return session factory
// *
// */
// public static org.hibernate.SessionFactory getSessionFactory() {
// return sessionFactory;
// }
// /**
// * return hibernate configuration
// *
// */
// public static Configuration getConfiguration() {
// return configuration;
// }
//
// }
// Path: Server/src/com/hufeiya/DAO/BaseHibernateDAO.java
import com.hufeiya.HibernateSessionFactory;
import org.hibernate.Session;
package com.hufeiya.DAO;
/**
* Data access object (DAO) for domain model
* @author MyEclipse Persistence Tools
*/
public class BaseHibernateDAO implements IBaseHibernateDAO {
public Session getSession() {
| return HibernateSessionFactory.getSession();
|
hufeiya/CoolSignIn | Server/src/com/hufeiya/jsonObject/JsonUser.java | // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/User.java
// public class User implements java.io.Serializable {
//
// // Fields
//
// private Integer uid;
// private String username;
// private String pass;
// private String userNo;
// private String phone;
// private Boolean userType;
// private Set studentSheets = new HashSet(0);
// private Set courses = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public User() {
// }
//
// /** full constructor */
// public User(String username, String pass, String userNo, String phone,
// Boolean userType, Set studentSheets, Set courses) {
// this.username = username;
// this.pass = pass;
// this.userNo = userNo;
// this.phone = phone;
// this.userType = userType;
// this.studentSheets = studentSheets;
// this.courses = courses;
// }
//
// /**Login constructor*/
// public User(String phone,String pass){
// this.phone = phone;
// this.pass = pass;
// }
// // Property accessors
//
// public Integer getUid() {
// return this.uid;
// }
//
// public void setUid(Integer uid) {
// this.uid = uid;
// }
//
// public String getUsername() {
// return this.username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPass() {
// return this.pass;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public String getUserNo() {
// return this.userNo;
// }
//
// public void setUserNo(String userNo) {
// this.userNo = userNo;
// }
//
// public String getPhone() {
// return this.phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public Boolean getUserType() {
// return this.userType;
// }
//
// public void setUserType(Boolean userType) {
// this.userType = userType;
// }
//
// public Set getStudentSheets() {
// return this.studentSheets;
// }
//
// public void setStudentSheets(Set studentSheets) {
// this.studentSheets = studentSheets;
// }
//
// public Set getCourses() {
// return this.courses;
// }
//
// public void setCourses(Set courses) {
// this.courses = courses;
// }
//
// }
| import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hufeiya.entity.Course;
import com.hufeiya.entity.User; | package com.hufeiya.jsonObject;
public class JsonUser {
// Fields
private Integer uid;
private String username;
private String pass;
private String userNo;
private String phone;
private Boolean userType;
private Map<Integer, JsonCourse>jsonCoursesMap = new HashMap<Integer, JsonCourse>();
// Constructors
/** default constructor */
public JsonUser() {
}
/** full constructor */
public JsonUser(String username, String pass, String userNo, String phone,
Boolean userType) {
this.username = username;
this.pass = pass;
this.userNo = userNo;
this.phone = phone;
this.userType = userType;
}
| // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/User.java
// public class User implements java.io.Serializable {
//
// // Fields
//
// private Integer uid;
// private String username;
// private String pass;
// private String userNo;
// private String phone;
// private Boolean userType;
// private Set studentSheets = new HashSet(0);
// private Set courses = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public User() {
// }
//
// /** full constructor */
// public User(String username, String pass, String userNo, String phone,
// Boolean userType, Set studentSheets, Set courses) {
// this.username = username;
// this.pass = pass;
// this.userNo = userNo;
// this.phone = phone;
// this.userType = userType;
// this.studentSheets = studentSheets;
// this.courses = courses;
// }
//
// /**Login constructor*/
// public User(String phone,String pass){
// this.phone = phone;
// this.pass = pass;
// }
// // Property accessors
//
// public Integer getUid() {
// return this.uid;
// }
//
// public void setUid(Integer uid) {
// this.uid = uid;
// }
//
// public String getUsername() {
// return this.username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPass() {
// return this.pass;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public String getUserNo() {
// return this.userNo;
// }
//
// public void setUserNo(String userNo) {
// this.userNo = userNo;
// }
//
// public String getPhone() {
// return this.phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public Boolean getUserType() {
// return this.userType;
// }
//
// public void setUserType(Boolean userType) {
// this.userType = userType;
// }
//
// public Set getStudentSheets() {
// return this.studentSheets;
// }
//
// public void setStudentSheets(Set studentSheets) {
// this.studentSheets = studentSheets;
// }
//
// public Set getCourses() {
// return this.courses;
// }
//
// public void setCourses(Set courses) {
// this.courses = courses;
// }
//
// }
// Path: Server/src/com/hufeiya/jsonObject/JsonUser.java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hufeiya.entity.Course;
import com.hufeiya.entity.User;
package com.hufeiya.jsonObject;
public class JsonUser {
// Fields
private Integer uid;
private String username;
private String pass;
private String userNo;
private String phone;
private Boolean userType;
private Map<Integer, JsonCourse>jsonCoursesMap = new HashMap<Integer, JsonCourse>();
// Constructors
/** default constructor */
public JsonUser() {
}
/** full constructor */
public JsonUser(String username, String pass, String userNo, String phone,
Boolean userType) {
this.username = username;
this.pass = pass;
this.userNo = userNo;
this.phone = phone;
this.userType = userType;
}
| public JsonUser(User user){ |
hufeiya/CoolSignIn | Server/src/com/hufeiya/jsonObject/JsonUser.java | // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/User.java
// public class User implements java.io.Serializable {
//
// // Fields
//
// private Integer uid;
// private String username;
// private String pass;
// private String userNo;
// private String phone;
// private Boolean userType;
// private Set studentSheets = new HashSet(0);
// private Set courses = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public User() {
// }
//
// /** full constructor */
// public User(String username, String pass, String userNo, String phone,
// Boolean userType, Set studentSheets, Set courses) {
// this.username = username;
// this.pass = pass;
// this.userNo = userNo;
// this.phone = phone;
// this.userType = userType;
// this.studentSheets = studentSheets;
// this.courses = courses;
// }
//
// /**Login constructor*/
// public User(String phone,String pass){
// this.phone = phone;
// this.pass = pass;
// }
// // Property accessors
//
// public Integer getUid() {
// return this.uid;
// }
//
// public void setUid(Integer uid) {
// this.uid = uid;
// }
//
// public String getUsername() {
// return this.username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPass() {
// return this.pass;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public String getUserNo() {
// return this.userNo;
// }
//
// public void setUserNo(String userNo) {
// this.userNo = userNo;
// }
//
// public String getPhone() {
// return this.phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public Boolean getUserType() {
// return this.userType;
// }
//
// public void setUserType(Boolean userType) {
// this.userType = userType;
// }
//
// public Set getStudentSheets() {
// return this.studentSheets;
// }
//
// public void setStudentSheets(Set studentSheets) {
// this.studentSheets = studentSheets;
// }
//
// public Set getCourses() {
// return this.courses;
// }
//
// public void setCourses(Set courses) {
// this.courses = courses;
// }
//
// }
| import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hufeiya.entity.Course;
import com.hufeiya.entity.User; | package com.hufeiya.jsonObject;
public class JsonUser {
// Fields
private Integer uid;
private String username;
private String pass;
private String userNo;
private String phone;
private Boolean userType;
private Map<Integer, JsonCourse>jsonCoursesMap = new HashMap<Integer, JsonCourse>();
// Constructors
/** default constructor */
public JsonUser() {
}
/** full constructor */
public JsonUser(String username, String pass, String userNo, String phone,
Boolean userType) {
this.username = username;
this.pass = pass;
this.userNo = userNo;
this.phone = phone;
this.userType = userType;
}
public JsonUser(User user){
this.uid = user.getUid();
this.username = user.getUsername();
this.pass = user.getPass();
this.userNo = user.getUserNo();
this.phone = user.getPhone();
this.userType = user.getUserType(); | // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/User.java
// public class User implements java.io.Serializable {
//
// // Fields
//
// private Integer uid;
// private String username;
// private String pass;
// private String userNo;
// private String phone;
// private Boolean userType;
// private Set studentSheets = new HashSet(0);
// private Set courses = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public User() {
// }
//
// /** full constructor */
// public User(String username, String pass, String userNo, String phone,
// Boolean userType, Set studentSheets, Set courses) {
// this.username = username;
// this.pass = pass;
// this.userNo = userNo;
// this.phone = phone;
// this.userType = userType;
// this.studentSheets = studentSheets;
// this.courses = courses;
// }
//
// /**Login constructor*/
// public User(String phone,String pass){
// this.phone = phone;
// this.pass = pass;
// }
// // Property accessors
//
// public Integer getUid() {
// return this.uid;
// }
//
// public void setUid(Integer uid) {
// this.uid = uid;
// }
//
// public String getUsername() {
// return this.username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPass() {
// return this.pass;
// }
//
// public void setPass(String pass) {
// this.pass = pass;
// }
//
// public String getUserNo() {
// return this.userNo;
// }
//
// public void setUserNo(String userNo) {
// this.userNo = userNo;
// }
//
// public String getPhone() {
// return this.phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public Boolean getUserType() {
// return this.userType;
// }
//
// public void setUserType(Boolean userType) {
// this.userType = userType;
// }
//
// public Set getStudentSheets() {
// return this.studentSheets;
// }
//
// public void setStudentSheets(Set studentSheets) {
// this.studentSheets = studentSheets;
// }
//
// public Set getCourses() {
// return this.courses;
// }
//
// public void setCourses(Set courses) {
// this.courses = courses;
// }
//
// }
// Path: Server/src/com/hufeiya/jsonObject/JsonUser.java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hufeiya.entity.Course;
import com.hufeiya.entity.User;
package com.hufeiya.jsonObject;
public class JsonUser {
// Fields
private Integer uid;
private String username;
private String pass;
private String userNo;
private String phone;
private Boolean userType;
private Map<Integer, JsonCourse>jsonCoursesMap = new HashMap<Integer, JsonCourse>();
// Constructors
/** default constructor */
public JsonUser() {
}
/** full constructor */
public JsonUser(String username, String pass, String userNo, String phone,
Boolean userType) {
this.username = username;
this.pass = pass;
this.userNo = userNo;
this.phone = phone;
this.userType = userType;
}
public JsonUser(User user){
this.uid = user.getUid();
this.username = user.getUsername();
this.pass = user.getPass();
this.userNo = user.getUserNo();
this.phone = user.getPhone();
this.userType = user.getUserType(); | Set<Course> tempCouses = user.getCourses(); |
hufeiya/CoolSignIn | Server/src/com/hufeiya/jsonObject/JsonStudentSheet.java | // Path: Server/src/com/hufeiya/entity/Student.java
// public class Student implements java.io.Serializable {
//
// // Fields
//
// private Integer sid;
// private StudentSheet studentSheet;
// private String clientId;
// private String studentName;
// private String studentNo;
// private String className;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Student() {
// }
//
// /** full constructor */
// public Student(StudentSheet studentSheet, String clientId,
// String studentName, String studentNo, String className,
// Set signInfos) {
// this.studentSheet = studentSheet;
// this.clientId = clientId;
// this.studentName = studentName;
// this.studentNo = studentNo;
// this.className = className;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getSid() {
// return this.sid;
// }
//
// public void setSid(Integer sid) {
// this.sid = sid;
// }
//
// public StudentSheet getStudentSheet() {
// return this.studentSheet;
// }
//
// public void setStudentSheet(StudentSheet studentSheet) {
// this.studentSheet = studentSheet;
// }
//
// public String getClientId() {
// return this.clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
//
// public String getStudentNo() {
// return this.studentNo;
// }
//
// public void setStudentNo(String studentNo) {
// this.studentNo = studentNo;
// }
//
// public String getClassName() {
// return this.className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/StudentSheet.java
// public class StudentSheet implements java.io.Serializable {
//
// // Fields
//
// private Integer sheetId;
// private User user;
// private String sheetName;
// private Set students = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public StudentSheet() {
// }
//
// /** minimal constructor */
// public StudentSheet(User user, String sheetName) {
// this.user = user;
// this.sheetName = sheetName;
// }
//
// /** full constructor */
// public StudentSheet(User user, String sheetName, Set students) {
// this.user = user;
// this.sheetName = sheetName;
// this.students = students;
// }
//
// // Property accessors
//
// public Integer getSheetId() {
// return this.sheetId;
// }
//
// public void setSheetId(Integer sheetId) {
// this.sheetId = sheetId;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getSheetName() {
// return this.sheetName;
// }
//
// public void setSheetName(String sheetName) {
// this.sheetName = sheetName;
// }
//
// public Set getStudents() {
// return this.students;
// }
//
// public void setStudents(Set students) {
// this.students = students;
// }
//
// }
| import java.util.HashSet;
import java.util.Set;
import com.hufeiya.entity.Student;
import com.hufeiya.entity.StudentSheet; | package com.hufeiya.jsonObject;
public class JsonStudentSheet {
// Fields
private Integer sheetId;
private String sheetName;
private Set<JsonStudent> jsonStudents = new HashSet<>();
// Constructors
/** default constructor */
public JsonStudentSheet() {
}
| // Path: Server/src/com/hufeiya/entity/Student.java
// public class Student implements java.io.Serializable {
//
// // Fields
//
// private Integer sid;
// private StudentSheet studentSheet;
// private String clientId;
// private String studentName;
// private String studentNo;
// private String className;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Student() {
// }
//
// /** full constructor */
// public Student(StudentSheet studentSheet, String clientId,
// String studentName, String studentNo, String className,
// Set signInfos) {
// this.studentSheet = studentSheet;
// this.clientId = clientId;
// this.studentName = studentName;
// this.studentNo = studentNo;
// this.className = className;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getSid() {
// return this.sid;
// }
//
// public void setSid(Integer sid) {
// this.sid = sid;
// }
//
// public StudentSheet getStudentSheet() {
// return this.studentSheet;
// }
//
// public void setStudentSheet(StudentSheet studentSheet) {
// this.studentSheet = studentSheet;
// }
//
// public String getClientId() {
// return this.clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
//
// public String getStudentNo() {
// return this.studentNo;
// }
//
// public void setStudentNo(String studentNo) {
// this.studentNo = studentNo;
// }
//
// public String getClassName() {
// return this.className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/StudentSheet.java
// public class StudentSheet implements java.io.Serializable {
//
// // Fields
//
// private Integer sheetId;
// private User user;
// private String sheetName;
// private Set students = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public StudentSheet() {
// }
//
// /** minimal constructor */
// public StudentSheet(User user, String sheetName) {
// this.user = user;
// this.sheetName = sheetName;
// }
//
// /** full constructor */
// public StudentSheet(User user, String sheetName, Set students) {
// this.user = user;
// this.sheetName = sheetName;
// this.students = students;
// }
//
// // Property accessors
//
// public Integer getSheetId() {
// return this.sheetId;
// }
//
// public void setSheetId(Integer sheetId) {
// this.sheetId = sheetId;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getSheetName() {
// return this.sheetName;
// }
//
// public void setSheetName(String sheetName) {
// this.sheetName = sheetName;
// }
//
// public Set getStudents() {
// return this.students;
// }
//
// public void setStudents(Set students) {
// this.students = students;
// }
//
// }
// Path: Server/src/com/hufeiya/jsonObject/JsonStudentSheet.java
import java.util.HashSet;
import java.util.Set;
import com.hufeiya.entity.Student;
import com.hufeiya.entity.StudentSheet;
package com.hufeiya.jsonObject;
public class JsonStudentSheet {
// Fields
private Integer sheetId;
private String sheetName;
private Set<JsonStudent> jsonStudents = new HashSet<>();
// Constructors
/** default constructor */
public JsonStudentSheet() {
}
| public JsonStudentSheet(StudentSheet studentSheet) { |
hufeiya/CoolSignIn | Server/src/com/hufeiya/jsonObject/JsonStudentSheet.java | // Path: Server/src/com/hufeiya/entity/Student.java
// public class Student implements java.io.Serializable {
//
// // Fields
//
// private Integer sid;
// private StudentSheet studentSheet;
// private String clientId;
// private String studentName;
// private String studentNo;
// private String className;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Student() {
// }
//
// /** full constructor */
// public Student(StudentSheet studentSheet, String clientId,
// String studentName, String studentNo, String className,
// Set signInfos) {
// this.studentSheet = studentSheet;
// this.clientId = clientId;
// this.studentName = studentName;
// this.studentNo = studentNo;
// this.className = className;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getSid() {
// return this.sid;
// }
//
// public void setSid(Integer sid) {
// this.sid = sid;
// }
//
// public StudentSheet getStudentSheet() {
// return this.studentSheet;
// }
//
// public void setStudentSheet(StudentSheet studentSheet) {
// this.studentSheet = studentSheet;
// }
//
// public String getClientId() {
// return this.clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
//
// public String getStudentNo() {
// return this.studentNo;
// }
//
// public void setStudentNo(String studentNo) {
// this.studentNo = studentNo;
// }
//
// public String getClassName() {
// return this.className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/StudentSheet.java
// public class StudentSheet implements java.io.Serializable {
//
// // Fields
//
// private Integer sheetId;
// private User user;
// private String sheetName;
// private Set students = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public StudentSheet() {
// }
//
// /** minimal constructor */
// public StudentSheet(User user, String sheetName) {
// this.user = user;
// this.sheetName = sheetName;
// }
//
// /** full constructor */
// public StudentSheet(User user, String sheetName, Set students) {
// this.user = user;
// this.sheetName = sheetName;
// this.students = students;
// }
//
// // Property accessors
//
// public Integer getSheetId() {
// return this.sheetId;
// }
//
// public void setSheetId(Integer sheetId) {
// this.sheetId = sheetId;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getSheetName() {
// return this.sheetName;
// }
//
// public void setSheetName(String sheetName) {
// this.sheetName = sheetName;
// }
//
// public Set getStudents() {
// return this.students;
// }
//
// public void setStudents(Set students) {
// this.students = students;
// }
//
// }
| import java.util.HashSet;
import java.util.Set;
import com.hufeiya.entity.Student;
import com.hufeiya.entity.StudentSheet; | package com.hufeiya.jsonObject;
public class JsonStudentSheet {
// Fields
private Integer sheetId;
private String sheetName;
private Set<JsonStudent> jsonStudents = new HashSet<>();
// Constructors
/** default constructor */
public JsonStudentSheet() {
}
public JsonStudentSheet(StudentSheet studentSheet) {
this.sheetId = studentSheet.getSheetId();
this.sheetName = studentSheet.getSheetName(); | // Path: Server/src/com/hufeiya/entity/Student.java
// public class Student implements java.io.Serializable {
//
// // Fields
//
// private Integer sid;
// private StudentSheet studentSheet;
// private String clientId;
// private String studentName;
// private String studentNo;
// private String className;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Student() {
// }
//
// /** full constructor */
// public Student(StudentSheet studentSheet, String clientId,
// String studentName, String studentNo, String className,
// Set signInfos) {
// this.studentSheet = studentSheet;
// this.clientId = clientId;
// this.studentName = studentName;
// this.studentNo = studentNo;
// this.className = className;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getSid() {
// return this.sid;
// }
//
// public void setSid(Integer sid) {
// this.sid = sid;
// }
//
// public StudentSheet getStudentSheet() {
// return this.studentSheet;
// }
//
// public void setStudentSheet(StudentSheet studentSheet) {
// this.studentSheet = studentSheet;
// }
//
// public String getClientId() {
// return this.clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
//
// public String getStudentNo() {
// return this.studentNo;
// }
//
// public void setStudentNo(String studentNo) {
// this.studentNo = studentNo;
// }
//
// public String getClassName() {
// return this.className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/StudentSheet.java
// public class StudentSheet implements java.io.Serializable {
//
// // Fields
//
// private Integer sheetId;
// private User user;
// private String sheetName;
// private Set students = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public StudentSheet() {
// }
//
// /** minimal constructor */
// public StudentSheet(User user, String sheetName) {
// this.user = user;
// this.sheetName = sheetName;
// }
//
// /** full constructor */
// public StudentSheet(User user, String sheetName, Set students) {
// this.user = user;
// this.sheetName = sheetName;
// this.students = students;
// }
//
// // Property accessors
//
// public Integer getSheetId() {
// return this.sheetId;
// }
//
// public void setSheetId(Integer sheetId) {
// this.sheetId = sheetId;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getSheetName() {
// return this.sheetName;
// }
//
// public void setSheetName(String sheetName) {
// this.sheetName = sheetName;
// }
//
// public Set getStudents() {
// return this.students;
// }
//
// public void setStudents(Set students) {
// this.students = students;
// }
//
// }
// Path: Server/src/com/hufeiya/jsonObject/JsonStudentSheet.java
import java.util.HashSet;
import java.util.Set;
import com.hufeiya.entity.Student;
import com.hufeiya.entity.StudentSheet;
package com.hufeiya.jsonObject;
public class JsonStudentSheet {
// Fields
private Integer sheetId;
private String sheetName;
private Set<JsonStudent> jsonStudents = new HashSet<>();
// Constructors
/** default constructor */
public JsonStudentSheet() {
}
public JsonStudentSheet(StudentSheet studentSheet) {
this.sheetId = studentSheet.getSheetId();
this.sheetName = studentSheet.getSheetName(); | Set<Student> suStudents = studentSheet.getStudents(); |
hufeiya/CoolSignIn | Server/src/com/hufeiya/DAO/StudentDAO.java | // Path: Server/src/com/hufeiya/entity/Student.java
// public class Student implements java.io.Serializable {
//
// // Fields
//
// private Integer sid;
// private StudentSheet studentSheet;
// private String clientId;
// private String studentName;
// private String studentNo;
// private String className;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Student() {
// }
//
// /** full constructor */
// public Student(StudentSheet studentSheet, String clientId,
// String studentName, String studentNo, String className,
// Set signInfos) {
// this.studentSheet = studentSheet;
// this.clientId = clientId;
// this.studentName = studentName;
// this.studentNo = studentNo;
// this.className = className;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getSid() {
// return this.sid;
// }
//
// public void setSid(Integer sid) {
// this.sid = sid;
// }
//
// public StudentSheet getStudentSheet() {
// return this.studentSheet;
// }
//
// public void setStudentSheet(StudentSheet studentSheet) {
// this.studentSheet = studentSheet;
// }
//
// public String getClientId() {
// return this.clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
//
// public String getStudentNo() {
// return this.studentNo;
// }
//
// public void setStudentNo(String studentNo) {
// this.studentNo = studentNo;
// }
//
// public String getClassName() {
// return this.className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
| import java.util.List;
import java.util.Set;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.Student; | package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for
* Student entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see com.hufeiya.DAO.Student
* @author MyEclipse Persistence Tools
*/
public class StudentDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(StudentDAO.class);
// property constants
public static final String CLIENT_ID = "clientId";
public static final String STUDENT_NAME = "studentName";
public static final String STUDENT_NO = "studentNo";
public static final String CLASS_NAME = "className";
| // Path: Server/src/com/hufeiya/entity/Student.java
// public class Student implements java.io.Serializable {
//
// // Fields
//
// private Integer sid;
// private StudentSheet studentSheet;
// private String clientId;
// private String studentName;
// private String studentNo;
// private String className;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Student() {
// }
//
// /** full constructor */
// public Student(StudentSheet studentSheet, String clientId,
// String studentName, String studentNo, String className,
// Set signInfos) {
// this.studentSheet = studentSheet;
// this.clientId = clientId;
// this.studentName = studentName;
// this.studentNo = studentNo;
// this.className = className;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getSid() {
// return this.sid;
// }
//
// public void setSid(Integer sid) {
// this.sid = sid;
// }
//
// public StudentSheet getStudentSheet() {
// return this.studentSheet;
// }
//
// public void setStudentSheet(StudentSheet studentSheet) {
// this.studentSheet = studentSheet;
// }
//
// public String getClientId() {
// return this.clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
//
// public String getStudentNo() {
// return this.studentNo;
// }
//
// public void setStudentNo(String studentNo) {
// this.studentNo = studentNo;
// }
//
// public String getClassName() {
// return this.className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
// Path: Server/src/com/hufeiya/DAO/StudentDAO.java
import java.util.List;
import java.util.Set;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.Student;
package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for
* Student entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see com.hufeiya.DAO.Student
* @author MyEclipse Persistence Tools
*/
public class StudentDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(StudentDAO.class);
// property constants
public static final String CLIENT_ID = "clientId";
public static final String STUDENT_NAME = "studentName";
public static final String STUDENT_NO = "studentNo";
public static final String CLASS_NAME = "className";
| public void save(Student transientInstance) { |
hufeiya/CoolSignIn | Server/src/com/hufeiya/DAO/StudentSheetDAO.java | // Path: Server/src/com/hufeiya/entity/StudentSheet.java
// public class StudentSheet implements java.io.Serializable {
//
// // Fields
//
// private Integer sheetId;
// private User user;
// private String sheetName;
// private Set students = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public StudentSheet() {
// }
//
// /** minimal constructor */
// public StudentSheet(User user, String sheetName) {
// this.user = user;
// this.sheetName = sheetName;
// }
//
// /** full constructor */
// public StudentSheet(User user, String sheetName, Set students) {
// this.user = user;
// this.sheetName = sheetName;
// this.students = students;
// }
//
// // Property accessors
//
// public Integer getSheetId() {
// return this.sheetId;
// }
//
// public void setSheetId(Integer sheetId) {
// this.sheetId = sheetId;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getSheetName() {
// return this.sheetName;
// }
//
// public void setSheetName(String sheetName) {
// this.sheetName = sheetName;
// }
//
// public Set getStudents() {
// return this.students;
// }
//
// public void setStudents(Set students) {
// this.students = students;
// }
//
// }
| import java.util.List;
import java.util.Set;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.StudentSheet; | package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for
* StudentSheet entities. Transaction control of the save(), update() and
* delete() operations can directly support Spring container-managed
* transactions or they can be augmented to handle user-managed Spring
* transactions. Each of these methods provides additional information for how
* to configure it for the desired type of transaction control.
*
* @see com.hufeiya.DAO.StudentSheet
* @author MyEclipse Persistence Tools
*/
public class StudentSheetDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory
.getLogger(StudentSheetDAO.class);
// property constants
public static final String SHEET_NAME = "sheetName";
| // Path: Server/src/com/hufeiya/entity/StudentSheet.java
// public class StudentSheet implements java.io.Serializable {
//
// // Fields
//
// private Integer sheetId;
// private User user;
// private String sheetName;
// private Set students = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public StudentSheet() {
// }
//
// /** minimal constructor */
// public StudentSheet(User user, String sheetName) {
// this.user = user;
// this.sheetName = sheetName;
// }
//
// /** full constructor */
// public StudentSheet(User user, String sheetName, Set students) {
// this.user = user;
// this.sheetName = sheetName;
// this.students = students;
// }
//
// // Property accessors
//
// public Integer getSheetId() {
// return this.sheetId;
// }
//
// public void setSheetId(Integer sheetId) {
// this.sheetId = sheetId;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getSheetName() {
// return this.sheetName;
// }
//
// public void setSheetName(String sheetName) {
// this.sheetName = sheetName;
// }
//
// public Set getStudents() {
// return this.students;
// }
//
// public void setStudents(Set students) {
// this.students = students;
// }
//
// }
// Path: Server/src/com/hufeiya/DAO/StudentSheetDAO.java
import java.util.List;
import java.util.Set;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hufeiya.entity.StudentSheet;
package com.hufeiya.DAO;
/**
* A data access object (DAO) providing persistence and search support for
* StudentSheet entities. Transaction control of the save(), update() and
* delete() operations can directly support Spring container-managed
* transactions or they can be augmented to handle user-managed Spring
* transactions. Each of these methods provides additional information for how
* to configure it for the desired type of transaction control.
*
* @see com.hufeiya.DAO.StudentSheet
* @author MyEclipse Persistence Tools
*/
public class StudentSheetDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory
.getLogger(StudentSheetDAO.class);
// property constants
public static final String SHEET_NAME = "sheetName";
| public void save(StudentSheet transientInstance) { |
hufeiya/CoolSignIn | Server/src/com/hufeiya/jsonObject/JsonCourse.java | // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
| import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hufeiya.entity.Course;
import com.hufeiya.entity.SignInfo; | package com.hufeiya.jsonObject;
public class JsonCourse {
// Fields
private Integer cid;
private Integer uid;
private String teacherName;
private String courseName;
private String startDates;
private Integer numberOfWeeks;
private Map<Integer, JsonSignInfo> signInfos = new HashMap<>();
// Constructors
/** default constructor */
public JsonCourse() {
}
/** full constructor */
public JsonCourse(String courseName, String startDates,
Integer numberOfWeeks, Map signInfos) {
this.courseName = courseName;
this.startDates = startDates;
this.numberOfWeeks = numberOfWeeks;
this.signInfos = signInfos;
}
| // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
// Path: Server/src/com/hufeiya/jsonObject/JsonCourse.java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hufeiya.entity.Course;
import com.hufeiya.entity.SignInfo;
package com.hufeiya.jsonObject;
public class JsonCourse {
// Fields
private Integer cid;
private Integer uid;
private String teacherName;
private String courseName;
private String startDates;
private Integer numberOfWeeks;
private Map<Integer, JsonSignInfo> signInfos = new HashMap<>();
// Constructors
/** default constructor */
public JsonCourse() {
}
/** full constructor */
public JsonCourse(String courseName, String startDates,
Integer numberOfWeeks, Map signInfos) {
this.courseName = courseName;
this.startDates = startDates;
this.numberOfWeeks = numberOfWeeks;
this.signInfos = signInfos;
}
| public JsonCourse(Course course){ |
hufeiya/CoolSignIn | Server/src/com/hufeiya/jsonObject/JsonCourse.java | // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
| import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hufeiya.entity.Course;
import com.hufeiya.entity.SignInfo; | package com.hufeiya.jsonObject;
public class JsonCourse {
// Fields
private Integer cid;
private Integer uid;
private String teacherName;
private String courseName;
private String startDates;
private Integer numberOfWeeks;
private Map<Integer, JsonSignInfo> signInfos = new HashMap<>();
// Constructors
/** default constructor */
public JsonCourse() {
}
/** full constructor */
public JsonCourse(String courseName, String startDates,
Integer numberOfWeeks, Map signInfos) {
this.courseName = courseName;
this.startDates = startDates;
this.numberOfWeeks = numberOfWeeks;
this.signInfos = signInfos;
}
public JsonCourse(Course course){
this.cid = course.getCid();
this.uid = course.getUser().getUid();
this.teacherName = course.getUser().getUsername();
this.courseName = course.getCourseName();
this.startDates = course.getStartDates();
this.numberOfWeeks = course.getNumberOfWeeks(); | // Path: Server/src/com/hufeiya/entity/Course.java
// public class Course implements java.io.Serializable {
//
// // Fields
//
// private Integer cid;
// private User user;
// private String courseName;
// private String startDates;
// private Integer numberOfWeeks;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Course() {
// }
//
// /** full constructor */
// public Course(User user, String courseName, String startDates,
// Integer numberOfWeeks, Set signInfos) {
// this.user = user;
// this.courseName = courseName;
// this.startDates = startDates;
// this.numberOfWeeks = numberOfWeeks;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getCid() {
// return this.cid;
// }
//
// public void setCid(Integer cid) {
// this.cid = cid;
// }
//
// public User getUser() {
// return this.user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public String getCourseName() {
// return this.courseName;
// }
//
// public void setCourseName(String courseName) {
// this.courseName = courseName;
// }
//
// public String getStartDates() {
// return this.startDates;
// }
//
// public void setStartDates(String startDates) {
// this.startDates = startDates;
// }
//
// public Integer getNumberOfWeeks() {
// return this.numberOfWeeks;
// }
//
// public void setNumberOfWeeks(Integer numberOfWeeks) {
// this.numberOfWeeks = numberOfWeeks;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
// Path: Server/src/com/hufeiya/jsonObject/JsonCourse.java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.hufeiya.entity.Course;
import com.hufeiya.entity.SignInfo;
package com.hufeiya.jsonObject;
public class JsonCourse {
// Fields
private Integer cid;
private Integer uid;
private String teacherName;
private String courseName;
private String startDates;
private Integer numberOfWeeks;
private Map<Integer, JsonSignInfo> signInfos = new HashMap<>();
// Constructors
/** default constructor */
public JsonCourse() {
}
/** full constructor */
public JsonCourse(String courseName, String startDates,
Integer numberOfWeeks, Map signInfos) {
this.courseName = courseName;
this.startDates = startDates;
this.numberOfWeeks = numberOfWeeks;
this.signInfos = signInfos;
}
public JsonCourse(Course course){
this.cid = course.getCid();
this.uid = course.getUser().getUid();
this.teacherName = course.getUser().getUsername();
this.courseName = course.getCourseName();
this.startDates = course.getStartDates();
this.numberOfWeeks = course.getNumberOfWeeks(); | Set<SignInfo> temp = course.getSignInfos(); |
hufeiya/CoolSignIn | AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/TextResizeTransition.java | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/ViewUtils.java
// public class ViewUtils {
//
// /**
// * Allows changes to the text size in transitions and animations.
// * Using this with something else than {@link ChangeBounds}
// * can result in a severe performance penalty due to layout passes.
// */
// public static final Property<TextView, Float> PROPERTY_TEXT_SIZE =
// new FloatProperty<TextView>("textSize") {
// @Override
// public Float get(TextView view) {
// return view.getTextSize();
// }
//
// @Override
// public void setValue(TextView view, float textSize) {
// view.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
// }
// };
// /**
// * Allows making changes to the start padding of a view.
// * Using this with something else than {@link ChangeBounds}
// * can result in a severe performance penalty due to layout passes.
// */
// public static final Property<TextView, Integer> PROPERTY_TEXT_PADDING_START =
// new IntProperty<TextView>("paddingStart") {
// @Override
// public Integer get(TextView view) {
// return ViewCompat.getPaddingStart(view);
// }
//
// @Override
// public void setValue(TextView view, int paddingStart) {
// ViewCompat.setPaddingRelative(view, paddingStart, view.getPaddingTop(),
// ViewCompat.getPaddingEnd(view), view.getPaddingBottom());
// }
// };
//
// private ViewUtils() {
// //no instance
// }
//
// public static void setPaddingStart(TextView target, int paddingStart) {
// ViewCompat.setPaddingRelative(target, paddingStart, target.getPaddingTop(),
// ViewCompat.getPaddingEnd(target), target.getPaddingBottom());
// }
//
// public static abstract class IntProperty<T> extends Property<T, Integer> {
//
// public IntProperty(String name) {
// super(Integer.class, name);
// }
//
// /**
// * A type-specific override of the {@link #set(Object, Integer)} that is faster when
// * dealing
// * with fields of type <code>int</code>.
// */
// public abstract void setValue(T object, int value);
//
// @Override
// final public void set(T object, Integer value) {
// //noinspection UnnecessaryUnboxing
// setValue(object, value.intValue());
// }
// }
//
// public static abstract class FloatProperty<T> extends Property<T, Float> {
//
// public FloatProperty(String name) {
// super(Float.class, name);
// }
//
// /**
// * A type-specific override of the {@link #set(Object, Float)} that is faster when dealing
// * with fields of type <code>int</code>.
// */
// public abstract void setValue(T object, float value);
//
// @Override
// final public void set(T object, Float value) {
// //noinspection UnnecessaryUnboxing
// setValue(object, value.floatValue());
// }
// }
//
// }
| import com.hufeiya.SignIn.helper.ViewUtils;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.transition.Transition;
import android.transition.TransitionValues;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.TextView; | }
TextView view = (TextView) transitionValues.view;
transitionValues.values.put(PROPERTY_NAME_TEXT_RESIZE, view.getTextSize());
transitionValues.values.put(PROPERTY_NAME_PADDING_RESIZE,
ViewCompat.getPaddingStart(view));
}
@Override
public String[] getTransitionProperties() {
return TRANSITION_PROPERTIES;
}
@Override
public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues,
TransitionValues endValues) {
if (startValues == null || endValues == null) {
return null;
}
float initialTextSize = (float) startValues.values.get(PROPERTY_NAME_TEXT_RESIZE);
float targetTextSize = (float) endValues.values.get(PROPERTY_NAME_TEXT_RESIZE);
TextView targetView = (TextView) endValues.view;
targetView.setTextSize(TypedValue.COMPLEX_UNIT_PX, initialTextSize);
int initialPaddingStart = (int) startValues.values.get(PROPERTY_NAME_PADDING_RESIZE);
int targetPaddingStart = (int) endValues.values.get(PROPERTY_NAME_PADDING_RESIZE);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofFloat(targetView, | // Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/helper/ViewUtils.java
// public class ViewUtils {
//
// /**
// * Allows changes to the text size in transitions and animations.
// * Using this with something else than {@link ChangeBounds}
// * can result in a severe performance penalty due to layout passes.
// */
// public static final Property<TextView, Float> PROPERTY_TEXT_SIZE =
// new FloatProperty<TextView>("textSize") {
// @Override
// public Float get(TextView view) {
// return view.getTextSize();
// }
//
// @Override
// public void setValue(TextView view, float textSize) {
// view.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
// }
// };
// /**
// * Allows making changes to the start padding of a view.
// * Using this with something else than {@link ChangeBounds}
// * can result in a severe performance penalty due to layout passes.
// */
// public static final Property<TextView, Integer> PROPERTY_TEXT_PADDING_START =
// new IntProperty<TextView>("paddingStart") {
// @Override
// public Integer get(TextView view) {
// return ViewCompat.getPaddingStart(view);
// }
//
// @Override
// public void setValue(TextView view, int paddingStart) {
// ViewCompat.setPaddingRelative(view, paddingStart, view.getPaddingTop(),
// ViewCompat.getPaddingEnd(view), view.getPaddingBottom());
// }
// };
//
// private ViewUtils() {
// //no instance
// }
//
// public static void setPaddingStart(TextView target, int paddingStart) {
// ViewCompat.setPaddingRelative(target, paddingStart, target.getPaddingTop(),
// ViewCompat.getPaddingEnd(target), target.getPaddingBottom());
// }
//
// public static abstract class IntProperty<T> extends Property<T, Integer> {
//
// public IntProperty(String name) {
// super(Integer.class, name);
// }
//
// /**
// * A type-specific override of the {@link #set(Object, Integer)} that is faster when
// * dealing
// * with fields of type <code>int</code>.
// */
// public abstract void setValue(T object, int value);
//
// @Override
// final public void set(T object, Integer value) {
// //noinspection UnnecessaryUnboxing
// setValue(object, value.intValue());
// }
// }
//
// public static abstract class FloatProperty<T> extends Property<T, Float> {
//
// public FloatProperty(String name) {
// super(Float.class, name);
// }
//
// /**
// * A type-specific override of the {@link #set(Object, Float)} that is faster when dealing
// * with fields of type <code>int</code>.
// */
// public abstract void setValue(T object, float value);
//
// @Override
// final public void set(T object, Float value) {
// //noinspection UnnecessaryUnboxing
// setValue(object, value.floatValue());
// }
// }
//
// }
// Path: AndroidClient/app/src/main/java/com/hufeiya/SignIn/widget/TextResizeTransition.java
import com.hufeiya.SignIn.helper.ViewUtils;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.transition.Transition;
import android.transition.TransitionValues;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ViewGroup;
import android.widget.TextView;
}
TextView view = (TextView) transitionValues.view;
transitionValues.values.put(PROPERTY_NAME_TEXT_RESIZE, view.getTextSize());
transitionValues.values.put(PROPERTY_NAME_PADDING_RESIZE,
ViewCompat.getPaddingStart(view));
}
@Override
public String[] getTransitionProperties() {
return TRANSITION_PROPERTIES;
}
@Override
public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues,
TransitionValues endValues) {
if (startValues == null || endValues == null) {
return null;
}
float initialTextSize = (float) startValues.values.get(PROPERTY_NAME_TEXT_RESIZE);
float targetTextSize = (float) endValues.values.get(PROPERTY_NAME_TEXT_RESIZE);
TextView targetView = (TextView) endValues.view;
targetView.setTextSize(TypedValue.COMPLEX_UNIT_PX, initialTextSize);
int initialPaddingStart = (int) startValues.values.get(PROPERTY_NAME_PADDING_RESIZE);
int targetPaddingStart = (int) endValues.values.get(PROPERTY_NAME_PADDING_RESIZE);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(
ObjectAnimator.ofFloat(targetView, | ViewUtils.PROPERTY_TEXT_SIZE, |
hufeiya/CoolSignIn | Server/src/com/hufeiya/jsonObject/JsonStudent.java | // Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/Student.java
// public class Student implements java.io.Serializable {
//
// // Fields
//
// private Integer sid;
// private StudentSheet studentSheet;
// private String clientId;
// private String studentName;
// private String studentNo;
// private String className;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Student() {
// }
//
// /** full constructor */
// public Student(StudentSheet studentSheet, String clientId,
// String studentName, String studentNo, String className,
// Set signInfos) {
// this.studentSheet = studentSheet;
// this.clientId = clientId;
// this.studentName = studentName;
// this.studentNo = studentNo;
// this.className = className;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getSid() {
// return this.sid;
// }
//
// public void setSid(Integer sid) {
// this.sid = sid;
// }
//
// public StudentSheet getStudentSheet() {
// return this.studentSheet;
// }
//
// public void setStudentSheet(StudentSheet studentSheet) {
// this.studentSheet = studentSheet;
// }
//
// public String getClientId() {
// return this.clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
//
// public String getStudentNo() {
// return this.studentNo;
// }
//
// public void setStudentNo(String studentNo) {
// this.studentNo = studentNo;
// }
//
// public String getClassName() {
// return this.className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
| import java.util.HashSet;
import java.util.Set;
import com.hufeiya.entity.SignInfo;
import com.hufeiya.entity.Student; | package com.hufeiya.jsonObject;
public class JsonStudent {
// Fields
private Integer sid;
private String clientId;
private String studentName;
private String studentNo;
private String className;
private Set<JsonSignInfo> jsonSignInfos = new HashSet<>();
// Constructors
/** default constructor */
public JsonStudent() {
}
| // Path: Server/src/com/hufeiya/entity/SignInfo.java
// public class SignInfo implements java.io.Serializable {
//
// // Fields
//
// private Integer signId;
// private Student student;
// private Course course;
// private String signDetail;
// private Integer signTimes;
// private String lastSignPhoto;
//
// // Constructors
//
// /** default constructor */
// public SignInfo() {
// }
//
// /** minimal constructor */
// public SignInfo(Student student, Course course) {
// this.student = student;
// this.course = course;
// }
//
// /** full constructor */
// public SignInfo(Student student, Course course, String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.student = student;
// this.course = course;
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
// /** constructor for update*/
// public SignInfo( String signDetail,
// Integer signTimes, String lastSignPhoto) {
// this.signDetail = signDetail;
// this.signTimes = signTimes;
// this.lastSignPhoto = lastSignPhoto;
// }
//
// // Property accessors
//
// public Integer getSignId() {
// return this.signId;
// }
//
// public void setSignId(Integer signId) {
// this.signId = signId;
// }
//
// public Student getStudent() {
// return this.student;
// }
//
// public void setStudent(Student student) {
// this.student = student;
// }
//
// public Course getCourse() {
// return this.course;
// }
//
// public void setCourse(Course course) {
// this.course = course;
// }
//
// public String getSignDetail() {
// return this.signDetail;
// }
//
// public void setSignDetail(String signDetail) {
// this.signDetail = signDetail;
// }
//
// public Integer getSignTimes() {
// return this.signTimes;
// }
//
// public void setSignTimes(Integer signTimes) {
// this.signTimes = signTimes;
// }
//
// public String getLastSignPhoto() {
// return this.lastSignPhoto;
// }
//
// public void setLastSignPhoto(String lastSignPhoto) {
// this.lastSignPhoto = lastSignPhoto;
// }
//
// }
//
// Path: Server/src/com/hufeiya/entity/Student.java
// public class Student implements java.io.Serializable {
//
// // Fields
//
// private Integer sid;
// private StudentSheet studentSheet;
// private String clientId;
// private String studentName;
// private String studentNo;
// private String className;
// private Set signInfos = new HashSet(0);
//
// // Constructors
//
// /** default constructor */
// public Student() {
// }
//
// /** full constructor */
// public Student(StudentSheet studentSheet, String clientId,
// String studentName, String studentNo, String className,
// Set signInfos) {
// this.studentSheet = studentSheet;
// this.clientId = clientId;
// this.studentName = studentName;
// this.studentNo = studentNo;
// this.className = className;
// this.signInfos = signInfos;
// }
//
// // Property accessors
//
// public Integer getSid() {
// return this.sid;
// }
//
// public void setSid(Integer sid) {
// this.sid = sid;
// }
//
// public StudentSheet getStudentSheet() {
// return this.studentSheet;
// }
//
// public void setStudentSheet(StudentSheet studentSheet) {
// this.studentSheet = studentSheet;
// }
//
// public String getClientId() {
// return this.clientId;
// }
//
// public void setClientId(String clientId) {
// this.clientId = clientId;
// }
//
// public String getStudentName() {
// return this.studentName;
// }
//
// public void setStudentName(String studentName) {
// this.studentName = studentName;
// }
//
// public String getStudentNo() {
// return this.studentNo;
// }
//
// public void setStudentNo(String studentNo) {
// this.studentNo = studentNo;
// }
//
// public String getClassName() {
// return this.className;
// }
//
// public void setClassName(String className) {
// this.className = className;
// }
//
// public Set getSignInfos() {
// return this.signInfos;
// }
//
// public void setSignInfos(Set signInfos) {
// this.signInfos = signInfos;
// }
//
// }
// Path: Server/src/com/hufeiya/jsonObject/JsonStudent.java
import java.util.HashSet;
import java.util.Set;
import com.hufeiya.entity.SignInfo;
import com.hufeiya.entity.Student;
package com.hufeiya.jsonObject;
public class JsonStudent {
// Fields
private Integer sid;
private String clientId;
private String studentName;
private String studentNo;
private String className;
private Set<JsonSignInfo> jsonSignInfos = new HashSet<>();
// Constructors
/** default constructor */
public JsonStudent() {
}
| public JsonStudent(Student student) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.