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
meruvian/yama
social/src/main/java/org/meruvian/yama/social/mervid/api/UserTemplate.java
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // }
import org.meruvian.yama.core.user.User; import org.springframework.web.client.RestTemplate;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.mervid.api; /** * @author Dian Aditya * */ public class UserTemplate implements UserOperations { private RestTemplate restTemplate; public UserTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @Override
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // Path: social/src/main/java/org/meruvian/yama/social/mervid/api/UserTemplate.java import org.meruvian.yama.core.user.User; import org.springframework.web.client.RestTemplate; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.mervid.api; /** * @author Dian Aditya * */ public class UserTemplate implements UserOperations { private RestTemplate restTemplate; public UserTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @Override
public User getUser() {
meruvian/yama
social/src/main/java/org/meruvian/yama/social/core/SocialService.java
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // }
import org.meruvian.yama.core.user.User; import org.springframework.social.connect.Connection; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.oauth2.OAuth2Parameters; import org.springframework.util.MultiValueMap;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.core; /** * @author Dian Aditya * */ public interface SocialService<T> { Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters);;
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // Path: social/src/main/java/org/meruvian/yama/social/core/SocialService.java import org.meruvian.yama.core.user.User; import org.springframework.social.connect.Connection; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.oauth2.OAuth2Parameters; import org.springframework.util.MultiValueMap; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.core; /** * @author Dian Aditya * */ public interface SocialService<T> { Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters);;
User createUser(Connection<?> connection);
meruvian/yama
social/src/main/java/org/meruvian/yama/social/google/GooglePlusService.java
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: social/src/main/java/org/meruvian/yama/social/core/AbstractSocialService.java // public abstract class AbstractSocialService<T> implements SocialService<T> { // protected OAuth2ConnectionFactory<T> connectionFactory; // // protected String redirectUri; // protected String scope; // protected String state; // // public AbstractSocialService(OAuth2ConnectionFactory<T> cf) { // this.connectionFactory = cf; // } // // public void setRedirectUri(String redirectUri) { // this.redirectUri = redirectUri; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public void setState(String state) { // this.state = state; // } // // @Override // public Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters) { // AccessGrant grant = connectionFactory.getOAuthOperations() // .exchangeForAccess(authorizationCode, getParameters().getRedirectUri(), additionalParameters); // // return connectionFactory.createConnection(grant); // } // // @Override // public String getAuthorizeUrl() { // String authUrl = connectionFactory.getOAuthOperations() // .buildAuthenticateUrl(GrantType.AUTHORIZATION_CODE, getParameters()); // // return authUrl; // } // // @Override // public boolean isAuthorized(Connection<?> connection) { // Object api = connection.getApi(); // if (api instanceof ApiBinding) { // ApiBinding apiBinding = (ApiBinding) api; // return apiBinding.isAuthorized(); // } // // return false; // } // // @Override // public OAuth2Parameters getParameters() { // OAuth2Parameters parameters = new OAuth2Parameters(); // parameters.setRedirectUri(redirectUri); // parameters.setScope(StringUtils.defaultString(scope)); // parameters.setState(StringUtils.defaultString(state)); // // return parameters; // } // // @Override // public OAuth2ConnectionFactory<T> getConnectionFactory() { // return connectionFactory; // } // }
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.commons.FileInfo; import org.meruvian.yama.core.user.User; import org.meruvian.yama.social.core.AbstractSocialService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.social.connect.Connection; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.google.api.Google; import org.springframework.social.google.api.plus.Person; import org.springframework.web.client.RestTemplate;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.google; /** * @author Dian Aditya * */ public class GooglePlusService extends AbstractSocialService<Google> { private static final Logger LOG = LoggerFactory.getLogger(GooglePlusService.class); private RestTemplate restTemplate; public GooglePlusService(OAuth2ConnectionFactory<Google> google) { super(google); restTemplate = new RestTemplate(); } @Override
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: social/src/main/java/org/meruvian/yama/social/core/AbstractSocialService.java // public abstract class AbstractSocialService<T> implements SocialService<T> { // protected OAuth2ConnectionFactory<T> connectionFactory; // // protected String redirectUri; // protected String scope; // protected String state; // // public AbstractSocialService(OAuth2ConnectionFactory<T> cf) { // this.connectionFactory = cf; // } // // public void setRedirectUri(String redirectUri) { // this.redirectUri = redirectUri; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public void setState(String state) { // this.state = state; // } // // @Override // public Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters) { // AccessGrant grant = connectionFactory.getOAuthOperations() // .exchangeForAccess(authorizationCode, getParameters().getRedirectUri(), additionalParameters); // // return connectionFactory.createConnection(grant); // } // // @Override // public String getAuthorizeUrl() { // String authUrl = connectionFactory.getOAuthOperations() // .buildAuthenticateUrl(GrantType.AUTHORIZATION_CODE, getParameters()); // // return authUrl; // } // // @Override // public boolean isAuthorized(Connection<?> connection) { // Object api = connection.getApi(); // if (api instanceof ApiBinding) { // ApiBinding apiBinding = (ApiBinding) api; // return apiBinding.isAuthorized(); // } // // return false; // } // // @Override // public OAuth2Parameters getParameters() { // OAuth2Parameters parameters = new OAuth2Parameters(); // parameters.setRedirectUri(redirectUri); // parameters.setScope(StringUtils.defaultString(scope)); // parameters.setState(StringUtils.defaultString(state)); // // return parameters; // } // // @Override // public OAuth2ConnectionFactory<T> getConnectionFactory() { // return connectionFactory; // } // } // Path: social/src/main/java/org/meruvian/yama/social/google/GooglePlusService.java import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.commons.FileInfo; import org.meruvian.yama.core.user.User; import org.meruvian.yama.social.core.AbstractSocialService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.social.connect.Connection; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.google.api.Google; import org.springframework.social.google.api.plus.Person; import org.springframework.web.client.RestTemplate; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.google; /** * @author Dian Aditya * */ public class GooglePlusService extends AbstractSocialService<Google> { private static final Logger LOG = LoggerFactory.getLogger(GooglePlusService.class); private RestTemplate restTemplate; public GooglePlusService(OAuth2ConnectionFactory<Google> google) { super(google); restTemplate = new RestTemplate(); } @Override
public User createUser(Connection<?> connection) {
meruvian/yama
core/src/main/java/org/meruvian/yama/social/connection/SocialConnection.java
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // }
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.meruvian.yama.core.DefaultPersistence; import org.meruvian.yama.core.user.User;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.connection; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_social_connection", uniqueConstraints = { @UniqueConstraint(columnNames = { "user_id", "provider", "rank" }), @UniqueConstraint(columnNames = { "user_id", "provider", "provider_user_id" }) })
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // Path: core/src/main/java/org/meruvian/yama/social/connection/SocialConnection.java import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.meruvian.yama.core.DefaultPersistence; import org.meruvian.yama.core.user.User; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.connection; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_social_connection", uniqueConstraints = { @UniqueConstraint(columnNames = { "user_id", "provider", "rank" }), @UniqueConstraint(columnNames = { "user_id", "provider", "provider_user_id" }) })
public class SocialConnection extends DefaultPersistence {
meruvian/yama
core/src/main/java/org/meruvian/yama/social/connection/SocialConnection.java
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // }
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.meruvian.yama.core.DefaultPersistence; import org.meruvian.yama.core.user.User;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.connection; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_social_connection", uniqueConstraints = { @UniqueConstraint(columnNames = { "user_id", "provider", "rank" }), @UniqueConstraint(columnNames = { "user_id", "provider", "provider_user_id" }) }) public class SocialConnection extends DefaultPersistence {
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // Path: core/src/main/java/org/meruvian/yama/social/connection/SocialConnection.java import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.meruvian.yama.core.DefaultPersistence; import org.meruvian.yama.core.user.User; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.connection; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_social_connection", uniqueConstraints = { @UniqueConstraint(columnNames = { "user_id", "provider", "rank" }), @UniqueConstraint(columnNames = { "user_id", "provider", "provider_user_id" }) }) public class SocialConnection extends DefaultPersistence {
private User user;
meruvian/yama
social/src/main/java/org/meruvian/yama/social/github/GithubService.java
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: social/src/main/java/org/meruvian/yama/social/core/AbstractSocialService.java // public abstract class AbstractSocialService<T> implements SocialService<T> { // protected OAuth2ConnectionFactory<T> connectionFactory; // // protected String redirectUri; // protected String scope; // protected String state; // // public AbstractSocialService(OAuth2ConnectionFactory<T> cf) { // this.connectionFactory = cf; // } // // public void setRedirectUri(String redirectUri) { // this.redirectUri = redirectUri; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public void setState(String state) { // this.state = state; // } // // @Override // public Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters) { // AccessGrant grant = connectionFactory.getOAuthOperations() // .exchangeForAccess(authorizationCode, getParameters().getRedirectUri(), additionalParameters); // // return connectionFactory.createConnection(grant); // } // // @Override // public String getAuthorizeUrl() { // String authUrl = connectionFactory.getOAuthOperations() // .buildAuthenticateUrl(GrantType.AUTHORIZATION_CODE, getParameters()); // // return authUrl; // } // // @Override // public boolean isAuthorized(Connection<?> connection) { // Object api = connection.getApi(); // if (api instanceof ApiBinding) { // ApiBinding apiBinding = (ApiBinding) api; // return apiBinding.isAuthorized(); // } // // return false; // } // // @Override // public OAuth2Parameters getParameters() { // OAuth2Parameters parameters = new OAuth2Parameters(); // parameters.setRedirectUri(redirectUri); // parameters.setScope(StringUtils.defaultString(scope)); // parameters.setState(StringUtils.defaultString(state)); // // return parameters; // } // // @Override // public OAuth2ConnectionFactory<T> getConnectionFactory() { // return connectionFactory; // } // }
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.commons.FileInfo; import org.meruvian.yama.core.user.User; import org.meruvian.yama.social.core.AbstractSocialService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.social.connect.Connection; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.github.api.GitHub; import org.springframework.social.github.api.GitHubUserProfile;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.github; /** * @author Dian Aditya * */ public class GithubService extends AbstractSocialService<GitHub> { private final Logger log = LoggerFactory.getLogger(getClass()); public GithubService(OAuth2ConnectionFactory<GitHub> github) { super(github); } @Override
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: social/src/main/java/org/meruvian/yama/social/core/AbstractSocialService.java // public abstract class AbstractSocialService<T> implements SocialService<T> { // protected OAuth2ConnectionFactory<T> connectionFactory; // // protected String redirectUri; // protected String scope; // protected String state; // // public AbstractSocialService(OAuth2ConnectionFactory<T> cf) { // this.connectionFactory = cf; // } // // public void setRedirectUri(String redirectUri) { // this.redirectUri = redirectUri; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public void setState(String state) { // this.state = state; // } // // @Override // public Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters) { // AccessGrant grant = connectionFactory.getOAuthOperations() // .exchangeForAccess(authorizationCode, getParameters().getRedirectUri(), additionalParameters); // // return connectionFactory.createConnection(grant); // } // // @Override // public String getAuthorizeUrl() { // String authUrl = connectionFactory.getOAuthOperations() // .buildAuthenticateUrl(GrantType.AUTHORIZATION_CODE, getParameters()); // // return authUrl; // } // // @Override // public boolean isAuthorized(Connection<?> connection) { // Object api = connection.getApi(); // if (api instanceof ApiBinding) { // ApiBinding apiBinding = (ApiBinding) api; // return apiBinding.isAuthorized(); // } // // return false; // } // // @Override // public OAuth2Parameters getParameters() { // OAuth2Parameters parameters = new OAuth2Parameters(); // parameters.setRedirectUri(redirectUri); // parameters.setScope(StringUtils.defaultString(scope)); // parameters.setState(StringUtils.defaultString(state)); // // return parameters; // } // // @Override // public OAuth2ConnectionFactory<T> getConnectionFactory() { // return connectionFactory; // } // } // Path: social/src/main/java/org/meruvian/yama/social/github/GithubService.java import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.commons.FileInfo; import org.meruvian.yama.core.user.User; import org.meruvian.yama.social.core.AbstractSocialService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.social.connect.Connection; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.github.api.GitHub; import org.springframework.social.github.api.GitHubUserProfile; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.github; /** * @author Dian Aditya * */ public class GithubService extends AbstractSocialService<GitHub> { private final Logger log = LoggerFactory.getLogger(getClass()); public GithubService(OAuth2ConnectionFactory<GitHub> github) { super(github); } @Override
public User createUser(Connection<?> connection) {
meruvian/yama
webapi/src/main/java/org/meruvian/yama/webapi/service/RestSocialSignInService.java
// Path: social/src/main/java/org/meruvian/yama/social/core/SocialService.java // public interface SocialService<T> { // Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters);; // // User createUser(Connection<?> connection); // // String getAuthorizeUrl(); // // boolean isAuthorized(Connection<?> connection); // // OAuth2Parameters getParameters(); // // OAuth2ConnectionFactory<T> getConnectionFactory(); // } // // Path: core/src/main/java/org/meruvian/yama/web/CredentialsService.java // public interface CredentialsService { // void registerAuthentication(String userId); // // void registerAuthentication(String userId, HttpServletRequest request); // }
import org.springframework.stereotype.Service; import java.net.URI; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.meruvian.yama.social.core.SocialService; import org.meruvian.yama.social.core.SocialServiceLocator; import org.meruvian.yama.web.CredentialsService; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.social.connect.Connection; import org.springframework.social.connect.UsersConnectionRepository;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.service; /** * @author Dian Aditya * */ @Service public class RestSocialSignInService implements SocialSignInService { public static final String OAUTH_AUTH_URL = "/oauth/authorize"; @Inject private SocialServiceLocator socialServiceLocator; @Inject private UsersConnectionRepository connectionRepository; @Inject
// Path: social/src/main/java/org/meruvian/yama/social/core/SocialService.java // public interface SocialService<T> { // Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters);; // // User createUser(Connection<?> connection); // // String getAuthorizeUrl(); // // boolean isAuthorized(Connection<?> connection); // // OAuth2Parameters getParameters(); // // OAuth2ConnectionFactory<T> getConnectionFactory(); // } // // Path: core/src/main/java/org/meruvian/yama/web/CredentialsService.java // public interface CredentialsService { // void registerAuthentication(String userId); // // void registerAuthentication(String userId, HttpServletRequest request); // } // Path: webapi/src/main/java/org/meruvian/yama/webapi/service/RestSocialSignInService.java import org.springframework.stereotype.Service; import java.net.URI; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.meruvian.yama.social.core.SocialService; import org.meruvian.yama.social.core.SocialServiceLocator; import org.meruvian.yama.web.CredentialsService; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.social.connect.Connection; import org.springframework.social.connect.UsersConnectionRepository; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.service; /** * @author Dian Aditya * */ @Service public class RestSocialSignInService implements SocialSignInService { public static final String OAUTH_AUTH_URL = "/oauth/authorize"; @Inject private SocialServiceLocator socialServiceLocator; @Inject private UsersConnectionRepository connectionRepository; @Inject
private CredentialsService credentialsService;
meruvian/yama
webapi/src/main/java/org/meruvian/yama/webapi/service/RestSocialSignInService.java
// Path: social/src/main/java/org/meruvian/yama/social/core/SocialService.java // public interface SocialService<T> { // Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters);; // // User createUser(Connection<?> connection); // // String getAuthorizeUrl(); // // boolean isAuthorized(Connection<?> connection); // // OAuth2Parameters getParameters(); // // OAuth2ConnectionFactory<T> getConnectionFactory(); // } // // Path: core/src/main/java/org/meruvian/yama/web/CredentialsService.java // public interface CredentialsService { // void registerAuthentication(String userId); // // void registerAuthentication(String userId, HttpServletRequest request); // }
import org.springframework.stereotype.Service; import java.net.URI; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.meruvian.yama.social.core.SocialService; import org.meruvian.yama.social.core.SocialServiceLocator; import org.meruvian.yama.web.CredentialsService; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.social.connect.Connection; import org.springframework.social.connect.UsersConnectionRepository;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.service; /** * @author Dian Aditya * */ @Service public class RestSocialSignInService implements SocialSignInService { public static final String OAUTH_AUTH_URL = "/oauth/authorize"; @Inject private SocialServiceLocator socialServiceLocator; @Inject private UsersConnectionRepository connectionRepository; @Inject private CredentialsService credentialsService; @Context private HttpServletRequest request; @Override public Response socialSignIn(String provider) { String redirectUri = socialServiceLocator.getSocialService(provider).getAuthorizeUrl(); return Response.seeOther(URI.create(redirectUri)).build(); } @Override public Response socialSignInCallback(String provider, String code) {
// Path: social/src/main/java/org/meruvian/yama/social/core/SocialService.java // public interface SocialService<T> { // Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters);; // // User createUser(Connection<?> connection); // // String getAuthorizeUrl(); // // boolean isAuthorized(Connection<?> connection); // // OAuth2Parameters getParameters(); // // OAuth2ConnectionFactory<T> getConnectionFactory(); // } // // Path: core/src/main/java/org/meruvian/yama/web/CredentialsService.java // public interface CredentialsService { // void registerAuthentication(String userId); // // void registerAuthentication(String userId, HttpServletRequest request); // } // Path: webapi/src/main/java/org/meruvian/yama/webapi/service/RestSocialSignInService.java import org.springframework.stereotype.Service; import java.net.URI; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.meruvian.yama.social.core.SocialService; import org.meruvian.yama.social.core.SocialServiceLocator; import org.meruvian.yama.web.CredentialsService; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.social.connect.Connection; import org.springframework.social.connect.UsersConnectionRepository; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.service; /** * @author Dian Aditya * */ @Service public class RestSocialSignInService implements SocialSignInService { public static final String OAUTH_AUTH_URL = "/oauth/authorize"; @Inject private SocialServiceLocator socialServiceLocator; @Inject private UsersConnectionRepository connectionRepository; @Inject private CredentialsService credentialsService; @Context private HttpServletRequest request; @Override public Response socialSignIn(String provider) { String redirectUri = socialServiceLocator.getSocialService(provider).getAuthorizeUrl(); return Response.seeOther(URI.create(redirectUri)).build(); } @Override public Response socialSignInCallback(String provider, String code) {
SocialService<?> socialService = socialServiceLocator.getSocialService(provider);
meruvian/yama
social/src/main/java/org/meruvian/yama/social/facebook/FacebookService.java
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: social/src/main/java/org/meruvian/yama/social/core/AbstractSocialService.java // public abstract class AbstractSocialService<T> implements SocialService<T> { // protected OAuth2ConnectionFactory<T> connectionFactory; // // protected String redirectUri; // protected String scope; // protected String state; // // public AbstractSocialService(OAuth2ConnectionFactory<T> cf) { // this.connectionFactory = cf; // } // // public void setRedirectUri(String redirectUri) { // this.redirectUri = redirectUri; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public void setState(String state) { // this.state = state; // } // // @Override // public Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters) { // AccessGrant grant = connectionFactory.getOAuthOperations() // .exchangeForAccess(authorizationCode, getParameters().getRedirectUri(), additionalParameters); // // return connectionFactory.createConnection(grant); // } // // @Override // public String getAuthorizeUrl() { // String authUrl = connectionFactory.getOAuthOperations() // .buildAuthenticateUrl(GrantType.AUTHORIZATION_CODE, getParameters()); // // return authUrl; // } // // @Override // public boolean isAuthorized(Connection<?> connection) { // Object api = connection.getApi(); // if (api instanceof ApiBinding) { // ApiBinding apiBinding = (ApiBinding) api; // return apiBinding.isAuthorized(); // } // // return false; // } // // @Override // public OAuth2Parameters getParameters() { // OAuth2Parameters parameters = new OAuth2Parameters(); // parameters.setRedirectUri(redirectUri); // parameters.setScope(StringUtils.defaultString(scope)); // parameters.setState(StringUtils.defaultString(state)); // // return parameters; // } // // @Override // public OAuth2ConnectionFactory<T> getConnectionFactory() { // return connectionFactory; // } // }
import java.io.ByteArrayInputStream; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.commons.FileInfo; import org.meruvian.yama.core.user.User; import org.meruvian.yama.social.core.AbstractSocialService; import org.springframework.social.connect.Connection; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.facebook.api.Facebook; import org.springframework.social.facebook.api.ImageType;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.facebook; /** * @author Dian Aditya * */ public class FacebookService extends AbstractSocialService<Facebook> { public FacebookService(OAuth2ConnectionFactory<Facebook> facebook) { super(facebook); } @Override
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: social/src/main/java/org/meruvian/yama/social/core/AbstractSocialService.java // public abstract class AbstractSocialService<T> implements SocialService<T> { // protected OAuth2ConnectionFactory<T> connectionFactory; // // protected String redirectUri; // protected String scope; // protected String state; // // public AbstractSocialService(OAuth2ConnectionFactory<T> cf) { // this.connectionFactory = cf; // } // // public void setRedirectUri(String redirectUri) { // this.redirectUri = redirectUri; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public void setState(String state) { // this.state = state; // } // // @Override // public Connection<T> createConnection(String authorizationCode, MultiValueMap<String, String> additionalParameters) { // AccessGrant grant = connectionFactory.getOAuthOperations() // .exchangeForAccess(authorizationCode, getParameters().getRedirectUri(), additionalParameters); // // return connectionFactory.createConnection(grant); // } // // @Override // public String getAuthorizeUrl() { // String authUrl = connectionFactory.getOAuthOperations() // .buildAuthenticateUrl(GrantType.AUTHORIZATION_CODE, getParameters()); // // return authUrl; // } // // @Override // public boolean isAuthorized(Connection<?> connection) { // Object api = connection.getApi(); // if (api instanceof ApiBinding) { // ApiBinding apiBinding = (ApiBinding) api; // return apiBinding.isAuthorized(); // } // // return false; // } // // @Override // public OAuth2Parameters getParameters() { // OAuth2Parameters parameters = new OAuth2Parameters(); // parameters.setRedirectUri(redirectUri); // parameters.setScope(StringUtils.defaultString(scope)); // parameters.setState(StringUtils.defaultString(state)); // // return parameters; // } // // @Override // public OAuth2ConnectionFactory<T> getConnectionFactory() { // return connectionFactory; // } // } // Path: social/src/main/java/org/meruvian/yama/social/facebook/FacebookService.java import java.io.ByteArrayInputStream; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.commons.FileInfo; import org.meruvian.yama.core.user.User; import org.meruvian.yama.social.core.AbstractSocialService; import org.springframework.social.connect.Connection; import org.springframework.social.connect.support.OAuth2ConnectionFactory; import org.springframework.social.facebook.api.Facebook; import org.springframework.social.facebook.api.ImageType; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.social.facebook; /** * @author Dian Aditya * */ public class FacebookService extends AbstractSocialService<Facebook> { public FacebookService(OAuth2ConnectionFactory<Facebook> facebook) { super(facebook); } @Override
public User createUser(Connection<?> connection) {
meruvian/yama
core/src/main/java/org/meruvian/yama/core/application/Application.java
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Lob; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.DefaultPersistence;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.core.application; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_application", indexes = { @Index(columnList = "create_by", unique = false) })
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // Path: core/src/main/java/org/meruvian/yama/core/application/Application.java import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Lob; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.NotNull; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.DefaultPersistence; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.core.application; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_application", indexes = { @Index(columnList = "create_by", unique = false) })
public class Application extends DefaultPersistence {
meruvian/yama
webapi/src/main/java/org/meruvian/yama/webapi/service/RestRoleService.java
// Path: core/src/main/java/org/meruvian/yama/core/role/Role.java // @Entity // @Table(name = "yama_workflow_role") // public class Role extends DefaultPersistence { // private String name; // private String description; // private List<UserRole> users = new ArrayList<UserRole>(); // // @NotNull // @Column(nullable = false, unique = true) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @JsonIgnore // @OneToMany(mappedBy = "role", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getUsers() { // return users; // } // // public void setUsers(List<UserRole> users) { // this.users = users; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/role/RoleRepository.java // @Repository // public interface RoleRepository extends DefaultRepository<Role> { // Role findByName(String name); // // @Query("SELECT r FROM Role r WHERE (r.name LIKE ?1% OR r.description LIKE ?2%) AND r.logInformation.activeFlag = ?3") // Page<Role> findByNameOrDescription(String name, String description, int activeFlag, Pageable pageable); // }
import javax.inject.Inject; import javax.ws.rs.BadRequestException; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.LogInformation; import org.meruvian.yama.core.role.Role; import org.meruvian.yama.core.role.RoleRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.service; /** * @author Dian Aditya * */ @Service @Transactional(readOnly = true) public class RestRoleService implements RoleService { @Inject
// Path: core/src/main/java/org/meruvian/yama/core/role/Role.java // @Entity // @Table(name = "yama_workflow_role") // public class Role extends DefaultPersistence { // private String name; // private String description; // private List<UserRole> users = new ArrayList<UserRole>(); // // @NotNull // @Column(nullable = false, unique = true) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @JsonIgnore // @OneToMany(mappedBy = "role", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getUsers() { // return users; // } // // public void setUsers(List<UserRole> users) { // this.users = users; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/role/RoleRepository.java // @Repository // public interface RoleRepository extends DefaultRepository<Role> { // Role findByName(String name); // // @Query("SELECT r FROM Role r WHERE (r.name LIKE ?1% OR r.description LIKE ?2%) AND r.logInformation.activeFlag = ?3") // Page<Role> findByNameOrDescription(String name, String description, int activeFlag, Pageable pageable); // } // Path: webapi/src/main/java/org/meruvian/yama/webapi/service/RestRoleService.java import javax.inject.Inject; import javax.ws.rs.BadRequestException; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.LogInformation; import org.meruvian.yama.core.role.Role; import org.meruvian.yama.core.role.RoleRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.service; /** * @author Dian Aditya * */ @Service @Transactional(readOnly = true) public class RestRoleService implements RoleService { @Inject
private RoleRepository roleRepository;
meruvian/yama
webapi/src/main/java/org/meruvian/yama/webapi/service/RestRoleService.java
// Path: core/src/main/java/org/meruvian/yama/core/role/Role.java // @Entity // @Table(name = "yama_workflow_role") // public class Role extends DefaultPersistence { // private String name; // private String description; // private List<UserRole> users = new ArrayList<UserRole>(); // // @NotNull // @Column(nullable = false, unique = true) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @JsonIgnore // @OneToMany(mappedBy = "role", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getUsers() { // return users; // } // // public void setUsers(List<UserRole> users) { // this.users = users; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/role/RoleRepository.java // @Repository // public interface RoleRepository extends DefaultRepository<Role> { // Role findByName(String name); // // @Query("SELECT r FROM Role r WHERE (r.name LIKE ?1% OR r.description LIKE ?2%) AND r.logInformation.activeFlag = ?3") // Page<Role> findByNameOrDescription(String name, String description, int activeFlag, Pageable pageable); // }
import javax.inject.Inject; import javax.ws.rs.BadRequestException; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.LogInformation; import org.meruvian.yama.core.role.Role; import org.meruvian.yama.core.role.RoleRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.service; /** * @author Dian Aditya * */ @Service @Transactional(readOnly = true) public class RestRoleService implements RoleService { @Inject private RoleRepository roleRepository; @Override
// Path: core/src/main/java/org/meruvian/yama/core/role/Role.java // @Entity // @Table(name = "yama_workflow_role") // public class Role extends DefaultPersistence { // private String name; // private String description; // private List<UserRole> users = new ArrayList<UserRole>(); // // @NotNull // @Column(nullable = false, unique = true) // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // @JsonIgnore // @OneToMany(mappedBy = "role", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getUsers() { // return users; // } // // public void setUsers(List<UserRole> users) { // this.users = users; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/role/RoleRepository.java // @Repository // public interface RoleRepository extends DefaultRepository<Role> { // Role findByName(String name); // // @Query("SELECT r FROM Role r WHERE (r.name LIKE ?1% OR r.description LIKE ?2%) AND r.logInformation.activeFlag = ?3") // Page<Role> findByNameOrDescription(String name, String description, int activeFlag, Pageable pageable); // } // Path: webapi/src/main/java/org/meruvian/yama/webapi/service/RestRoleService.java import javax.inject.Inject; import javax.ws.rs.BadRequestException; import org.apache.commons.lang3.StringUtils; import org.meruvian.yama.core.LogInformation; import org.meruvian.yama.core.role.Role; import org.meruvian.yama.core.role.RoleRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.service; /** * @author Dian Aditya * */ @Service @Transactional(readOnly = true) public class RestRoleService implements RoleService { @Inject private RoleRepository roleRepository; @Override
public Role getRoleById(String id) {
meruvian/yama
core/src/main/java/org/meruvian/yama/web/SessionCredentials.java
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: core/src/main/java/org/meruvian/yama/web/security/DefaultUserDetails.java // public class DefaultUserDetails extends org.springframework.security.core.userdetails.User { // private String id; // private User user; // // public DefaultUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) { // super(username, password, authorities); // } // // public DefaultUserDetails(String username, String password, boolean enabled, boolean accountNonExpired, // boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { // super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // }
import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.meruvian.yama.core.user.User; import org.meruvian.yama.web.security.DefaultUserDetails; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.web; /** * @author Dian Aditya * */ public class SessionCredentials { public static User getCurrentUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated()) { return null; }
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: core/src/main/java/org/meruvian/yama/web/security/DefaultUserDetails.java // public class DefaultUserDetails extends org.springframework.security.core.userdetails.User { // private String id; // private User user; // // public DefaultUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) { // super(username, password, authorities); // } // // public DefaultUserDetails(String username, String password, boolean enabled, boolean accountNonExpired, // boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { // super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // } // Path: core/src/main/java/org/meruvian/yama/web/SessionCredentials.java import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.meruvian.yama.core.user.User; import org.meruvian.yama.web.security.DefaultUserDetails; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.web; /** * @author Dian Aditya * */ public class SessionCredentials { public static User getCurrentUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || !authentication.isAuthenticated()) { return null; }
if (authentication.getPrincipal() instanceof DefaultUserDetails) {
meruvian/yama
core/src/main/java/org/meruvian/yama/core/role/UserRole.java
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // }
import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.meruvian.yama.core.DefaultPersistence; import org.meruvian.yama.core.user.User;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.core.role; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_user_role", uniqueConstraints = @UniqueConstraint(columnNames = { "role_id", "user_id" }))
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // Path: core/src/main/java/org/meruvian/yama/core/role/UserRole.java import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.meruvian.yama.core.DefaultPersistence; import org.meruvian.yama.core.user.User; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.core.role; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_user_role", uniqueConstraints = @UniqueConstraint(columnNames = { "role_id", "user_id" }))
public class UserRole extends DefaultPersistence {
meruvian/yama
core/src/main/java/org/meruvian/yama/core/role/UserRole.java
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // }
import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.meruvian.yama.core.DefaultPersistence; import org.meruvian.yama.core.user.User;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.core.role; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_user_role", uniqueConstraints = @UniqueConstraint(columnNames = { "role_id", "user_id" })) public class UserRole extends DefaultPersistence { private Role role = new Role();
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // // Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // Path: core/src/main/java/org/meruvian/yama/core/role/UserRole.java import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.meruvian.yama.core.DefaultPersistence; import org.meruvian.yama.core.user.User; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.core.role; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_user_role", uniqueConstraints = @UniqueConstraint(columnNames = { "role_id", "user_id" })) public class UserRole extends DefaultPersistence { private Role role = new Role();
private User user = new User();
meruvian/yama
webapi/src/main/java/org/meruvian/yama/webapi/config/persistence/UserRegisteredListener.java
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: webapi/src/main/java/org/meruvian/yama/webapi/service/commons/EmailService.java // @Service // public class EmailService { // private final Logger log = LoggerFactory.getLogger(EmailService.class); // // @Inject // private HtmlEmail htmlEmail; // // @Inject // private Configuration configuration; // // @Async // public void sendEmail(String to, String subject, String template, Object templateModel) { // log.debug("Sending email to {}", to); // // try { // StringWriter emailContent = new StringWriter(); // Template emailTemplate = configuration.getTemplate(template); // emailTemplate.process(templateModel, emailContent); // // htmlEmail.setSubject(subject); // htmlEmail.addTo(to); // htmlEmail.setHtmlMsg(emailContent.toString()); // htmlEmail.send(); // } catch (IOException e) { // log.error("Error occured while creating email template", e); // } catch (TemplateException e) { // log.error("Error occured while creating email template", e); // } catch (EmailException e) { // log.warn("Email could not be sent to {}", to, e); // } // } // }
import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PostInsertEvent; import org.hibernate.event.spi.PostInsertEventListener; import org.hibernate.persister.entity.EntityPersister; import org.meruvian.yama.core.user.User; import org.meruvian.yama.webapi.service.commons.EmailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.config.persistence; /** * @author Dian Aditya * */ @Component public class UserRegisteredListener implements PostInsertEventListener { private final Logger log = LoggerFactory.getLogger(UserRegisteredListener.class); @Inject public UserRegisteredListener(EventListenerRegistry registry) { registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(this); } @Inject
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: webapi/src/main/java/org/meruvian/yama/webapi/service/commons/EmailService.java // @Service // public class EmailService { // private final Logger log = LoggerFactory.getLogger(EmailService.class); // // @Inject // private HtmlEmail htmlEmail; // // @Inject // private Configuration configuration; // // @Async // public void sendEmail(String to, String subject, String template, Object templateModel) { // log.debug("Sending email to {}", to); // // try { // StringWriter emailContent = new StringWriter(); // Template emailTemplate = configuration.getTemplate(template); // emailTemplate.process(templateModel, emailContent); // // htmlEmail.setSubject(subject); // htmlEmail.addTo(to); // htmlEmail.setHtmlMsg(emailContent.toString()); // htmlEmail.send(); // } catch (IOException e) { // log.error("Error occured while creating email template", e); // } catch (TemplateException e) { // log.error("Error occured while creating email template", e); // } catch (EmailException e) { // log.warn("Email could not be sent to {}", to, e); // } // } // } // Path: webapi/src/main/java/org/meruvian/yama/webapi/config/persistence/UserRegisteredListener.java import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PostInsertEvent; import org.hibernate.event.spi.PostInsertEventListener; import org.hibernate.persister.entity.EntityPersister; import org.meruvian.yama.core.user.User; import org.meruvian.yama.webapi.service.commons.EmailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.config.persistence; /** * @author Dian Aditya * */ @Component public class UserRegisteredListener implements PostInsertEventListener { private final Logger log = LoggerFactory.getLogger(UserRegisteredListener.class); @Inject public UserRegisteredListener(EventListenerRegistry registry) { registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(this); } @Inject
private EmailService emailService;
meruvian/yama
webapi/src/main/java/org/meruvian/yama/webapi/config/persistence/UserRegisteredListener.java
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: webapi/src/main/java/org/meruvian/yama/webapi/service/commons/EmailService.java // @Service // public class EmailService { // private final Logger log = LoggerFactory.getLogger(EmailService.class); // // @Inject // private HtmlEmail htmlEmail; // // @Inject // private Configuration configuration; // // @Async // public void sendEmail(String to, String subject, String template, Object templateModel) { // log.debug("Sending email to {}", to); // // try { // StringWriter emailContent = new StringWriter(); // Template emailTemplate = configuration.getTemplate(template); // emailTemplate.process(templateModel, emailContent); // // htmlEmail.setSubject(subject); // htmlEmail.addTo(to); // htmlEmail.setHtmlMsg(emailContent.toString()); // htmlEmail.send(); // } catch (IOException e) { // log.error("Error occured while creating email template", e); // } catch (TemplateException e) { // log.error("Error occured while creating email template", e); // } catch (EmailException e) { // log.warn("Email could not be sent to {}", to, e); // } // } // }
import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PostInsertEvent; import org.hibernate.event.spi.PostInsertEventListener; import org.hibernate.persister.entity.EntityPersister; import org.meruvian.yama.core.user.User; import org.meruvian.yama.webapi.service.commons.EmailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.config.persistence; /** * @author Dian Aditya * */ @Component public class UserRegisteredListener implements PostInsertEventListener { private final Logger log = LoggerFactory.getLogger(UserRegisteredListener.class); @Inject public UserRegisteredListener(EventListenerRegistry registry) { registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(this); } @Inject private EmailService emailService; @Override public void onPostInsert(PostInsertEvent event) {
// Path: core/src/main/java/org/meruvian/yama/core/user/User.java // @Entity // @Table(name = "yama_backend_user") // public class User extends DefaultPersistence { // private String username; // private String password; // private String email; // private Name name = new Name(); // private Address address = new Address(); // private FileInfo fileInfo; // private List<UserRole> roles = new ArrayList<UserRole>(); // // @NotNull // @Size(min = 6) // @Column(name = "username", unique = true, nullable = false) // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // @Column(name = "password", nullable = false) // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // @NotNull // @Column(name = "email", unique = true, nullable = false) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Embedded // public Name getName() { // return name; // } // // public void setName(Name name) { // this.name = name; // } // // @Embedded // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // @ManyToOne // @JoinColumn(name = "file_info_id") // public FileInfo getFileInfo() { // return fileInfo; // } // // public void setFileInfo(FileInfo fileInfo) { // this.fileInfo = fileInfo; // } // // @JsonIgnore // @OneToMany(mappedBy = "user", cascade = { CascadeType.REMOVE }, fetch = FetchType.LAZY) // public List<UserRole> getRoles() { // return roles; // } // // public void setRoles(List<UserRole> roles) { // this.roles = roles; // } // } // // Path: webapi/src/main/java/org/meruvian/yama/webapi/service/commons/EmailService.java // @Service // public class EmailService { // private final Logger log = LoggerFactory.getLogger(EmailService.class); // // @Inject // private HtmlEmail htmlEmail; // // @Inject // private Configuration configuration; // // @Async // public void sendEmail(String to, String subject, String template, Object templateModel) { // log.debug("Sending email to {}", to); // // try { // StringWriter emailContent = new StringWriter(); // Template emailTemplate = configuration.getTemplate(template); // emailTemplate.process(templateModel, emailContent); // // htmlEmail.setSubject(subject); // htmlEmail.addTo(to); // htmlEmail.setHtmlMsg(emailContent.toString()); // htmlEmail.send(); // } catch (IOException e) { // log.error("Error occured while creating email template", e); // } catch (TemplateException e) { // log.error("Error occured while creating email template", e); // } catch (EmailException e) { // log.warn("Email could not be sent to {}", to, e); // } // } // } // Path: webapi/src/main/java/org/meruvian/yama/webapi/config/persistence/UserRegisteredListener.java import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import org.hibernate.event.service.spi.EventListenerRegistry; import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PostInsertEvent; import org.hibernate.event.spi.PostInsertEventListener; import org.hibernate.persister.entity.EntityPersister; import org.meruvian.yama.core.user.User; import org.meruvian.yama.webapi.service.commons.EmailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.webapi.config.persistence; /** * @author Dian Aditya * */ @Component public class UserRegisteredListener implements PostInsertEventListener { private final Logger log = LoggerFactory.getLogger(UserRegisteredListener.class); @Inject public UserRegisteredListener(EventListenerRegistry registry) { registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(this); } @Inject private EmailService emailService; @Override public void onPostInsert(PostInsertEvent event) {
if (event.getEntity() instanceof User) {
meruvian/yama
core/src/main/java/org/meruvian/yama/core/role/Role.java
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // }
import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import org.meruvian.yama.core.DefaultPersistence; import com.fasterxml.jackson.annotation.JsonIgnore;
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.core.role; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_workflow_role")
// Path: core/src/main/java/org/meruvian/yama/core/DefaultPersistence.java // @MappedSuperclass // public class DefaultPersistence { // protected String id; // protected LogInformation logInformation = new LogInformation(); // // @Id() // @GeneratedValue(generator = "system-uuid") // @GenericGenerator(name = "system-uuid", strategy = "uuid2") // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @Embedded // public LogInformation getLogInformation() { // return logInformation; // } // // public void setLogInformation(LogInformation logInformation) { // this.logInformation = logInformation; // } // } // Path: core/src/main/java/org/meruvian/yama/core/role/Role.java import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import org.meruvian.yama.core.DefaultPersistence; import com.fasterxml.jackson.annotation.JsonIgnore; /** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.core.role; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_workflow_role")
public class Role extends DefaultPersistence {
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/PlayerAdapter.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Club.java // @Table(name = "Club") public class Club extends Model { // // @Column(name = "ClubId") int clubId; // @Column(name = "Name") String name; // @Column(name = "Abbr") String abbr; // @Column(name = "Image") String image; // // public Club() { // super(); // } // // public int getClubId() { // return clubId; // } // // public void setClubId(int clubId) { // this.clubId = clubId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAbbr() { // return abbr; // } // // public void setAbbr(String abbr) { // this.abbr = abbr; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Player.java // @Table(name = "Player") public class Player extends Model { // // @SerializedName(value = "atleta_id") @Column(name = "PlayerId") String playerId; // @SerializedName(value = "nome") @Column(name = "Name") String name; // @SerializedName(value = "foto") @Column(name = "Photo") String photo; // @SerializedName(value = "preco_num") @Column(name = "Price") double price; // @SerializedName(value = "time_id") @Column(name = "Var") double var; // @SerializedName(value = "time_id") @Column(name = "Average") double average; // @SerializedName(value = "time_id") @Column(name = "Points") double points; // @SerializedName(value = "time_id") @Column(name = "Matches") double matches; // @SerializedName(value = "time_id") @Column(name = "ClubId") long clubId; // // public Player() { // super(); // } // // public String getPlayerId() { // return playerId; // } // // public void setPlayerId(String playerId) { // this.playerId = playerId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPhoto() { // return photo; // } // // public void setPhoto(String photo) { // this.photo = photo; // } // // public double getPrice() { // return price; // } // // public void setPrice(double price) { // this.price = price; // } // // public double getVar() { // return var; // } // // public void setVar(double var) { // this.var = var; // } // // public double getAverage() { // return average; // } // // public void setAverage(double average) { // this.average = average; // } // // public double getMatches() { // return matches; // } // // public void setMatches(double matches) { // this.matches = matches; // } // // public long getClubId() { // return clubId; // } // // public void setClubId(long clubId) { // this.clubId = clubId; // } // // public double getPoints() { // return points; // } // // public void setPoints(double points) { // this.points = points; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/IClubRepository.java // public interface IClubRepository extends ICrud<Club> { // // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.domain.Club; import com.github.pierry.cartolapp.domain.Player; import com.github.pierry.cartolapp.domain.contracts.IClubRepository; import com.koushikdutta.ion.Ion; import java.util.List;
package com.github.pierry.cartolapp.ui.adapters; public class PlayerAdapter extends RecyclerView.Adapter<PlayerAdapter.PlayerHolder> { private List<Player> players; private Context context;
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Club.java // @Table(name = "Club") public class Club extends Model { // // @Column(name = "ClubId") int clubId; // @Column(name = "Name") String name; // @Column(name = "Abbr") String abbr; // @Column(name = "Image") String image; // // public Club() { // super(); // } // // public int getClubId() { // return clubId; // } // // public void setClubId(int clubId) { // this.clubId = clubId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAbbr() { // return abbr; // } // // public void setAbbr(String abbr) { // this.abbr = abbr; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Player.java // @Table(name = "Player") public class Player extends Model { // // @SerializedName(value = "atleta_id") @Column(name = "PlayerId") String playerId; // @SerializedName(value = "nome") @Column(name = "Name") String name; // @SerializedName(value = "foto") @Column(name = "Photo") String photo; // @SerializedName(value = "preco_num") @Column(name = "Price") double price; // @SerializedName(value = "time_id") @Column(name = "Var") double var; // @SerializedName(value = "time_id") @Column(name = "Average") double average; // @SerializedName(value = "time_id") @Column(name = "Points") double points; // @SerializedName(value = "time_id") @Column(name = "Matches") double matches; // @SerializedName(value = "time_id") @Column(name = "ClubId") long clubId; // // public Player() { // super(); // } // // public String getPlayerId() { // return playerId; // } // // public void setPlayerId(String playerId) { // this.playerId = playerId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPhoto() { // return photo; // } // // public void setPhoto(String photo) { // this.photo = photo; // } // // public double getPrice() { // return price; // } // // public void setPrice(double price) { // this.price = price; // } // // public double getVar() { // return var; // } // // public void setVar(double var) { // this.var = var; // } // // public double getAverage() { // return average; // } // // public void setAverage(double average) { // this.average = average; // } // // public double getMatches() { // return matches; // } // // public void setMatches(double matches) { // this.matches = matches; // } // // public long getClubId() { // return clubId; // } // // public void setClubId(long clubId) { // this.clubId = clubId; // } // // public double getPoints() { // return points; // } // // public void setPoints(double points) { // this.points = points; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/IClubRepository.java // public interface IClubRepository extends ICrud<Club> { // // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/PlayerAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.domain.Club; import com.github.pierry.cartolapp.domain.Player; import com.github.pierry.cartolapp.domain.contracts.IClubRepository; import com.koushikdutta.ion.Ion; import java.util.List; package com.github.pierry.cartolapp.ui.adapters; public class PlayerAdapter extends RecyclerView.Adapter<PlayerAdapter.PlayerHolder> { private List<Player> players; private Context context;
private IClubRepository clubRepository;
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/PlayerAdapter.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Club.java // @Table(name = "Club") public class Club extends Model { // // @Column(name = "ClubId") int clubId; // @Column(name = "Name") String name; // @Column(name = "Abbr") String abbr; // @Column(name = "Image") String image; // // public Club() { // super(); // } // // public int getClubId() { // return clubId; // } // // public void setClubId(int clubId) { // this.clubId = clubId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAbbr() { // return abbr; // } // // public void setAbbr(String abbr) { // this.abbr = abbr; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Player.java // @Table(name = "Player") public class Player extends Model { // // @SerializedName(value = "atleta_id") @Column(name = "PlayerId") String playerId; // @SerializedName(value = "nome") @Column(name = "Name") String name; // @SerializedName(value = "foto") @Column(name = "Photo") String photo; // @SerializedName(value = "preco_num") @Column(name = "Price") double price; // @SerializedName(value = "time_id") @Column(name = "Var") double var; // @SerializedName(value = "time_id") @Column(name = "Average") double average; // @SerializedName(value = "time_id") @Column(name = "Points") double points; // @SerializedName(value = "time_id") @Column(name = "Matches") double matches; // @SerializedName(value = "time_id") @Column(name = "ClubId") long clubId; // // public Player() { // super(); // } // // public String getPlayerId() { // return playerId; // } // // public void setPlayerId(String playerId) { // this.playerId = playerId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPhoto() { // return photo; // } // // public void setPhoto(String photo) { // this.photo = photo; // } // // public double getPrice() { // return price; // } // // public void setPrice(double price) { // this.price = price; // } // // public double getVar() { // return var; // } // // public void setVar(double var) { // this.var = var; // } // // public double getAverage() { // return average; // } // // public void setAverage(double average) { // this.average = average; // } // // public double getMatches() { // return matches; // } // // public void setMatches(double matches) { // this.matches = matches; // } // // public long getClubId() { // return clubId; // } // // public void setClubId(long clubId) { // this.clubId = clubId; // } // // public double getPoints() { // return points; // } // // public void setPoints(double points) { // this.points = points; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/IClubRepository.java // public interface IClubRepository extends ICrud<Club> { // // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.domain.Club; import com.github.pierry.cartolapp.domain.Player; import com.github.pierry.cartolapp.domain.contracts.IClubRepository; import com.koushikdutta.ion.Ion; import java.util.List;
photo = (ImageView) view.findViewById(R.id.photo); nickname = (TextView) view.findViewById(R.id.nickname); club = (TextView) view.findViewById(R.id.club); price = (TextView) view.findViewById(R.id.price); points = (TextView) view.findViewById(R.id.points); } @Override public void onClick(View v) { switch (v.getId()) { default: break; } } } public PlayerAdapter(Context context, List<Player> players, IClubRepository clubRepository) { this.context = context; this.players = players; this.clubRepository = clubRepository; } @Override public PlayerHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_team, parent, false); return new PlayerHolder(itemView); } @Override public void onBindViewHolder(PlayerHolder holder, int position) { Player player = players.get(position); holder.nickname.setText(player.getName());
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Club.java // @Table(name = "Club") public class Club extends Model { // // @Column(name = "ClubId") int clubId; // @Column(name = "Name") String name; // @Column(name = "Abbr") String abbr; // @Column(name = "Image") String image; // // public Club() { // super(); // } // // public int getClubId() { // return clubId; // } // // public void setClubId(int clubId) { // this.clubId = clubId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getAbbr() { // return abbr; // } // // public void setAbbr(String abbr) { // this.abbr = abbr; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Player.java // @Table(name = "Player") public class Player extends Model { // // @SerializedName(value = "atleta_id") @Column(name = "PlayerId") String playerId; // @SerializedName(value = "nome") @Column(name = "Name") String name; // @SerializedName(value = "foto") @Column(name = "Photo") String photo; // @SerializedName(value = "preco_num") @Column(name = "Price") double price; // @SerializedName(value = "time_id") @Column(name = "Var") double var; // @SerializedName(value = "time_id") @Column(name = "Average") double average; // @SerializedName(value = "time_id") @Column(name = "Points") double points; // @SerializedName(value = "time_id") @Column(name = "Matches") double matches; // @SerializedName(value = "time_id") @Column(name = "ClubId") long clubId; // // public Player() { // super(); // } // // public String getPlayerId() { // return playerId; // } // // public void setPlayerId(String playerId) { // this.playerId = playerId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPhoto() { // return photo; // } // // public void setPhoto(String photo) { // this.photo = photo; // } // // public double getPrice() { // return price; // } // // public void setPrice(double price) { // this.price = price; // } // // public double getVar() { // return var; // } // // public void setVar(double var) { // this.var = var; // } // // public double getAverage() { // return average; // } // // public void setAverage(double average) { // this.average = average; // } // // public double getMatches() { // return matches; // } // // public void setMatches(double matches) { // this.matches = matches; // } // // public long getClubId() { // return clubId; // } // // public void setClubId(long clubId) { // this.clubId = clubId; // } // // public double getPoints() { // return points; // } // // public void setPoints(double points) { // this.points = points; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/IClubRepository.java // public interface IClubRepository extends ICrud<Club> { // // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/PlayerAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.domain.Club; import com.github.pierry.cartolapp.domain.Player; import com.github.pierry.cartolapp.domain.contracts.IClubRepository; import com.koushikdutta.ion.Ion; import java.util.List; photo = (ImageView) view.findViewById(R.id.photo); nickname = (TextView) view.findViewById(R.id.nickname); club = (TextView) view.findViewById(R.id.club); price = (TextView) view.findViewById(R.id.price); points = (TextView) view.findViewById(R.id.points); } @Override public void onClick(View v) { switch (v.getId()) { default: break; } } } public PlayerAdapter(Context context, List<Player> players, IClubRepository clubRepository) { this.context = context; this.players = players; this.clubRepository = clubRepository; } @Override public PlayerHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_team, parent, false); return new PlayerHolder(itemView); } @Override public void onBindViewHolder(PlayerHolder holder, int position) { Player player = players.get(position); holder.nickname.setText(player.getName());
Club club = clubRepository.getById(player.getClubId());
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/MainActivity.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/ToolbarBase.java // @EBean public class ToolbarBase { // // private Drawer drawer; // private Toolbar toolbar; // private Activity act; // private AccountHeader headerResult; // private Context context; // // public ToolbarBase(Context context) { // this.context = context; // } // // @UiThread public void injectToolbar(Toolbar toolbar, Activity act) { // this.toolbar = toolbar; // this.act = act; // initAccount(); // initDrawer(); // } // // @UiThread void initDrawer() { // PrimaryDrawerItem home = // new PrimaryDrawerItem().withName(R.string.home).withIcon(GoogleMaterial.Icon.gmd_home); // new DrawerBuilder().withActivity((Activity) act) // .withToolbar(toolbar) // .withHasStableIds(true) // .withTranslucentStatusBar(true) // .withSelectedItem(-1) // .withAccountHeader(headerResult) // .addDrawerItems(home) // .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { // @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { // switch (position) { // case 1: // context.startActivity(new Intent(context, MainActivity_.class)); // return true; // default: // return true; // } // } // }) // .build(); // } // // @UiThread void initAccount() { // headerResult = new AccountHeaderBuilder().withActivity(act) // .withHeaderBackground(R.color.colorPrimary) // .addProfiles(new ProfileDrawerItem().withName("Usuário")) // .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { // @Override // public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { // return false; // } // }) // .build(); // } // // @UiThread // public void changeColor(PagerSlidingTabStrip tabs, SystemBarTintManager tintManager, int newColor) { // tabs.setBackgroundColor(newColor); // tintManager.setTintColor(newColor); // } // }
import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.github.pierry.cartolapp.ui.ToolbarBase; import com.github.pierry.cartolapp.ui.fragments.HomeFragment_; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById;
package com.github.pierry.cartolapp; @EActivity(R.layout.activity_main) public class MainActivity extends AppCompatActivity { @ViewById Toolbar toolbar;
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/ToolbarBase.java // @EBean public class ToolbarBase { // // private Drawer drawer; // private Toolbar toolbar; // private Activity act; // private AccountHeader headerResult; // private Context context; // // public ToolbarBase(Context context) { // this.context = context; // } // // @UiThread public void injectToolbar(Toolbar toolbar, Activity act) { // this.toolbar = toolbar; // this.act = act; // initAccount(); // initDrawer(); // } // // @UiThread void initDrawer() { // PrimaryDrawerItem home = // new PrimaryDrawerItem().withName(R.string.home).withIcon(GoogleMaterial.Icon.gmd_home); // new DrawerBuilder().withActivity((Activity) act) // .withToolbar(toolbar) // .withHasStableIds(true) // .withTranslucentStatusBar(true) // .withSelectedItem(-1) // .withAccountHeader(headerResult) // .addDrawerItems(home) // .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { // @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { // switch (position) { // case 1: // context.startActivity(new Intent(context, MainActivity_.class)); // return true; // default: // return true; // } // } // }) // .build(); // } // // @UiThread void initAccount() { // headerResult = new AccountHeaderBuilder().withActivity(act) // .withHeaderBackground(R.color.colorPrimary) // .addProfiles(new ProfileDrawerItem().withName("Usuário")) // .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { // @Override // public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { // return false; // } // }) // .build(); // } // // @UiThread // public void changeColor(PagerSlidingTabStrip tabs, SystemBarTintManager tintManager, int newColor) { // tabs.setBackgroundColor(newColor); // tintManager.setTintColor(newColor); // } // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/MainActivity.java import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.github.pierry.cartolapp.ui.ToolbarBase; import com.github.pierry.cartolapp.ui.fragments.HomeFragment_; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; package com.github.pierry.cartolapp; @EActivity(R.layout.activity_main) public class MainActivity extends AppCompatActivity { @ViewById Toolbar toolbar;
@Bean(ToolbarBase.class) ToolbarBase toolbarBase;
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/SearchTeamAdapter.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Team.java // @Table(name = "Team") public class Team extends Model { // // @SerializedName(value = "time_id") @Column(name = "TeamId") long teamId; // @SerializedName(value = "nome") @Column(name = "Name") String name; // @SerializedName(value = "nome_cartola") @Column(name = "Owner") String owner; // @SerializedName(value = "url_escudo_png") @Column(name = "Image") String image; // @Column(name = "Mine") transient boolean mine; // @Column(name = "Points") transient double points; // // public Team() { // super(); // } // // public long getTeamId() { // return teamId; // } // // public void setTeamId(long teamId) { // this.teamId = teamId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public double getPoints() { // return points; // } // // public void setPoints(double points) { // this.points = points; // } // // public boolean isMine() { // return mine; // } // // public void setMine(boolean mine) { // this.mine = mine; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.domain.Team; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.koushikdutta.ion.Ion; import java.util.List;
package com.github.pierry.cartolapp.ui.adapters; public class SearchTeamAdapter extends RecyclerView.Adapter<SearchTeamAdapter.TeamHolder> { private List<Team> teams; private Context context;
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/Team.java // @Table(name = "Team") public class Team extends Model { // // @SerializedName(value = "time_id") @Column(name = "TeamId") long teamId; // @SerializedName(value = "nome") @Column(name = "Name") String name; // @SerializedName(value = "nome_cartola") @Column(name = "Owner") String owner; // @SerializedName(value = "url_escudo_png") @Column(name = "Image") String image; // @Column(name = "Mine") transient boolean mine; // @Column(name = "Points") transient double points; // // public Team() { // super(); // } // // public long getTeamId() { // return teamId; // } // // public void setTeamId(long teamId) { // this.teamId = teamId; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getOwner() { // return owner; // } // // public void setOwner(String owner) { // this.owner = owner; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // // public double getPoints() { // return points; // } // // public void setPoints(double points) { // this.points = points; // } // // public boolean isMine() { // return mine; // } // // public void setMine(boolean mine) { // this.mine = mine; // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/SearchTeamAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.domain.Team; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.koushikdutta.ion.Ion; import java.util.List; package com.github.pierry.cartolapp.ui.adapters; public class SearchTeamAdapter extends RecyclerView.Adapter<SearchTeamAdapter.TeamHolder> { private List<Team> teams; private Context context;
private ITeamRepository teamRepository;
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/SearchTeamActivity.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/TeamApi.java // @EBean public class TeamApi implements ITeamApi { // // @Bean(Api.class) IApi api; // @Bean(PlayerApi.class) IPlayerApi playerApi; // @Bean(TeamRepository.class) ITeamRepository teamRepository; // // @Override public void get(final Context context, String team, final RecyclerView recyclerView) { // String urlFull = ApiConstraints.TEAM.concat(team); // api.getArray(urlFull).setCallback(new FutureCallback<Response<JsonArray>>() { // @Override public void onCompleted(Exception e, Response<JsonArray> result) { // if (e != null) { // return; // } // int code = result.getHeaders().code(); // switch (code) { // case 200: // Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); // TypeToken listType = new TypeToken<List<Team>>() { // }; // List<Team> teams = (List<Team>) gson.fromJson(result.getResult(), listType.getType()); // SearchTeamAdapter teamAdapter = new SearchTeamAdapter(context, teams, teamRepository); // recyclerView.setAdapter(teamAdapter); // break; // case 404: // break; // } // } // }); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/contracts/ITeamApi.java // public interface ITeamApi { // // void get(Context context, String team, RecyclerView recyclerView); // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/repositories/TeamRepository.java // @EBean public class TeamRepository implements ITeamRepository { // // @Override public List<Team> get() { // try { // return new Select().from(Team.class).execute(); // } catch (Exception e) { // return Collections.emptyList(); // } // } // // @Override public Team getById(long id) { // try { // return new Select().from(Team.class).where("TeamId = ?", id).executeSingle(); // } catch (Exception e) { // return null; // } // } // // @Override public long create(Team item) { // try { // return item.save(); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // @Override public boolean update(Team item) { // try { // return item.save() > 0; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // @Override public boolean delete(long id) { // try { // new Delete().from(Team.class).where("TeamId = ?", id).executeSingle(); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // }
import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.widget.RelativeLayout; import com.github.pierry.cartolapp.MainActivity_; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.api.TeamApi; import com.github.pierry.cartolapp.api.contracts.ITeamApi; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.github.pierry.cartolapp.repositories.TeamRepository; import com.github.pierry.fitloader.RotateLoading; import com.rengwuxian.materialedittext.MaterialEditText; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById;
package com.github.pierry.cartolapp.ui; @EActivity(R.layout.activity_team_search) public class SearchTeamActivity extends AppCompatActivity { @ViewById RecyclerView recyclerView; @ViewById RelativeLayout body; @ViewById RotateLoading rotateLoading; @ViewById MaterialEditText teamRequest; @ViewById Toolbar toolbar;
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/TeamApi.java // @EBean public class TeamApi implements ITeamApi { // // @Bean(Api.class) IApi api; // @Bean(PlayerApi.class) IPlayerApi playerApi; // @Bean(TeamRepository.class) ITeamRepository teamRepository; // // @Override public void get(final Context context, String team, final RecyclerView recyclerView) { // String urlFull = ApiConstraints.TEAM.concat(team); // api.getArray(urlFull).setCallback(new FutureCallback<Response<JsonArray>>() { // @Override public void onCompleted(Exception e, Response<JsonArray> result) { // if (e != null) { // return; // } // int code = result.getHeaders().code(); // switch (code) { // case 200: // Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); // TypeToken listType = new TypeToken<List<Team>>() { // }; // List<Team> teams = (List<Team>) gson.fromJson(result.getResult(), listType.getType()); // SearchTeamAdapter teamAdapter = new SearchTeamAdapter(context, teams, teamRepository); // recyclerView.setAdapter(teamAdapter); // break; // case 404: // break; // } // } // }); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/contracts/ITeamApi.java // public interface ITeamApi { // // void get(Context context, String team, RecyclerView recyclerView); // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/repositories/TeamRepository.java // @EBean public class TeamRepository implements ITeamRepository { // // @Override public List<Team> get() { // try { // return new Select().from(Team.class).execute(); // } catch (Exception e) { // return Collections.emptyList(); // } // } // // @Override public Team getById(long id) { // try { // return new Select().from(Team.class).where("TeamId = ?", id).executeSingle(); // } catch (Exception e) { // return null; // } // } // // @Override public long create(Team item) { // try { // return item.save(); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // @Override public boolean update(Team item) { // try { // return item.save() > 0; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // @Override public boolean delete(long id) { // try { // new Delete().from(Team.class).where("TeamId = ?", id).executeSingle(); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/SearchTeamActivity.java import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.widget.RelativeLayout; import com.github.pierry.cartolapp.MainActivity_; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.api.TeamApi; import com.github.pierry.cartolapp.api.contracts.ITeamApi; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.github.pierry.cartolapp.repositories.TeamRepository; import com.github.pierry.fitloader.RotateLoading; import com.rengwuxian.materialedittext.MaterialEditText; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; package com.github.pierry.cartolapp.ui; @EActivity(R.layout.activity_team_search) public class SearchTeamActivity extends AppCompatActivity { @ViewById RecyclerView recyclerView; @ViewById RelativeLayout body; @ViewById RotateLoading rotateLoading; @ViewById MaterialEditText teamRequest; @ViewById Toolbar toolbar;
@Bean(TeamApi.class) ITeamApi teamApi;
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/SearchTeamActivity.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/TeamApi.java // @EBean public class TeamApi implements ITeamApi { // // @Bean(Api.class) IApi api; // @Bean(PlayerApi.class) IPlayerApi playerApi; // @Bean(TeamRepository.class) ITeamRepository teamRepository; // // @Override public void get(final Context context, String team, final RecyclerView recyclerView) { // String urlFull = ApiConstraints.TEAM.concat(team); // api.getArray(urlFull).setCallback(new FutureCallback<Response<JsonArray>>() { // @Override public void onCompleted(Exception e, Response<JsonArray> result) { // if (e != null) { // return; // } // int code = result.getHeaders().code(); // switch (code) { // case 200: // Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); // TypeToken listType = new TypeToken<List<Team>>() { // }; // List<Team> teams = (List<Team>) gson.fromJson(result.getResult(), listType.getType()); // SearchTeamAdapter teamAdapter = new SearchTeamAdapter(context, teams, teamRepository); // recyclerView.setAdapter(teamAdapter); // break; // case 404: // break; // } // } // }); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/contracts/ITeamApi.java // public interface ITeamApi { // // void get(Context context, String team, RecyclerView recyclerView); // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/repositories/TeamRepository.java // @EBean public class TeamRepository implements ITeamRepository { // // @Override public List<Team> get() { // try { // return new Select().from(Team.class).execute(); // } catch (Exception e) { // return Collections.emptyList(); // } // } // // @Override public Team getById(long id) { // try { // return new Select().from(Team.class).where("TeamId = ?", id).executeSingle(); // } catch (Exception e) { // return null; // } // } // // @Override public long create(Team item) { // try { // return item.save(); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // @Override public boolean update(Team item) { // try { // return item.save() > 0; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // @Override public boolean delete(long id) { // try { // new Delete().from(Team.class).where("TeamId = ?", id).executeSingle(); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // }
import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.widget.RelativeLayout; import com.github.pierry.cartolapp.MainActivity_; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.api.TeamApi; import com.github.pierry.cartolapp.api.contracts.ITeamApi; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.github.pierry.cartolapp.repositories.TeamRepository; import com.github.pierry.fitloader.RotateLoading; import com.rengwuxian.materialedittext.MaterialEditText; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById;
package com.github.pierry.cartolapp.ui; @EActivity(R.layout.activity_team_search) public class SearchTeamActivity extends AppCompatActivity { @ViewById RecyclerView recyclerView; @ViewById RelativeLayout body; @ViewById RotateLoading rotateLoading; @ViewById MaterialEditText teamRequest; @ViewById Toolbar toolbar;
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/TeamApi.java // @EBean public class TeamApi implements ITeamApi { // // @Bean(Api.class) IApi api; // @Bean(PlayerApi.class) IPlayerApi playerApi; // @Bean(TeamRepository.class) ITeamRepository teamRepository; // // @Override public void get(final Context context, String team, final RecyclerView recyclerView) { // String urlFull = ApiConstraints.TEAM.concat(team); // api.getArray(urlFull).setCallback(new FutureCallback<Response<JsonArray>>() { // @Override public void onCompleted(Exception e, Response<JsonArray> result) { // if (e != null) { // return; // } // int code = result.getHeaders().code(); // switch (code) { // case 200: // Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); // TypeToken listType = new TypeToken<List<Team>>() { // }; // List<Team> teams = (List<Team>) gson.fromJson(result.getResult(), listType.getType()); // SearchTeamAdapter teamAdapter = new SearchTeamAdapter(context, teams, teamRepository); // recyclerView.setAdapter(teamAdapter); // break; // case 404: // break; // } // } // }); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/contracts/ITeamApi.java // public interface ITeamApi { // // void get(Context context, String team, RecyclerView recyclerView); // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/repositories/TeamRepository.java // @EBean public class TeamRepository implements ITeamRepository { // // @Override public List<Team> get() { // try { // return new Select().from(Team.class).execute(); // } catch (Exception e) { // return Collections.emptyList(); // } // } // // @Override public Team getById(long id) { // try { // return new Select().from(Team.class).where("TeamId = ?", id).executeSingle(); // } catch (Exception e) { // return null; // } // } // // @Override public long create(Team item) { // try { // return item.save(); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // @Override public boolean update(Team item) { // try { // return item.save() > 0; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // @Override public boolean delete(long id) { // try { // new Delete().from(Team.class).where("TeamId = ?", id).executeSingle(); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/SearchTeamActivity.java import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.widget.RelativeLayout; import com.github.pierry.cartolapp.MainActivity_; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.api.TeamApi; import com.github.pierry.cartolapp.api.contracts.ITeamApi; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.github.pierry.cartolapp.repositories.TeamRepository; import com.github.pierry.fitloader.RotateLoading; import com.rengwuxian.materialedittext.MaterialEditText; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; package com.github.pierry.cartolapp.ui; @EActivity(R.layout.activity_team_search) public class SearchTeamActivity extends AppCompatActivity { @ViewById RecyclerView recyclerView; @ViewById RelativeLayout body; @ViewById RotateLoading rotateLoading; @ViewById MaterialEditText teamRequest; @ViewById Toolbar toolbar;
@Bean(TeamApi.class) ITeamApi teamApi;
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/SearchTeamActivity.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/TeamApi.java // @EBean public class TeamApi implements ITeamApi { // // @Bean(Api.class) IApi api; // @Bean(PlayerApi.class) IPlayerApi playerApi; // @Bean(TeamRepository.class) ITeamRepository teamRepository; // // @Override public void get(final Context context, String team, final RecyclerView recyclerView) { // String urlFull = ApiConstraints.TEAM.concat(team); // api.getArray(urlFull).setCallback(new FutureCallback<Response<JsonArray>>() { // @Override public void onCompleted(Exception e, Response<JsonArray> result) { // if (e != null) { // return; // } // int code = result.getHeaders().code(); // switch (code) { // case 200: // Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); // TypeToken listType = new TypeToken<List<Team>>() { // }; // List<Team> teams = (List<Team>) gson.fromJson(result.getResult(), listType.getType()); // SearchTeamAdapter teamAdapter = new SearchTeamAdapter(context, teams, teamRepository); // recyclerView.setAdapter(teamAdapter); // break; // case 404: // break; // } // } // }); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/contracts/ITeamApi.java // public interface ITeamApi { // // void get(Context context, String team, RecyclerView recyclerView); // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/repositories/TeamRepository.java // @EBean public class TeamRepository implements ITeamRepository { // // @Override public List<Team> get() { // try { // return new Select().from(Team.class).execute(); // } catch (Exception e) { // return Collections.emptyList(); // } // } // // @Override public Team getById(long id) { // try { // return new Select().from(Team.class).where("TeamId = ?", id).executeSingle(); // } catch (Exception e) { // return null; // } // } // // @Override public long create(Team item) { // try { // return item.save(); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // @Override public boolean update(Team item) { // try { // return item.save() > 0; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // @Override public boolean delete(long id) { // try { // new Delete().from(Team.class).where("TeamId = ?", id).executeSingle(); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // }
import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.widget.RelativeLayout; import com.github.pierry.cartolapp.MainActivity_; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.api.TeamApi; import com.github.pierry.cartolapp.api.contracts.ITeamApi; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.github.pierry.cartolapp.repositories.TeamRepository; import com.github.pierry.fitloader.RotateLoading; import com.rengwuxian.materialedittext.MaterialEditText; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById;
package com.github.pierry.cartolapp.ui; @EActivity(R.layout.activity_team_search) public class SearchTeamActivity extends AppCompatActivity { @ViewById RecyclerView recyclerView; @ViewById RelativeLayout body; @ViewById RotateLoading rotateLoading; @ViewById MaterialEditText teamRequest; @ViewById Toolbar toolbar; @Bean(TeamApi.class) ITeamApi teamApi;
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/TeamApi.java // @EBean public class TeamApi implements ITeamApi { // // @Bean(Api.class) IApi api; // @Bean(PlayerApi.class) IPlayerApi playerApi; // @Bean(TeamRepository.class) ITeamRepository teamRepository; // // @Override public void get(final Context context, String team, final RecyclerView recyclerView) { // String urlFull = ApiConstraints.TEAM.concat(team); // api.getArray(urlFull).setCallback(new FutureCallback<Response<JsonArray>>() { // @Override public void onCompleted(Exception e, Response<JsonArray> result) { // if (e != null) { // return; // } // int code = result.getHeaders().code(); // switch (code) { // case 200: // Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); // TypeToken listType = new TypeToken<List<Team>>() { // }; // List<Team> teams = (List<Team>) gson.fromJson(result.getResult(), listType.getType()); // SearchTeamAdapter teamAdapter = new SearchTeamAdapter(context, teams, teamRepository); // recyclerView.setAdapter(teamAdapter); // break; // case 404: // break; // } // } // }); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/contracts/ITeamApi.java // public interface ITeamApi { // // void get(Context context, String team, RecyclerView recyclerView); // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/repositories/TeamRepository.java // @EBean public class TeamRepository implements ITeamRepository { // // @Override public List<Team> get() { // try { // return new Select().from(Team.class).execute(); // } catch (Exception e) { // return Collections.emptyList(); // } // } // // @Override public Team getById(long id) { // try { // return new Select().from(Team.class).where("TeamId = ?", id).executeSingle(); // } catch (Exception e) { // return null; // } // } // // @Override public long create(Team item) { // try { // return item.save(); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // @Override public boolean update(Team item) { // try { // return item.save() > 0; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // @Override public boolean delete(long id) { // try { // new Delete().from(Team.class).where("TeamId = ?", id).executeSingle(); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/SearchTeamActivity.java import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.widget.RelativeLayout; import com.github.pierry.cartolapp.MainActivity_; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.api.TeamApi; import com.github.pierry.cartolapp.api.contracts.ITeamApi; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.github.pierry.cartolapp.repositories.TeamRepository; import com.github.pierry.fitloader.RotateLoading; import com.rengwuxian.materialedittext.MaterialEditText; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; package com.github.pierry.cartolapp.ui; @EActivity(R.layout.activity_team_search) public class SearchTeamActivity extends AppCompatActivity { @ViewById RecyclerView recyclerView; @ViewById RelativeLayout body; @ViewById RotateLoading rotateLoading; @ViewById MaterialEditText teamRequest; @ViewById Toolbar toolbar; @Bean(TeamApi.class) ITeamApi teamApi;
@Bean(TeamRepository.class) ITeamRepository teamRepository;
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/SearchTeamActivity.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/TeamApi.java // @EBean public class TeamApi implements ITeamApi { // // @Bean(Api.class) IApi api; // @Bean(PlayerApi.class) IPlayerApi playerApi; // @Bean(TeamRepository.class) ITeamRepository teamRepository; // // @Override public void get(final Context context, String team, final RecyclerView recyclerView) { // String urlFull = ApiConstraints.TEAM.concat(team); // api.getArray(urlFull).setCallback(new FutureCallback<Response<JsonArray>>() { // @Override public void onCompleted(Exception e, Response<JsonArray> result) { // if (e != null) { // return; // } // int code = result.getHeaders().code(); // switch (code) { // case 200: // Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); // TypeToken listType = new TypeToken<List<Team>>() { // }; // List<Team> teams = (List<Team>) gson.fromJson(result.getResult(), listType.getType()); // SearchTeamAdapter teamAdapter = new SearchTeamAdapter(context, teams, teamRepository); // recyclerView.setAdapter(teamAdapter); // break; // case 404: // break; // } // } // }); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/contracts/ITeamApi.java // public interface ITeamApi { // // void get(Context context, String team, RecyclerView recyclerView); // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/repositories/TeamRepository.java // @EBean public class TeamRepository implements ITeamRepository { // // @Override public List<Team> get() { // try { // return new Select().from(Team.class).execute(); // } catch (Exception e) { // return Collections.emptyList(); // } // } // // @Override public Team getById(long id) { // try { // return new Select().from(Team.class).where("TeamId = ?", id).executeSingle(); // } catch (Exception e) { // return null; // } // } // // @Override public long create(Team item) { // try { // return item.save(); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // @Override public boolean update(Team item) { // try { // return item.save() > 0; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // @Override public boolean delete(long id) { // try { // new Delete().from(Team.class).where("TeamId = ?", id).executeSingle(); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // }
import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.widget.RelativeLayout; import com.github.pierry.cartolapp.MainActivity_; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.api.TeamApi; import com.github.pierry.cartolapp.api.contracts.ITeamApi; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.github.pierry.cartolapp.repositories.TeamRepository; import com.github.pierry.fitloader.RotateLoading; import com.rengwuxian.materialedittext.MaterialEditText; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById;
package com.github.pierry.cartolapp.ui; @EActivity(R.layout.activity_team_search) public class SearchTeamActivity extends AppCompatActivity { @ViewById RecyclerView recyclerView; @ViewById RelativeLayout body; @ViewById RotateLoading rotateLoading; @ViewById MaterialEditText teamRequest; @ViewById Toolbar toolbar; @Bean(TeamApi.class) ITeamApi teamApi;
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/TeamApi.java // @EBean public class TeamApi implements ITeamApi { // // @Bean(Api.class) IApi api; // @Bean(PlayerApi.class) IPlayerApi playerApi; // @Bean(TeamRepository.class) ITeamRepository teamRepository; // // @Override public void get(final Context context, String team, final RecyclerView recyclerView) { // String urlFull = ApiConstraints.TEAM.concat(team); // api.getArray(urlFull).setCallback(new FutureCallback<Response<JsonArray>>() { // @Override public void onCompleted(Exception e, Response<JsonArray> result) { // if (e != null) { // return; // } // int code = result.getHeaders().code(); // switch (code) { // case 200: // Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); // TypeToken listType = new TypeToken<List<Team>>() { // }; // List<Team> teams = (List<Team>) gson.fromJson(result.getResult(), listType.getType()); // SearchTeamAdapter teamAdapter = new SearchTeamAdapter(context, teams, teamRepository); // recyclerView.setAdapter(teamAdapter); // break; // case 404: // break; // } // } // }); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/api/contracts/ITeamApi.java // public interface ITeamApi { // // void get(Context context, String team, RecyclerView recyclerView); // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/domain/contracts/ITeamRepository.java // public interface ITeamRepository extends ICrud<Team> { // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/repositories/TeamRepository.java // @EBean public class TeamRepository implements ITeamRepository { // // @Override public List<Team> get() { // try { // return new Select().from(Team.class).execute(); // } catch (Exception e) { // return Collections.emptyList(); // } // } // // @Override public Team getById(long id) { // try { // return new Select().from(Team.class).where("TeamId = ?", id).executeSingle(); // } catch (Exception e) { // return null; // } // } // // @Override public long create(Team item) { // try { // return item.save(); // } catch (Exception e) { // e.printStackTrace(); // return 0; // } // } // // @Override public boolean update(Team item) { // try { // return item.save() > 0; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // // @Override public boolean delete(long id) { // try { // new Delete().from(Team.class).where("TeamId = ?", id).executeSingle(); // return true; // } catch (Exception e) { // e.printStackTrace(); // return false; // } // } // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/SearchTeamActivity.java import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.widget.RelativeLayout; import com.github.pierry.cartolapp.MainActivity_; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.api.TeamApi; import com.github.pierry.cartolapp.api.contracts.ITeamApi; import com.github.pierry.cartolapp.domain.contracts.ITeamRepository; import com.github.pierry.cartolapp.repositories.TeamRepository; import com.github.pierry.fitloader.RotateLoading; import com.rengwuxian.materialedittext.MaterialEditText; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; package com.github.pierry.cartolapp.ui; @EActivity(R.layout.activity_team_search) public class SearchTeamActivity extends AppCompatActivity { @ViewById RecyclerView recyclerView; @ViewById RelativeLayout body; @ViewById RotateLoading rotateLoading; @ViewById MaterialEditText teamRequest; @ViewById Toolbar toolbar; @Bean(TeamApi.class) ITeamApi teamApi;
@Bean(TeamRepository.class) ITeamRepository teamRepository;
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/fragments/HomeFragment.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/ToolbarBase.java // @EBean public class ToolbarBase { // // private Drawer drawer; // private Toolbar toolbar; // private Activity act; // private AccountHeader headerResult; // private Context context; // // public ToolbarBase(Context context) { // this.context = context; // } // // @UiThread public void injectToolbar(Toolbar toolbar, Activity act) { // this.toolbar = toolbar; // this.act = act; // initAccount(); // initDrawer(); // } // // @UiThread void initDrawer() { // PrimaryDrawerItem home = // new PrimaryDrawerItem().withName(R.string.home).withIcon(GoogleMaterial.Icon.gmd_home); // new DrawerBuilder().withActivity((Activity) act) // .withToolbar(toolbar) // .withHasStableIds(true) // .withTranslucentStatusBar(true) // .withSelectedItem(-1) // .withAccountHeader(headerResult) // .addDrawerItems(home) // .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { // @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { // switch (position) { // case 1: // context.startActivity(new Intent(context, MainActivity_.class)); // return true; // default: // return true; // } // } // }) // .build(); // } // // @UiThread void initAccount() { // headerResult = new AccountHeaderBuilder().withActivity(act) // .withHeaderBackground(R.color.colorPrimary) // .addProfiles(new ProfileDrawerItem().withName("Usuário")) // .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { // @Override // public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { // return false; // } // }) // .build(); // } // // @UiThread // public void changeColor(PagerSlidingTabStrip tabs, SystemBarTintManager tintManager, int newColor) { // tabs.setBackgroundColor(newColor); // tintManager.setTintColor(newColor); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/HomeAdapter.java // public class HomeAdapter extends FragmentPagerAdapter { // final int PAGE_COUNT = 3; // private String tabTitles[] = new String[] { "Equipes", "Jogadores", "Perfil" }; // // public HomeAdapter(FragmentManager fm) { // super(fm); // } // // @Override public int getCount() { // return PAGE_COUNT; // } // // @Override public Fragment getItem(int position) { // switch (position) { // case 0: // return new TeamFragment_(); // case 1: // return new PlayerFragment_(); // case 2: // return new PlayerFragment_(); // } // return new TeamFragment_(); // } // // @Override public CharSequence getPageTitle(int position) { // return tabTitles[position]; // } // }
import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.TypedValue; import android.widget.LinearLayout; import android.widget.TextView; import com.astuetz.PagerSlidingTabStrip; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.ui.ToolbarBase; import com.github.pierry.cartolapp.ui.adapters.HomeAdapter; import com.readystatesoftware.systembartint.SystemBarTintManager; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.ViewById;
package com.github.pierry.cartolapp.ui.fragments; @EFragment(R.layout.fragment_home) public class HomeFragment extends Fragment implements OnPageChangeListener { @ViewById PagerSlidingTabStrip tabs; @ViewById ViewPager pager;
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/ToolbarBase.java // @EBean public class ToolbarBase { // // private Drawer drawer; // private Toolbar toolbar; // private Activity act; // private AccountHeader headerResult; // private Context context; // // public ToolbarBase(Context context) { // this.context = context; // } // // @UiThread public void injectToolbar(Toolbar toolbar, Activity act) { // this.toolbar = toolbar; // this.act = act; // initAccount(); // initDrawer(); // } // // @UiThread void initDrawer() { // PrimaryDrawerItem home = // new PrimaryDrawerItem().withName(R.string.home).withIcon(GoogleMaterial.Icon.gmd_home); // new DrawerBuilder().withActivity((Activity) act) // .withToolbar(toolbar) // .withHasStableIds(true) // .withTranslucentStatusBar(true) // .withSelectedItem(-1) // .withAccountHeader(headerResult) // .addDrawerItems(home) // .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { // @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { // switch (position) { // case 1: // context.startActivity(new Intent(context, MainActivity_.class)); // return true; // default: // return true; // } // } // }) // .build(); // } // // @UiThread void initAccount() { // headerResult = new AccountHeaderBuilder().withActivity(act) // .withHeaderBackground(R.color.colorPrimary) // .addProfiles(new ProfileDrawerItem().withName("Usuário")) // .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { // @Override // public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { // return false; // } // }) // .build(); // } // // @UiThread // public void changeColor(PagerSlidingTabStrip tabs, SystemBarTintManager tintManager, int newColor) { // tabs.setBackgroundColor(newColor); // tintManager.setTintColor(newColor); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/HomeAdapter.java // public class HomeAdapter extends FragmentPagerAdapter { // final int PAGE_COUNT = 3; // private String tabTitles[] = new String[] { "Equipes", "Jogadores", "Perfil" }; // // public HomeAdapter(FragmentManager fm) { // super(fm); // } // // @Override public int getCount() { // return PAGE_COUNT; // } // // @Override public Fragment getItem(int position) { // switch (position) { // case 0: // return new TeamFragment_(); // case 1: // return new PlayerFragment_(); // case 2: // return new PlayerFragment_(); // } // return new TeamFragment_(); // } // // @Override public CharSequence getPageTitle(int position) { // return tabTitles[position]; // } // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/fragments/HomeFragment.java import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.TypedValue; import android.widget.LinearLayout; import android.widget.TextView; import com.astuetz.PagerSlidingTabStrip; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.ui.ToolbarBase; import com.github.pierry.cartolapp.ui.adapters.HomeAdapter; import com.readystatesoftware.systembartint.SystemBarTintManager; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.ViewById; package com.github.pierry.cartolapp.ui.fragments; @EFragment(R.layout.fragment_home) public class HomeFragment extends Fragment implements OnPageChangeListener { @ViewById PagerSlidingTabStrip tabs; @ViewById ViewPager pager;
@Bean(ToolbarBase.class) ToolbarBase toolbarBase;
Pierry/cartolapp
cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/fragments/HomeFragment.java
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/ToolbarBase.java // @EBean public class ToolbarBase { // // private Drawer drawer; // private Toolbar toolbar; // private Activity act; // private AccountHeader headerResult; // private Context context; // // public ToolbarBase(Context context) { // this.context = context; // } // // @UiThread public void injectToolbar(Toolbar toolbar, Activity act) { // this.toolbar = toolbar; // this.act = act; // initAccount(); // initDrawer(); // } // // @UiThread void initDrawer() { // PrimaryDrawerItem home = // new PrimaryDrawerItem().withName(R.string.home).withIcon(GoogleMaterial.Icon.gmd_home); // new DrawerBuilder().withActivity((Activity) act) // .withToolbar(toolbar) // .withHasStableIds(true) // .withTranslucentStatusBar(true) // .withSelectedItem(-1) // .withAccountHeader(headerResult) // .addDrawerItems(home) // .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { // @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { // switch (position) { // case 1: // context.startActivity(new Intent(context, MainActivity_.class)); // return true; // default: // return true; // } // } // }) // .build(); // } // // @UiThread void initAccount() { // headerResult = new AccountHeaderBuilder().withActivity(act) // .withHeaderBackground(R.color.colorPrimary) // .addProfiles(new ProfileDrawerItem().withName("Usuário")) // .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { // @Override // public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { // return false; // } // }) // .build(); // } // // @UiThread // public void changeColor(PagerSlidingTabStrip tabs, SystemBarTintManager tintManager, int newColor) { // tabs.setBackgroundColor(newColor); // tintManager.setTintColor(newColor); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/HomeAdapter.java // public class HomeAdapter extends FragmentPagerAdapter { // final int PAGE_COUNT = 3; // private String tabTitles[] = new String[] { "Equipes", "Jogadores", "Perfil" }; // // public HomeAdapter(FragmentManager fm) { // super(fm); // } // // @Override public int getCount() { // return PAGE_COUNT; // } // // @Override public Fragment getItem(int position) { // switch (position) { // case 0: // return new TeamFragment_(); // case 1: // return new PlayerFragment_(); // case 2: // return new PlayerFragment_(); // } // return new TeamFragment_(); // } // // @Override public CharSequence getPageTitle(int position) { // return tabTitles[position]; // } // }
import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.TypedValue; import android.widget.LinearLayout; import android.widget.TextView; import com.astuetz.PagerSlidingTabStrip; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.ui.ToolbarBase; import com.github.pierry.cartolapp.ui.adapters.HomeAdapter; import com.readystatesoftware.systembartint.SystemBarTintManager; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.ViewById;
package com.github.pierry.cartolapp.ui.fragments; @EFragment(R.layout.fragment_home) public class HomeFragment extends Fragment implements OnPageChangeListener { @ViewById PagerSlidingTabStrip tabs; @ViewById ViewPager pager; @Bean(ToolbarBase.class) ToolbarBase toolbarBase; @AfterViews void init() { SystemBarTintManager tintManager = new SystemBarTintManager(getActivity()); tintManager.setStatusBarTintEnabled(true);
// Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/ToolbarBase.java // @EBean public class ToolbarBase { // // private Drawer drawer; // private Toolbar toolbar; // private Activity act; // private AccountHeader headerResult; // private Context context; // // public ToolbarBase(Context context) { // this.context = context; // } // // @UiThread public void injectToolbar(Toolbar toolbar, Activity act) { // this.toolbar = toolbar; // this.act = act; // initAccount(); // initDrawer(); // } // // @UiThread void initDrawer() { // PrimaryDrawerItem home = // new PrimaryDrawerItem().withName(R.string.home).withIcon(GoogleMaterial.Icon.gmd_home); // new DrawerBuilder().withActivity((Activity) act) // .withToolbar(toolbar) // .withHasStableIds(true) // .withTranslucentStatusBar(true) // .withSelectedItem(-1) // .withAccountHeader(headerResult) // .addDrawerItems(home) // .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { // @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { // switch (position) { // case 1: // context.startActivity(new Intent(context, MainActivity_.class)); // return true; // default: // return true; // } // } // }) // .build(); // } // // @UiThread void initAccount() { // headerResult = new AccountHeaderBuilder().withActivity(act) // .withHeaderBackground(R.color.colorPrimary) // .addProfiles(new ProfileDrawerItem().withName("Usuário")) // .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { // @Override // public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { // return false; // } // }) // .build(); // } // // @UiThread // public void changeColor(PagerSlidingTabStrip tabs, SystemBarTintManager tintManager, int newColor) { // tabs.setBackgroundColor(newColor); // tintManager.setTintColor(newColor); // } // } // // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/adapters/HomeAdapter.java // public class HomeAdapter extends FragmentPagerAdapter { // final int PAGE_COUNT = 3; // private String tabTitles[] = new String[] { "Equipes", "Jogadores", "Perfil" }; // // public HomeAdapter(FragmentManager fm) { // super(fm); // } // // @Override public int getCount() { // return PAGE_COUNT; // } // // @Override public Fragment getItem(int position) { // switch (position) { // case 0: // return new TeamFragment_(); // case 1: // return new PlayerFragment_(); // case 2: // return new PlayerFragment_(); // } // return new TeamFragment_(); // } // // @Override public CharSequence getPageTitle(int position) { // return tabTitles[position]; // } // } // Path: cartolapp/app/src/main/java/com/github/pierry/cartolapp/ui/fragments/HomeFragment.java import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.TypedValue; import android.widget.LinearLayout; import android.widget.TextView; import com.astuetz.PagerSlidingTabStrip; import com.github.pierry.cartolapp.R; import com.github.pierry.cartolapp.ui.ToolbarBase; import com.github.pierry.cartolapp.ui.adapters.HomeAdapter; import com.readystatesoftware.systembartint.SystemBarTintManager; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.ViewById; package com.github.pierry.cartolapp.ui.fragments; @EFragment(R.layout.fragment_home) public class HomeFragment extends Fragment implements OnPageChangeListener { @ViewById PagerSlidingTabStrip tabs; @ViewById ViewPager pager; @Bean(ToolbarBase.class) ToolbarBase toolbarBase; @AfterViews void init() { SystemBarTintManager tintManager = new SystemBarTintManager(getActivity()); tintManager.setStatusBarTintEnabled(true);
pager.setAdapter(new HomeAdapter(getActivity().getSupportFragmentManager()));
project-flink/flink-perf
flink-jobs/src/main/parking/tpch/generators/programs/TPCHGenerator.java
// Path: flink-jobs/src/main/parking/tpch/generators/core/DistributedTPCH.java // public class DistributedTPCH { // private double scale; // private ExecutionEnvironment env; // // // public DistributedTPCH(ExecutionEnvironment env) { // this.env = env; // } // // public void setScale(double scale) { // this.scale = scale; // } // // public double getScale() { // return scale; // } // // public DataSet<Part> generateParts() { // return getGenerator(PartGenerator.class, Part.class); // } // // public DataSet<LineItem> generateLineItems() { // return getGenerator(LineItemGenerator.class, LineItem.class); // } // public DataSet<Order> generateOrders() { // return getGenerator(OrderGenerator.class, Order.class); // } // // public DataSet<Supplier> generateSuppliers() { // return getGenerator(SupplierGenerator.class, Supplier.class); // } // // public DataSet<Region> generateRegions() { // return getGenerator(RegionGenerator.class, Region.class); // } // // public DataSet<Nation> generateNations() { // return getGenerator(NationGenerator.class, Nation.class); // } // // public DataSet<Customer> generateCustomers() { // return getGenerator(CustomerGenerator.class, Customer.class); // } // // public DataSet<PartSupplier> generatePartSuppliers() { // return getGenerator(PartSupplierGenerator.class, PartSupplier.class); // } // // public <T> DataSet<T> getGenerator(Class<? extends Iterable<T>> generatorClass, Class<T> type) { // SplittableIterator<T> si = new TPCHGeneratorSplittableIterator(scale, env.getParallelism(), generatorClass); // return env.fromParallelCollection(si, type).name("Generator: "+generatorClass); // } // } // // Path: flink-jobs/src/main/parking/tpch/generators/core/TpchEntityFormatter.java // public class TpchEntityFormatter<T extends TpchEntity> implements TextOutputFormat.TextFormatter<T> { // // @Override // public String format(T value) { // return value.toLine(); // } // }
import com.github.projectflink.generators.tpch.generators.core.DistributedTPCH; import com.github.projectflink.generators.tpch.generators.core.TpchEntityFormatter; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import org.apache.flink.api.java.ExecutionEnvironment;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.projectflink.generators.tpch.generators.programs; public class TPCHGenerator { public static void main(String[] args) throws Exception { // Parse and handle arguments ArgumentParser ap = ArgumentParsers.newArgumentParser("Distributed TPCH"); ap.defaultHelp(true); ap.addArgument("-s", "--scale").setDefault(1.0).help("TPC H Scale (final Size in GB)").type(Double.class); ap.addArgument("-p","--parallelism").setDefault(1).help("Parallelism for program").type(Integer.class); ap.addArgument("-e", "--extension").setDefault(".csv").help("File extension for generated files"); ap.addArgument("-o", "--outpath").setDefault("/tmp/").help("Output directory"); Namespace ns = null; try { ns = ap.parseArgs(args); } catch (ArgumentParserException e) { ap.handleError(e); System.exit(1); } final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(ns.getInt("parallelism"));
// Path: flink-jobs/src/main/parking/tpch/generators/core/DistributedTPCH.java // public class DistributedTPCH { // private double scale; // private ExecutionEnvironment env; // // // public DistributedTPCH(ExecutionEnvironment env) { // this.env = env; // } // // public void setScale(double scale) { // this.scale = scale; // } // // public double getScale() { // return scale; // } // // public DataSet<Part> generateParts() { // return getGenerator(PartGenerator.class, Part.class); // } // // public DataSet<LineItem> generateLineItems() { // return getGenerator(LineItemGenerator.class, LineItem.class); // } // public DataSet<Order> generateOrders() { // return getGenerator(OrderGenerator.class, Order.class); // } // // public DataSet<Supplier> generateSuppliers() { // return getGenerator(SupplierGenerator.class, Supplier.class); // } // // public DataSet<Region> generateRegions() { // return getGenerator(RegionGenerator.class, Region.class); // } // // public DataSet<Nation> generateNations() { // return getGenerator(NationGenerator.class, Nation.class); // } // // public DataSet<Customer> generateCustomers() { // return getGenerator(CustomerGenerator.class, Customer.class); // } // // public DataSet<PartSupplier> generatePartSuppliers() { // return getGenerator(PartSupplierGenerator.class, PartSupplier.class); // } // // public <T> DataSet<T> getGenerator(Class<? extends Iterable<T>> generatorClass, Class<T> type) { // SplittableIterator<T> si = new TPCHGeneratorSplittableIterator(scale, env.getParallelism(), generatorClass); // return env.fromParallelCollection(si, type).name("Generator: "+generatorClass); // } // } // // Path: flink-jobs/src/main/parking/tpch/generators/core/TpchEntityFormatter.java // public class TpchEntityFormatter<T extends TpchEntity> implements TextOutputFormat.TextFormatter<T> { // // @Override // public String format(T value) { // return value.toLine(); // } // } // Path: flink-jobs/src/main/parking/tpch/generators/programs/TPCHGenerator.java import com.github.projectflink.generators.tpch.generators.core.DistributedTPCH; import com.github.projectflink.generators.tpch.generators.core.TpchEntityFormatter; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import org.apache.flink.api.java.ExecutionEnvironment; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.projectflink.generators.tpch.generators.programs; public class TPCHGenerator { public static void main(String[] args) throws Exception { // Parse and handle arguments ArgumentParser ap = ArgumentParsers.newArgumentParser("Distributed TPCH"); ap.defaultHelp(true); ap.addArgument("-s", "--scale").setDefault(1.0).help("TPC H Scale (final Size in GB)").type(Double.class); ap.addArgument("-p","--parallelism").setDefault(1).help("Parallelism for program").type(Integer.class); ap.addArgument("-e", "--extension").setDefault(".csv").help("File extension for generated files"); ap.addArgument("-o", "--outpath").setDefault("/tmp/").help("Output directory"); Namespace ns = null; try { ns = ap.parseArgs(args); } catch (ArgumentParserException e) { ap.handleError(e); System.exit(1); } final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(ns.getInt("parallelism"));
DistributedTPCH gen = new DistributedTPCH(env);
project-flink/flink-perf
flink-jobs/src/main/parking/tpch/generators/programs/TPCHGenerator.java
// Path: flink-jobs/src/main/parking/tpch/generators/core/DistributedTPCH.java // public class DistributedTPCH { // private double scale; // private ExecutionEnvironment env; // // // public DistributedTPCH(ExecutionEnvironment env) { // this.env = env; // } // // public void setScale(double scale) { // this.scale = scale; // } // // public double getScale() { // return scale; // } // // public DataSet<Part> generateParts() { // return getGenerator(PartGenerator.class, Part.class); // } // // public DataSet<LineItem> generateLineItems() { // return getGenerator(LineItemGenerator.class, LineItem.class); // } // public DataSet<Order> generateOrders() { // return getGenerator(OrderGenerator.class, Order.class); // } // // public DataSet<Supplier> generateSuppliers() { // return getGenerator(SupplierGenerator.class, Supplier.class); // } // // public DataSet<Region> generateRegions() { // return getGenerator(RegionGenerator.class, Region.class); // } // // public DataSet<Nation> generateNations() { // return getGenerator(NationGenerator.class, Nation.class); // } // // public DataSet<Customer> generateCustomers() { // return getGenerator(CustomerGenerator.class, Customer.class); // } // // public DataSet<PartSupplier> generatePartSuppliers() { // return getGenerator(PartSupplierGenerator.class, PartSupplier.class); // } // // public <T> DataSet<T> getGenerator(Class<? extends Iterable<T>> generatorClass, Class<T> type) { // SplittableIterator<T> si = new TPCHGeneratorSplittableIterator(scale, env.getParallelism(), generatorClass); // return env.fromParallelCollection(si, type).name("Generator: "+generatorClass); // } // } // // Path: flink-jobs/src/main/parking/tpch/generators/core/TpchEntityFormatter.java // public class TpchEntityFormatter<T extends TpchEntity> implements TextOutputFormat.TextFormatter<T> { // // @Override // public String format(T value) { // return value.toLine(); // } // }
import com.github.projectflink.generators.tpch.generators.core.DistributedTPCH; import com.github.projectflink.generators.tpch.generators.core.TpchEntityFormatter; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import org.apache.flink.api.java.ExecutionEnvironment;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.projectflink.generators.tpch.generators.programs; public class TPCHGenerator { public static void main(String[] args) throws Exception { // Parse and handle arguments ArgumentParser ap = ArgumentParsers.newArgumentParser("Distributed TPCH"); ap.defaultHelp(true); ap.addArgument("-s", "--scale").setDefault(1.0).help("TPC H Scale (final Size in GB)").type(Double.class); ap.addArgument("-p","--parallelism").setDefault(1).help("Parallelism for program").type(Integer.class); ap.addArgument("-e", "--extension").setDefault(".csv").help("File extension for generated files"); ap.addArgument("-o", "--outpath").setDefault("/tmp/").help("Output directory"); Namespace ns = null; try { ns = ap.parseArgs(args); } catch (ArgumentParserException e) { ap.handleError(e); System.exit(1); } final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(ns.getInt("parallelism")); DistributedTPCH gen = new DistributedTPCH(env); gen.setScale(ns.getDouble("scale")); String base = ns.getString("outpath"); String ext = ns.getString("extension");
// Path: flink-jobs/src/main/parking/tpch/generators/core/DistributedTPCH.java // public class DistributedTPCH { // private double scale; // private ExecutionEnvironment env; // // // public DistributedTPCH(ExecutionEnvironment env) { // this.env = env; // } // // public void setScale(double scale) { // this.scale = scale; // } // // public double getScale() { // return scale; // } // // public DataSet<Part> generateParts() { // return getGenerator(PartGenerator.class, Part.class); // } // // public DataSet<LineItem> generateLineItems() { // return getGenerator(LineItemGenerator.class, LineItem.class); // } // public DataSet<Order> generateOrders() { // return getGenerator(OrderGenerator.class, Order.class); // } // // public DataSet<Supplier> generateSuppliers() { // return getGenerator(SupplierGenerator.class, Supplier.class); // } // // public DataSet<Region> generateRegions() { // return getGenerator(RegionGenerator.class, Region.class); // } // // public DataSet<Nation> generateNations() { // return getGenerator(NationGenerator.class, Nation.class); // } // // public DataSet<Customer> generateCustomers() { // return getGenerator(CustomerGenerator.class, Customer.class); // } // // public DataSet<PartSupplier> generatePartSuppliers() { // return getGenerator(PartSupplierGenerator.class, PartSupplier.class); // } // // public <T> DataSet<T> getGenerator(Class<? extends Iterable<T>> generatorClass, Class<T> type) { // SplittableIterator<T> si = new TPCHGeneratorSplittableIterator(scale, env.getParallelism(), generatorClass); // return env.fromParallelCollection(si, type).name("Generator: "+generatorClass); // } // } // // Path: flink-jobs/src/main/parking/tpch/generators/core/TpchEntityFormatter.java // public class TpchEntityFormatter<T extends TpchEntity> implements TextOutputFormat.TextFormatter<T> { // // @Override // public String format(T value) { // return value.toLine(); // } // } // Path: flink-jobs/src/main/parking/tpch/generators/programs/TPCHGenerator.java import com.github.projectflink.generators.tpch.generators.core.DistributedTPCH; import com.github.projectflink.generators.tpch.generators.core.TpchEntityFormatter; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import org.apache.flink.api.java.ExecutionEnvironment; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.projectflink.generators.tpch.generators.programs; public class TPCHGenerator { public static void main(String[] args) throws Exception { // Parse and handle arguments ArgumentParser ap = ArgumentParsers.newArgumentParser("Distributed TPCH"); ap.defaultHelp(true); ap.addArgument("-s", "--scale").setDefault(1.0).help("TPC H Scale (final Size in GB)").type(Double.class); ap.addArgument("-p","--parallelism").setDefault(1).help("Parallelism for program").type(Integer.class); ap.addArgument("-e", "--extension").setDefault(".csv").help("File extension for generated files"); ap.addArgument("-o", "--outpath").setDefault("/tmp/").help("Output directory"); Namespace ns = null; try { ns = ap.parseArgs(args); } catch (ArgumentParserException e) { ap.handleError(e); System.exit(1); } final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(ns.getInt("parallelism")); DistributedTPCH gen = new DistributedTPCH(env); gen.setScale(ns.getDouble("scale")); String base = ns.getString("outpath"); String ext = ns.getString("extension");
gen.generateParts().writeAsFormattedText(base + "parts" + ext, new TpchEntityFormatter());
project-flink/flink-perf
flink-jobs/src/main/parking/tpch/generators/programs/TPCHGeneratorExample.java
// Path: flink-jobs/src/main/parking/tpch/generators/core/DistributedTPCH.java // public class DistributedTPCH { // private double scale; // private ExecutionEnvironment env; // // // public DistributedTPCH(ExecutionEnvironment env) { // this.env = env; // } // // public void setScale(double scale) { // this.scale = scale; // } // // public double getScale() { // return scale; // } // // public DataSet<Part> generateParts() { // return getGenerator(PartGenerator.class, Part.class); // } // // public DataSet<LineItem> generateLineItems() { // return getGenerator(LineItemGenerator.class, LineItem.class); // } // public DataSet<Order> generateOrders() { // return getGenerator(OrderGenerator.class, Order.class); // } // // public DataSet<Supplier> generateSuppliers() { // return getGenerator(SupplierGenerator.class, Supplier.class); // } // // public DataSet<Region> generateRegions() { // return getGenerator(RegionGenerator.class, Region.class); // } // // public DataSet<Nation> generateNations() { // return getGenerator(NationGenerator.class, Nation.class); // } // // public DataSet<Customer> generateCustomers() { // return getGenerator(CustomerGenerator.class, Customer.class); // } // // public DataSet<PartSupplier> generatePartSuppliers() { // return getGenerator(PartSupplierGenerator.class, PartSupplier.class); // } // // public <T> DataSet<T> getGenerator(Class<? extends Iterable<T>> generatorClass, Class<T> type) { // SplittableIterator<T> si = new TPCHGeneratorSplittableIterator(scale, env.getParallelism(), generatorClass); // return env.fromParallelCollection(si, type).name("Generator: "+generatorClass); // } // }
import java.io.ObjectInputStream; import java.lang.reflect.Field; import com.github.projectflink.generators.tpch.generators.core.DistributedTPCH; import io.airlift.tpch.LineItem; import io.airlift.tpch.Order; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.typeutils.ResultTypeQueryable; import org.apache.flink.api.java.typeutils.TypeExtractor; import java.io.IOException;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.projectflink.generators.tpch.generators.programs; /** * TPC H Schema Diagramm: https://www.student.cs.uwaterloo.ca/~cs348/F14/TPC-H_Schema.png */ public class TPCHGeneratorExample { public static void main(String[] args) throws Exception { // set up the execution environment final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
// Path: flink-jobs/src/main/parking/tpch/generators/core/DistributedTPCH.java // public class DistributedTPCH { // private double scale; // private ExecutionEnvironment env; // // // public DistributedTPCH(ExecutionEnvironment env) { // this.env = env; // } // // public void setScale(double scale) { // this.scale = scale; // } // // public double getScale() { // return scale; // } // // public DataSet<Part> generateParts() { // return getGenerator(PartGenerator.class, Part.class); // } // // public DataSet<LineItem> generateLineItems() { // return getGenerator(LineItemGenerator.class, LineItem.class); // } // public DataSet<Order> generateOrders() { // return getGenerator(OrderGenerator.class, Order.class); // } // // public DataSet<Supplier> generateSuppliers() { // return getGenerator(SupplierGenerator.class, Supplier.class); // } // // public DataSet<Region> generateRegions() { // return getGenerator(RegionGenerator.class, Region.class); // } // // public DataSet<Nation> generateNations() { // return getGenerator(NationGenerator.class, Nation.class); // } // // public DataSet<Customer> generateCustomers() { // return getGenerator(CustomerGenerator.class, Customer.class); // } // // public DataSet<PartSupplier> generatePartSuppliers() { // return getGenerator(PartSupplierGenerator.class, PartSupplier.class); // } // // public <T> DataSet<T> getGenerator(Class<? extends Iterable<T>> generatorClass, Class<T> type) { // SplittableIterator<T> si = new TPCHGeneratorSplittableIterator(scale, env.getParallelism(), generatorClass); // return env.fromParallelCollection(si, type).name("Generator: "+generatorClass); // } // } // Path: flink-jobs/src/main/parking/tpch/generators/programs/TPCHGeneratorExample.java import java.io.ObjectInputStream; import java.lang.reflect.Field; import com.github.projectflink.generators.tpch.generators.core.DistributedTPCH; import io.airlift.tpch.LineItem; import io.airlift.tpch.Order; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.typeutils.ResultTypeQueryable; import org.apache.flink.api.java.typeutils.TypeExtractor; import java.io.IOException; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.projectflink.generators.tpch.generators.programs; /** * TPC H Schema Diagramm: https://www.student.cs.uwaterloo.ca/~cs348/F14/TPC-H_Schema.png */ public class TPCHGeneratorExample { public static void main(String[] args) throws Exception { // set up the execution environment final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DistributedTPCH gen = new DistributedTPCH(env);
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/loader/PluginWrapper.java
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // }
import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.*; import java.io.File;
package src.john01dav.serverforge.loader; public class PluginWrapper { private ServerForgePlugin serverForgeMod; private String name; private File pluginFolder; public PluginWrapper(ServerForgePlugin serverForgeMod, String name){ this.serverForgeMod = serverForgeMod; serverForgeMod.wrapper = this; this.name = name; //make sure that the plugins folder exists as a folder
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // Path: src/main/java/src/john01dav/serverforge/loader/PluginWrapper.java import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.*; import java.io.File; package src.john01dav.serverforge.loader; public class PluginWrapper { private ServerForgePlugin serverForgeMod; private String name; private File pluginFolder; public PluginWrapper(ServerForgePlugin serverForgeMod, String name){ this.serverForgeMod = serverForgeMod; serverForgeMod.wrapper = this; this.name = name; //make sure that the plugins folder exists as a folder
pluginFolder = new File(ServerForge.instance.getPluginLoader().getPluginsFolder(), name);
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/permissions/PermissionsManager.java
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // }
import net.minecraft.entity.player.EntityPlayerMP; import src.john01dav.serverforge.api.Player; import java.util.ArrayList;
package src.john01dav.serverforge.permissions; public class PermissionsManager{ private ArrayList<PermissionsHandler> handlerIndex; public void onServerStart(){ handlerIndex = new ArrayList<PermissionsHandler>(); } /** * Registers the specified permissionhandler in the system * @param permissionsHandler The permissionhandler to be registered */ public void registerPermissionsHandler(PermissionsHandler permissionsHandler){ handlerIndex.add(permissionsHandler); } //using entityplayermp to encourage use of the method in the src.john01dav.serverforge.api.Player class public boolean getPermission(EntityPlayerMP playerMP, String permission){
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // } // Path: src/main/java/src/john01dav/serverforge/permissions/PermissionsManager.java import net.minecraft.entity.player.EntityPlayerMP; import src.john01dav.serverforge.api.Player; import java.util.ArrayList; package src.john01dav.serverforge.permissions; public class PermissionsManager{ private ArrayList<PermissionsHandler> handlerIndex; public void onServerStart(){ handlerIndex = new ArrayList<PermissionsHandler>(); } /** * Registers the specified permissionhandler in the system * @param permissionsHandler The permissionhandler to be registered */ public void registerPermissionsHandler(PermissionsHandler permissionsHandler){ handlerIndex.add(permissionsHandler); } //using entityplayermp to encourage use of the method in the src.john01dav.serverforge.api.Player class public boolean getPermission(EntityPlayerMP playerMP, String permission){
Player player = Player.get(playerMP);
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/loader/PluginLoader.java
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgePlugin.java // public abstract class ServerForgePlugin{ // public PluginWrapper wrapper; // // /** // * Called when the server loads // */ // public abstract void onServerStart(); // // /** // * Called when the server unloads // */ // public abstract void onServerStop(); // // } // // Path: src/main/java/src/john01dav/serverforge/plugin/ServerForgeDefaultPlugin.java // public class ServerForgeDefaultPlugin extends ServerForgePlugin{ // private PropertiesFile propertiesFile; // // @Override // public void onServerStart(){ // try { // Properties defaultProperties = new Properties(); // defaultProperties.setProperty("enableVersion", String.valueOf(true)); // defaultProperties.setProperty("enablePlugins", String.valueOf(true)); // // propertiesFile = new PropertiesFile(wrapper, "serverforgeplugin.properties", defaultProperties); // // if((Boolean.parseBoolean(propertiesFile.getProperties().getProperty("enableVersion")))){ // ServerForge.instance.registerCommand("version", new VersionCommand()); // } // // if((Boolean.parseBoolean(propertiesFile.getProperties().getProperty("enablePlugins")))){ // ServerForge.instance.registerCommand("plugins", new PluginsCommand()); // } // }catch(IOException e){ // e.printStackTrace(); // } // } // // @Override // public void onServerStop(){ // // } // // }
import com.google.common.io.Files; import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.ServerForgePlugin; import src.john01dav.serverforge.plugin.ServerForgeDefaultPlugin; import java.io.File; import java.io.IOException; import java.net.*; import java.util.ArrayList;
package src.john01dav.serverforge.loader; public class PluginLoader{ private ArrayList<PluginFile> pluginFile; private ArrayList<PluginWrapper> pluginWrapper; private URLClassLoader loader; private File pluginsFolder; public void onServerStart(){ pluginsFolder = new File("./plugins"); try { if (!pluginsFolder.isDirectory()) { Files.move(pluginsFolder, new File("./plugins-file")); pluginsFolder.delete(); } if (!pluginsFolder.exists()) { pluginsFolder.mkdir(); } }catch(IOException e){ e.printStackTrace(); System.exit(0); } pluginFile = new ArrayList<PluginFile>(); pluginWrapper = new ArrayList<PluginWrapper>(); ArrayList<URL> pluginURL = new ArrayList<URL>();
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgePlugin.java // public abstract class ServerForgePlugin{ // public PluginWrapper wrapper; // // /** // * Called when the server loads // */ // public abstract void onServerStart(); // // /** // * Called when the server unloads // */ // public abstract void onServerStop(); // // } // // Path: src/main/java/src/john01dav/serverforge/plugin/ServerForgeDefaultPlugin.java // public class ServerForgeDefaultPlugin extends ServerForgePlugin{ // private PropertiesFile propertiesFile; // // @Override // public void onServerStart(){ // try { // Properties defaultProperties = new Properties(); // defaultProperties.setProperty("enableVersion", String.valueOf(true)); // defaultProperties.setProperty("enablePlugins", String.valueOf(true)); // // propertiesFile = new PropertiesFile(wrapper, "serverforgeplugin.properties", defaultProperties); // // if((Boolean.parseBoolean(propertiesFile.getProperties().getProperty("enableVersion")))){ // ServerForge.instance.registerCommand("version", new VersionCommand()); // } // // if((Boolean.parseBoolean(propertiesFile.getProperties().getProperty("enablePlugins")))){ // ServerForge.instance.registerCommand("plugins", new PluginsCommand()); // } // }catch(IOException e){ // e.printStackTrace(); // } // } // // @Override // public void onServerStop(){ // // } // // } // Path: src/main/java/src/john01dav/serverforge/loader/PluginLoader.java import com.google.common.io.Files; import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.ServerForgePlugin; import src.john01dav.serverforge.plugin.ServerForgeDefaultPlugin; import java.io.File; import java.io.IOException; import java.net.*; import java.util.ArrayList; package src.john01dav.serverforge.loader; public class PluginLoader{ private ArrayList<PluginFile> pluginFile; private ArrayList<PluginWrapper> pluginWrapper; private URLClassLoader loader; private File pluginsFolder; public void onServerStart(){ pluginsFolder = new File("./plugins"); try { if (!pluginsFolder.isDirectory()) { Files.move(pluginsFolder, new File("./plugins-file")); pluginsFolder.delete(); } if (!pluginsFolder.exists()) { pluginsFolder.mkdir(); } }catch(IOException e){ e.printStackTrace(); System.exit(0); } pluginFile = new ArrayList<PluginFile>(); pluginWrapper = new ArrayList<PluginWrapper>(); ArrayList<URL> pluginURL = new ArrayList<URL>();
ServerForge.info("Loading plugins...");
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/events/EventListenerWrapper.java
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // }
import src.john01dav.serverforge.ServerForge; import java.lang.reflect.Method;
package src.john01dav.serverforge.events; public class EventListenerWrapper{ private EventListener listener; protected EventListenerWrapper(EventListener listener){ this.listener = listener; } protected void callEvent(Object event){ for(Method method : listener.getClass().getMethods()){ try { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { Class<?> parameter = parameterTypes[0]; if (parameter.getCanonicalName().equalsIgnoreCase(event.getClass().getCanonicalName())) { method.setAccessible(true); method.invoke(listener, new Object[]{event}); } } }catch(Exception e){
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // Path: src/main/java/src/john01dav/serverforge/events/EventListenerWrapper.java import src.john01dav.serverforge.ServerForge; import java.lang.reflect.Method; package src.john01dav.serverforge.events; public class EventListenerWrapper{ private EventListener listener; protected EventListenerWrapper(EventListener listener){ this.listener = listener; } protected void callEvent(Object event){ for(Method method : listener.getClass().getMethods()){ try { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { Class<?> parameter = parameterTypes[0]; if (parameter.getCanonicalName().equalsIgnoreCase(event.getClass().getCanonicalName())) { method.setAccessible(true); method.invoke(listener, new Object[]{event}); } } }catch(Exception e){
ServerForge.instance.error("Failed to invote listener: " + e.getMessage());
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/events/EventManager.java
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // }
import net.minecraftforge.common.MinecraftForge; import src.john01dav.serverforge.ServerForge; import java.util.ArrayList;
package src.john01dav.serverforge.events; public class EventManager{ private ArrayList<EventListenerWrapper> listeners; public void onServerStart(){
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // Path: src/main/java/src/john01dav/serverforge/events/EventManager.java import net.minecraftforge.common.MinecraftForge; import src.john01dav.serverforge.ServerForge; import java.util.ArrayList; package src.john01dav.serverforge.events; public class EventManager{ private ArrayList<EventListenerWrapper> listeners; public void onServerStart(){
ServerForge.info("Starting events");
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/plugin/PluginsCommand.java
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // // Path: src/main/java/src/john01dav/serverforge/loader/PluginWrapper.java // public class PluginWrapper { // private ServerForgePlugin serverForgeMod; // private String name; // private File pluginFolder; // // public PluginWrapper(ServerForgePlugin serverForgeMod, String name){ // this.serverForgeMod = serverForgeMod; // serverForgeMod.wrapper = this; // this.name = name; // // //make sure that the plugins folder exists as a folder // pluginFolder = new File(ServerForge.instance.getPluginLoader().getPluginsFolder(), name); // // if(!pluginFolder.exists()){ // pluginFolder.mkdir(); // } // } // // public ServerForgePlugin getPlugin(){ // return serverForgeMod; // } // public String getName(){ // return name; // } // // public File getPluginFolder(){ // return pluginFolder; // } // // }
import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.loader.PluginWrapper; import java.util.ArrayList;
package src.john01dav.serverforge.plugin; public class PluginsCommand implements ServerForgeCommand{ @Override
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // // Path: src/main/java/src/john01dav/serverforge/loader/PluginWrapper.java // public class PluginWrapper { // private ServerForgePlugin serverForgeMod; // private String name; // private File pluginFolder; // // public PluginWrapper(ServerForgePlugin serverForgeMod, String name){ // this.serverForgeMod = serverForgeMod; // serverForgeMod.wrapper = this; // this.name = name; // // //make sure that the plugins folder exists as a folder // pluginFolder = new File(ServerForge.instance.getPluginLoader().getPluginsFolder(), name); // // if(!pluginFolder.exists()){ // pluginFolder.mkdir(); // } // } // // public ServerForgePlugin getPlugin(){ // return serverForgeMod; // } // public String getName(){ // return name; // } // // public File getPluginFolder(){ // return pluginFolder; // } // // } // Path: src/main/java/src/john01dav/serverforge/plugin/PluginsCommand.java import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.loader.PluginWrapper; import java.util.ArrayList; package src.john01dav.serverforge.plugin; public class PluginsCommand implements ServerForgeCommand{ @Override
public void onCommand(CommandSender sender, String[] args){
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/api/events/CommandSendEvent.java
// Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/NativeCommandWrapper.java // public class NativeCommandWrapper implements ServerForgeCommand{ // private ICommand command; // // public NativeCommandWrapper(ICommand command){ // this.command = command; // } // // @Override // public void onCommand(CommandSender sender, String[] args){ // command.processCommand(sender.forgeSender, args); // } // // public String getName(){ // return command.getCommandName(); // } // // public String getUsage(CommandSender sender){ // return command.getCommandUsage(sender.forgeSender); // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // }
import net.minecraftforge.event.CommandEvent; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.NativeCommandWrapper; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.events.CancellableEvent;
package src.john01dav.serverforge.api.events; public class CommandSendEvent implements CancellableEvent{ private CommandEvent commandEvent; private boolean cancelled = false; public CommandSendEvent(CommandEvent commandEvent){ this.commandEvent = commandEvent; setCancelled(commandEvent.isCanceled()); } /** * Returns the sender of this command * @return The sender of this command */
// Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/NativeCommandWrapper.java // public class NativeCommandWrapper implements ServerForgeCommand{ // private ICommand command; // // public NativeCommandWrapper(ICommand command){ // this.command = command; // } // // @Override // public void onCommand(CommandSender sender, String[] args){ // command.processCommand(sender.forgeSender, args); // } // // public String getName(){ // return command.getCommandName(); // } // // public String getUsage(CommandSender sender){ // return command.getCommandUsage(sender.forgeSender); // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // } // Path: src/main/java/src/john01dav/serverforge/api/events/CommandSendEvent.java import net.minecraftforge.event.CommandEvent; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.NativeCommandWrapper; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.events.CancellableEvent; package src.john01dav.serverforge.api.events; public class CommandSendEvent implements CancellableEvent{ private CommandEvent commandEvent; private boolean cancelled = false; public CommandSendEvent(CommandEvent commandEvent){ this.commandEvent = commandEvent; setCancelled(commandEvent.isCanceled()); } /** * Returns the sender of this command * @return The sender of this command */
public CommandSender getCommandSender(){
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/api/events/CommandSendEvent.java
// Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/NativeCommandWrapper.java // public class NativeCommandWrapper implements ServerForgeCommand{ // private ICommand command; // // public NativeCommandWrapper(ICommand command){ // this.command = command; // } // // @Override // public void onCommand(CommandSender sender, String[] args){ // command.processCommand(sender.forgeSender, args); // } // // public String getName(){ // return command.getCommandName(); // } // // public String getUsage(CommandSender sender){ // return command.getCommandUsage(sender.forgeSender); // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // }
import net.minecraftforge.event.CommandEvent; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.NativeCommandWrapper; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.events.CancellableEvent;
package src.john01dav.serverforge.api.events; public class CommandSendEvent implements CancellableEvent{ private CommandEvent commandEvent; private boolean cancelled = false; public CommandSendEvent(CommandEvent commandEvent){ this.commandEvent = commandEvent; setCancelled(commandEvent.isCanceled()); } /** * Returns the sender of this command * @return The sender of this command */ public CommandSender getCommandSender(){ return new CommandSender(commandEvent.sender); } /** * Returns the arguments of this command * @return The arguments of this command */ public String[] getArgs(){ return commandEvent.parameters; } /** * Returns the object representing this command * @return The object representing this command */
// Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/NativeCommandWrapper.java // public class NativeCommandWrapper implements ServerForgeCommand{ // private ICommand command; // // public NativeCommandWrapper(ICommand command){ // this.command = command; // } // // @Override // public void onCommand(CommandSender sender, String[] args){ // command.processCommand(sender.forgeSender, args); // } // // public String getName(){ // return command.getCommandName(); // } // // public String getUsage(CommandSender sender){ // return command.getCommandUsage(sender.forgeSender); // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // } // Path: src/main/java/src/john01dav/serverforge/api/events/CommandSendEvent.java import net.minecraftforge.event.CommandEvent; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.NativeCommandWrapper; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.events.CancellableEvent; package src.john01dav.serverforge.api.events; public class CommandSendEvent implements CancellableEvent{ private CommandEvent commandEvent; private boolean cancelled = false; public CommandSendEvent(CommandEvent commandEvent){ this.commandEvent = commandEvent; setCancelled(commandEvent.isCanceled()); } /** * Returns the sender of this command * @return The sender of this command */ public CommandSender getCommandSender(){ return new CommandSender(commandEvent.sender); } /** * Returns the arguments of this command * @return The arguments of this command */ public String[] getArgs(){ return commandEvent.parameters; } /** * Returns the object representing this command * @return The object representing this command */
public ServerForgeCommand getCommand(){
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/api/events/CommandSendEvent.java
// Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/NativeCommandWrapper.java // public class NativeCommandWrapper implements ServerForgeCommand{ // private ICommand command; // // public NativeCommandWrapper(ICommand command){ // this.command = command; // } // // @Override // public void onCommand(CommandSender sender, String[] args){ // command.processCommand(sender.forgeSender, args); // } // // public String getName(){ // return command.getCommandName(); // } // // public String getUsage(CommandSender sender){ // return command.getCommandUsage(sender.forgeSender); // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // }
import net.minecraftforge.event.CommandEvent; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.NativeCommandWrapper; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.events.CancellableEvent;
package src.john01dav.serverforge.api.events; public class CommandSendEvent implements CancellableEvent{ private CommandEvent commandEvent; private boolean cancelled = false; public CommandSendEvent(CommandEvent commandEvent){ this.commandEvent = commandEvent; setCancelled(commandEvent.isCanceled()); } /** * Returns the sender of this command * @return The sender of this command */ public CommandSender getCommandSender(){ return new CommandSender(commandEvent.sender); } /** * Returns the arguments of this command * @return The arguments of this command */ public String[] getArgs(){ return commandEvent.parameters; } /** * Returns the object representing this command * @return The object representing this command */ public ServerForgeCommand getCommand(){
// Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/NativeCommandWrapper.java // public class NativeCommandWrapper implements ServerForgeCommand{ // private ICommand command; // // public NativeCommandWrapper(ICommand command){ // this.command = command; // } // // @Override // public void onCommand(CommandSender sender, String[] args){ // command.processCommand(sender.forgeSender, args); // } // // public String getName(){ // return command.getCommandName(); // } // // public String getUsage(CommandSender sender){ // return command.getCommandUsage(sender.forgeSender); // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // } // Path: src/main/java/src/john01dav/serverforge/api/events/CommandSendEvent.java import net.minecraftforge.event.CommandEvent; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.NativeCommandWrapper; import src.john01dav.serverforge.api.ServerForgeCommand; import src.john01dav.serverforge.events.CancellableEvent; package src.john01dav.serverforge.api.events; public class CommandSendEvent implements CancellableEvent{ private CommandEvent commandEvent; private boolean cancelled = false; public CommandSendEvent(CommandEvent commandEvent){ this.commandEvent = commandEvent; setCancelled(commandEvent.isCanceled()); } /** * Returns the sender of this command * @return The sender of this command */ public CommandSender getCommandSender(){ return new CommandSender(commandEvent.sender); } /** * Returns the arguments of this command * @return The arguments of this command */ public String[] getArgs(){ return commandEvent.parameters; } /** * Returns the object representing this command * @return The object representing this command */ public ServerForgeCommand getCommand(){
return new NativeCommandWrapper(commandEvent.command);
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/api/events/PlayerDeathEvent.java
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // }
import net.minecraftforge.event.entity.player.PlayerDropsEvent; import src.john01dav.serverforge.api.Player;
package src.john01dav.serverforge.api.events; public class PlayerDeathEvent { private PlayerDropsEvent playerDropsEvent; private boolean cancelled = false; public PlayerDeathEvent(PlayerDropsEvent playerDropsEvent){ this.playerDropsEvent = playerDropsEvent; setCancelled(playerDropsEvent.isCanceled()); } /** * Returns the player associated with this event * @return the player associated with this event */
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // } // Path: src/main/java/src/john01dav/serverforge/api/events/PlayerDeathEvent.java import net.minecraftforge.event.entity.player.PlayerDropsEvent; import src.john01dav.serverforge.api.Player; package src.john01dav.serverforge.api.events; public class PlayerDeathEvent { private PlayerDropsEvent playerDropsEvent; private boolean cancelled = false; public PlayerDeathEvent(PlayerDropsEvent playerDropsEvent){ this.playerDropsEvent = playerDropsEvent; setCancelled(playerDropsEvent.isCanceled()); } /** * Returns the player associated with this event * @return the player associated with this event */
public Player getPlayer(){
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/plugin/VersionCommand.java
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // }
import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.ServerForgeCommand;
package src.john01dav.serverforge.plugin; public class VersionCommand implements ServerForgeCommand{ @Override
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // Path: src/main/java/src/john01dav/serverforge/plugin/VersionCommand.java import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.ServerForgeCommand; package src.john01dav.serverforge.plugin; public class VersionCommand implements ServerForgeCommand{ @Override
public void onCommand(CommandSender sender, String[] args) {
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/plugin/VersionCommand.java
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // }
import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.ServerForgeCommand;
package src.john01dav.serverforge.plugin; public class VersionCommand implements ServerForgeCommand{ @Override public void onCommand(CommandSender sender, String[] args) {
// Path: src/main/java/src/john01dav/serverforge/ServerForge.java // @Mod(modid = "ServerForge", name = "ServerForge", version = ServerForge.VERSION, acceptableRemoteVersions = "*") // public class ServerForge{ // public static final String VERSION = "PRE-ALPHA 0.0.1"; // // private EventManager eventManager; // private PermissionsManager permissionsManager; // private PluginLoader pluginLoader; // // private FMLServerStartingEvent serverStartingEvent; // // @Mod.Instance("ServerForge") // public static ServerForge instance; // // public static void info(String info){ // System.out.println("[SERVERFORGE INFO]: " + info); // } // // public static void error(String error){ // System.out.println("[SERVERFORGE ERROR]: " + error); // } // // @Mod.EventHandler // public void serverStartingEvent(FMLServerStartingEvent e){ // info("Starting ServerForge..."); // this.serverStartingEvent = e; // // eventManager = new EventManager(); // eventManager.onServerStart(); // // permissionsManager = new PermissionsManager(); // permissionsManager.onServerStart(); // // pluginLoader = new PluginLoader(); // pluginLoader.onServerStart(); // // this.serverStartingEvent = null; // info("ServerForge started"); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // * @param aliases Array containing the aliases for this command // */ // public void registerCommand(String name, ServerForgeCommand command, String[] aliases){ // CommandWrapper wrapper = new CommandWrapper(name, command, aliases); // serverStartingEvent.registerServerCommand(wrapper); // } // // /** // * Registers a command for use in the server, can only be called from onServerStart() or it's submethods // * @param name The name of the command to add, to be used as the name to execute (ie. name = "example", to type in chat = "/example") // * @param command The command object to register // */ // public void registerCommand(String name, ServerForgeCommand command){ // registerCommand(name, command, new String[0]); // } // // /** // * Returns the plugin loader (the class responsible for the loading and management of plugins) // * @return the plugin loader // */ // public PluginLoader getPluginLoader(){ // return pluginLoader; // } // // /** // * Returns the event manager (the class responsible for the registering and calling of events) // * @return The event manager // */ // public EventManager getEventManager(){ // return eventManager; // } // // /** // * Returns the permissions manager (the class responsible for the setting and getting of player's permissions) // * @return the permissions manager // */ // public PermissionsManager getPermissionsManager(){ // return permissionsManager; // } // // /** // * Returns the Minecraft version running this server // * @return The Minecraft version running this server // */ // public String getMinecraftVersion(){ // return MinecraftForge.MC_VERSION; // } // // /** // * Returns all online players // * @return All online players // */ // public ArrayList<Player> getOnlinePlayers(){ // ArrayList<Player> list = new ArrayList<Player>(); // // for(World world : MinecraftServer.getServer().worldServers){ // for(Object o : world.playerEntities){ // EntityPlayerMP playerMP = ((EntityPlayerMP) o); // Player player = Player.get(playerMP); // list.add(player); // } // } // // return list; // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/CommandSender.java // public class CommandSender { // protected ICommandSender forgeSender; // // public CommandSender(ICommandSender forgeSender){ // this.forgeSender = forgeSender; // } // // /** // * Sends a message to this commandsender // * @param message The message to send // */ // public void sendMessage(String message){ // forgeSender.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the name of the commandsender, "RCon" for a console // * @return The name of this commandsender // */ // public String getName(){ // return forgeSender.getCommandSenderName(); // } // // /** // * Returns the player that sent this command, or null if it was not a player // * @return The player who sent this command // */ // public Player getPlayer(){ // if(forgeSender instanceof EntityPlayer){ // EntityPlayer entity = ((EntityPlayer) forgeSender); // return Player.get(entity); // }else{ // return null; // } // } // // } // // Path: src/main/java/src/john01dav/serverforge/api/ServerForgeCommand.java // public interface ServerForgeCommand { // // /** // * Called when a command is executed // * @param sender An object representing the player, console, or command block that sent the command // * @param args The arguments of the command // */ // public void onCommand(CommandSender sender, String[] args); // // } // Path: src/main/java/src/john01dav/serverforge/plugin/VersionCommand.java import src.john01dav.serverforge.ServerForge; import src.john01dav.serverforge.api.CommandSender; import src.john01dav.serverforge.api.ServerForgeCommand; package src.john01dav.serverforge.plugin; public class VersionCommand implements ServerForgeCommand{ @Override public void onCommand(CommandSender sender, String[] args) {
sender.sendMessage("This server is running ServerForge " + ServerForge.VERSION + " running on Minecraft " + ServerForge.instance.getMinecraftVersion());
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/api/events/JoinWorldEvent.java
// Path: src/main/java/src/john01dav/serverforge/api/entity/EntityBase.java // public class EntityBase{ // private Entity entity; // // public EntityBase(Entity entity){ // this.entity = entity; // } // // /** // * Returns the player behind this entity, or null if this entity is not a player // * @return The player behind this entity // */ // public Player getPlayer(){ // if(entity instanceof EntityPlayer){ // EntityPlayer player = ((EntityPlayer) entity); // return Player.get(player); // }else{ // return null; // } // } // // }
import net.minecraftforge.event.entity.EntityJoinWorldEvent; import src.john01dav.serverforge.api.entity.EntityBase;
package src.john01dav.serverforge.api.events; public class JoinWorldEvent { private EntityJoinWorldEvent entityJoinWorldEvent; public JoinWorldEvent(EntityJoinWorldEvent entityJoinWorldEvent){ this.entityJoinWorldEvent = entityJoinWorldEvent; } /** * Returns the entity whom is joining the world * @return The entity whom is joining the world */
// Path: src/main/java/src/john01dav/serverforge/api/entity/EntityBase.java // public class EntityBase{ // private Entity entity; // // public EntityBase(Entity entity){ // this.entity = entity; // } // // /** // * Returns the player behind this entity, or null if this entity is not a player // * @return The player behind this entity // */ // public Player getPlayer(){ // if(entity instanceof EntityPlayer){ // EntityPlayer player = ((EntityPlayer) entity); // return Player.get(player); // }else{ // return null; // } // } // // } // Path: src/main/java/src/john01dav/serverforge/api/events/JoinWorldEvent.java import net.minecraftforge.event.entity.EntityJoinWorldEvent; import src.john01dav.serverforge.api.entity.EntityBase; package src.john01dav.serverforge.api.events; public class JoinWorldEvent { private EntityJoinWorldEvent entityJoinWorldEvent; public JoinWorldEvent(EntityJoinWorldEvent entityJoinWorldEvent){ this.entityJoinWorldEvent = entityJoinWorldEvent; } /** * Returns the entity whom is joining the world * @return The entity whom is joining the world */
public EntityBase getEntity(){
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/api/events/InteractEvent.java
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // }
import cpw.mods.fml.common.eventhandler.Event; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import src.john01dav.serverforge.api.Player; import src.john01dav.serverforge.events.CancellableEvent;
package src.john01dav.serverforge.api.events; public class InteractEvent implements CancellableEvent{ public static final int AIR_FACE = -1; public static final int TOP_FACE = 1; public static final int BOTTOM_FACE = 0; public static final int SIDE1_FACE = 2; public static final int SIDE2_FACE = 3; public static final int SIDE3_FACE = 4; public static final int SIDE4_FACE = 5; public static final int RIGHT_CLICK_BLOCK = 6; public static final int RIGHT_CLICK_AIR = 6; public static final int LEFT_CLICK_BLOCK = 6; private PlayerInteractEvent playerInteractEvent;
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // } // Path: src/main/java/src/john01dav/serverforge/api/events/InteractEvent.java import cpw.mods.fml.common.eventhandler.Event; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import src.john01dav.serverforge.api.Player; import src.john01dav.serverforge.events.CancellableEvent; package src.john01dav.serverforge.api.events; public class InteractEvent implements CancellableEvent{ public static final int AIR_FACE = -1; public static final int TOP_FACE = 1; public static final int BOTTOM_FACE = 0; public static final int SIDE1_FACE = 2; public static final int SIDE2_FACE = 3; public static final int SIDE3_FACE = 4; public static final int SIDE4_FACE = 5; public static final int RIGHT_CLICK_BLOCK = 6; public static final int RIGHT_CLICK_AIR = 6; public static final int LEFT_CLICK_BLOCK = 6; private PlayerInteractEvent playerInteractEvent;
private Player player;
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/api/events/BlockBreakEvent.java
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // }
import net.minecraftforge.event.world.BlockEvent; import src.john01dav.serverforge.api.Player; import src.john01dav.serverforge.events.CancellableEvent;
package src.john01dav.serverforge.api.events; public class BlockBreakEvent implements CancellableEvent{ private boolean cancelled = false; private BlockEvent.BreakEvent breakEvent;
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // } // Path: src/main/java/src/john01dav/serverforge/api/events/BlockBreakEvent.java import net.minecraftforge.event.world.BlockEvent; import src.john01dav.serverforge.api.Player; import src.john01dav.serverforge.events.CancellableEvent; package src.john01dav.serverforge.api.events; public class BlockBreakEvent implements CancellableEvent{ private boolean cancelled = false; private BlockEvent.BreakEvent breakEvent;
private Player player;
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/api/entity/EntityBase.java
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // }
import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import src.john01dav.serverforge.api.Player;
package src.john01dav.serverforge.api.entity; public class EntityBase{ private Entity entity; public EntityBase(Entity entity){ this.entity = entity; } /** * Returns the player behind this entity, or null if this entity is not a player * @return The player behind this entity */
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // } // Path: src/main/java/src/john01dav/serverforge/api/entity/EntityBase.java import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import src.john01dav.serverforge.api.Player; package src.john01dav.serverforge.api.entity; public class EntityBase{ private Entity entity; public EntityBase(Entity entity){ this.entity = entity; } /** * Returns the player behind this entity, or null if this entity is not a player * @return The player behind this entity */
public Player getPlayer(){
john01dav/ServerForge
src/main/java/src/john01dav/serverforge/api/events/ChatEvent.java
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // }
import net.minecraftforge.event.ServerChatEvent; import src.john01dav.serverforge.api.Player; import src.john01dav.serverforge.events.CancellableEvent;
package src.john01dav.serverforge.api.events; public class ChatEvent implements CancellableEvent{ private ServerChatEvent serverChatEvent; private boolean cancelled = false; private String chatFormat = "%player%: %message%"; private String message;
// Path: src/main/java/src/john01dav/serverforge/api/Player.java // public class Player{ // private static HashMap<UUID, Player> playerEntities = new HashMap<UUID, Player>(); // private EntityPlayer entityPlayer; // private InventoryBase inventory; // // public enum GameMode{ // SURVIVAL, // CREATIVE, // ADVENTURE // } // // private Player(EntityPlayer entityPlayer){ // this.entityPlayer = entityPlayer; // inventory = new InventoryBase(this.entityPlayer.inventory); // } // // public static Player get(EntityPlayer player){ // Player c = playerEntities.get(player.getUniqueID()); // if(c == null){ // Player np = new Player(player); // playerEntities.put(player.getUniqueID(), np); // return np; // }else{ // return c; // } // } // // /** // * Returns the name of this player // * @return The name of this player // */ // public String getName(){ // return entityPlayer.getCommandSenderName(); // } // // /** // * Returns the Mojang Specified UUID of this player, or a hash of their name if the server is in offline mode // * @return The player's UUID // */ // public UUID getUUID(){ // return entityPlayer.getUniqueID(); // } // // /** // * Teleports the player to the specified location // * @param x The x coordinate of the location to teleport the player to // * @param y The y coordinate of the location to teleport the player to // * @param z The z coordinate of the location to teleport the player to // */ // public void teleport(double x, double y, double z){ // entityPlayer.setPosition(x, y, z); // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(x, y, z, mpPlayer.cameraYaw, mpPlayer.cameraPitch); // } // // /** // * Sets the yaw and pitch of the player's camera // * @param yaw The yaw to set for this player // * @param pitch The pitch to set for this player // */ // public void setCameraAngles(float yaw, float pitch){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // mpPlayer.playerNetServerHandler.setPlayerLocation(mpPlayer.posX, mpPlayer.posY, mpPlayer.posZ, yaw, pitch); // } // // /** // * Sends the message passed into this method to the player's chat box // * @param message The message to send to the player // */ // public void sendMessage(String message){ // entityPlayer.addChatMessage(new ChatComponentText(message)); // } // // /** // * Returns the value for the permission of this player // * @param permission the permission to lookup // * @return the value of the permission // */ // public boolean getPermission(String permission) { // return ServerForge.instance.getPermissionsManager().getPermission(((EntityPlayerMP) entityPlayer), permission); // } // // public InventoryBase getInventory(){ // return inventory; // } // // /** // * Sets this player's current gamemode // * @param mode the new gamemode // */ // public void setGameMode(GameMode mode){ // EntityPlayerMP mpPlayer = ((EntityPlayerMP) entityPlayer); // switch(mode){ // case SURVIVAL: // mpPlayer.setGameType(WorldSettings.GameType.SURVIVAL); // break; // case CREATIVE: // mpPlayer.setGameType(WorldSettings.GameType.CREATIVE); // break; // case ADVENTURE: // mpPlayer.setGameType(WorldSettings.GameType.ADVENTURE); // break; // } // } // // /** // * Returns this player's current world // * @return This player's current world // */ // public ServerForgeWorld getWorld(){ // return ServerForgeWorld.get(entityPlayer.dimension); // } // // /** // * Returns the current X coordinate of this player // * @return The current X coordinate of this player // */ // public double getX(){ // return entityPlayer.getPlayerCoordinates().posX; // } // // /** // * Returns the current Y coordinate of this player // * @return The current Y coordinate of this player // */ // public double getY(){ // return entityPlayer.getPlayerCoordinates().posY; // } // // /** // * Returns the current Z coordinate of this player // * @return The current Z coordinate of this player // */ // public double getZ(){ // return entityPlayer.getPlayerCoordinates().posZ; // } // // } // // Path: src/main/java/src/john01dav/serverforge/events/CancellableEvent.java // public interface CancellableEvent { // // public void setCancelled(boolean cancelled); // public boolean getCancelled(); // // } // Path: src/main/java/src/john01dav/serverforge/api/events/ChatEvent.java import net.minecraftforge.event.ServerChatEvent; import src.john01dav.serverforge.api.Player; import src.john01dav.serverforge.events.CancellableEvent; package src.john01dav.serverforge.api.events; public class ChatEvent implements CancellableEvent{ private ServerChatEvent serverChatEvent; private boolean cancelled = false; private String chatFormat = "%player%: %message%"; private String message;
private Player player;
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/activity/IntroActivity.java
// Path: app/src/main/java/hrv/band/app/ui/view/fragment/IntroFragment.java // public class IntroFragment extends Fragment { // // /** // * Key value for the tutorial title of this intro page (fragment). // **/ // private static final String INTRO_TITLE_ID = "intro_title_id"; // /** // * Key value for the tutorial description of this intro page (fragment). // **/ // private static final String INTRO_DESC_ID = "intro_desc_id"; // /** // * Key value for the tutorial image of this intro page (fragment). // **/ // private static final String INTRO_IMAGE_ID = "intro_image_id"; // // /** // * Returns a new instance of this fragment. // * // * @return a new instance of this fragment. // */ // public static IntroFragment newInstance(String title, String desc, int imageId) { // IntroFragment fragment = new IntroFragment(); // Bundle args = new Bundle(); // args.putString(INTRO_TITLE_ID, title); // args.putString(INTRO_DESC_ID, desc); // args.putInt(INTRO_IMAGE_ID, imageId); // fragment.setArguments(args); // return fragment; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View rootView = inflater.inflate(R.layout.intro_fragment, container, false); // // TextView title = rootView.findViewById(R.id.intro_title); // ImageView image = rootView.findViewById(R.id.intro_image); // TextView desc = rootView.findViewById(R.id.intro_desc); // // title.setText(getArguments().getString(INTRO_TITLE_ID)); // // BitmapFactory.Options o = new BitmapFactory.Options(); // o.inSampleSize = 2; // // Bitmap img = BitmapFactory.decodeResource(getResources(), getArguments().getInt(INTRO_IMAGE_ID), o); // image.setImageBitmap(img); // // desc.setText(getArguments().getString(INTRO_DESC_ID)); // // return rootView; // } // }
import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import com.github.paolorotolo.appintro.AppIntro; import hrv.band.app.R; import hrv.band.app.ui.view.fragment.IntroFragment; import hrv.band.app.ui.view.fragment.SampleDataFragment; import hrv.band.app.ui.view.fragment.TextDialogFragment;
package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 19.01.2017 * <p> * This Activity shows a tutorial to the user. */ public class IntroActivity extends AppIntro { /** * Key value for tutorial if it should start at app start. **/ public static final String APP_INTRO = "app_intro"; /** * Sets the APP_INTRO preference. * * @param context of this activity. */ private static void setPreference(Context context) { SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor prefsEditor = mPrefs.edit(); prefsEditor.putBoolean(APP_INTRO, true); prefsEditor.apply(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Resources resources = getResources();
// Path: app/src/main/java/hrv/band/app/ui/view/fragment/IntroFragment.java // public class IntroFragment extends Fragment { // // /** // * Key value for the tutorial title of this intro page (fragment). // **/ // private static final String INTRO_TITLE_ID = "intro_title_id"; // /** // * Key value for the tutorial description of this intro page (fragment). // **/ // private static final String INTRO_DESC_ID = "intro_desc_id"; // /** // * Key value for the tutorial image of this intro page (fragment). // **/ // private static final String INTRO_IMAGE_ID = "intro_image_id"; // // /** // * Returns a new instance of this fragment. // * // * @return a new instance of this fragment. // */ // public static IntroFragment newInstance(String title, String desc, int imageId) { // IntroFragment fragment = new IntroFragment(); // Bundle args = new Bundle(); // args.putString(INTRO_TITLE_ID, title); // args.putString(INTRO_DESC_ID, desc); // args.putInt(INTRO_IMAGE_ID, imageId); // fragment.setArguments(args); // return fragment; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // View rootView = inflater.inflate(R.layout.intro_fragment, container, false); // // TextView title = rootView.findViewById(R.id.intro_title); // ImageView image = rootView.findViewById(R.id.intro_image); // TextView desc = rootView.findViewById(R.id.intro_desc); // // title.setText(getArguments().getString(INTRO_TITLE_ID)); // // BitmapFactory.Options o = new BitmapFactory.Options(); // o.inSampleSize = 2; // // Bitmap img = BitmapFactory.decodeResource(getResources(), getArguments().getInt(INTRO_IMAGE_ID), o); // image.setImageBitmap(img); // // desc.setText(getArguments().getString(INTRO_DESC_ID)); // // return rootView; // } // } // Path: app/src/main/java/hrv/band/app/ui/view/activity/IntroActivity.java import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import com.github.paolorotolo.appintro.AppIntro; import hrv.band.app.R; import hrv.band.app.ui.view.fragment.IntroFragment; import hrv.band.app.ui.view.fragment.SampleDataFragment; import hrv.band.app.ui.view.fragment.TextDialogFragment; package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 19.01.2017 * <p> * This Activity shows a tutorial to the user. */ public class IntroActivity extends AppIntro { /** * Key value for tutorial if it should start at app start. **/ public static final String APP_INTRO = "app_intro"; /** * Sets the APP_INTRO preference. * * @param context of this activity. */ private static void setPreference(Context context) { SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor prefsEditor = mPrefs.edit(); prefsEditor.putBoolean(APP_INTRO, true); prefsEditor.apply(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Resources resources = getResources();
addSlide(IntroFragment.newInstance(resources.getString(R.string.tutorial_welcome_title), resources.getString(R.string.tutorial_welcome_desc), R.drawable.hrv_logo));
HRVBand/hrv-band
app/src/main/java/hrv/band/app/device/ConnectionManager.java
// Path: app/src/main/java/hrv/band/app/device/antplus/AntPlusRRDataDevice.java // public class AntPlusRRDataDevice // extends HRVRRIntervalDevice // implements AntPluginPcc.IDeviceStateChangeReceiver, // AntPluginPcc.IPluginAccessResultReceiver<AntPlusHeartRatePcc>, // AntPlusHeartRatePcc.ICalculatedRrIntervalReceiver { // // private final Activity activity; // private AntPlusHeartRatePcc wgtplc; // // public AntPlusRRDataDevice(Activity activity) { // this.activity = activity; // } // // @Override // public void onDeviceStateChange(DeviceState deviceState) { // if(deviceState == DeviceState.DEAD) // { // wgtplc = null; // } // } // // @Override // public void onResultReceived(AntPlusHeartRatePcc antPlusHeartRatePcc, RequestAccessResult requestAccessResult, DeviceState deviceState) { // // switch(requestAccessResult) { // case SUCCESS: // wgtplc = antPlusHeartRatePcc; // notifyDeviceStatusChanged(HRVDeviceStatus.CONNECTED); // break; // case USER_CANCELLED: // case SEARCH_TIMEOUT: // case OTHER_FAILURE: // notifyDeviceStatusChanged(HRVDeviceStatus.DISCONNECTED); // break; // default: // notifyDeviceStatusChanged(HRVDeviceStatus.DISCONNECTED); // } // } // // @Override // public void onNewCalculatedRrInterval(long l, EnumSet<EventFlag> enumSet, BigDecimal bigDecimal, AntPlusHeartRatePcc.RrFlag rrFlag) { // double rr = bigDecimal.longValue() / 1000.0; // this.rrMeasurements.add(rr); // notifyRRIntervalListeners(rr); // } // // // @Override // public void stopMeasuring() { // if(wgtplc != null) { // wgtplc.releaseAccess(); // notifyDeviceStatusChanged(HRVDeviceStatus.DISCONNECTED); // } // } // // @Override // public List<Double> getRRIntervals() { // return rrMeasurements; // } // // @Override // public void pauseMeasuring() { // stopMeasuring(); // } // // @Override // public void destroy() { // stopMeasuring(); // } // // @Override // public void connect() { // notifyDeviceStatusChanged(HRVDeviceStatus.CONNECTING); // // //Release the old access // if(wgtplc != null) { // wgtplc.releaseAccess(); // wgtplc = null; // } // // final AntPlusRRDataDevice helper = this; // // //Make access request // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // AntPlusHeartRatePcc.requestAccess(activity, activity.getApplicationContext(), helper, helper); // } // }); // } // // @Override // public void tryStartRRIntervalMeasuring() { // if(wgtplc == null) // { // connect(); // } // else { // boolean submitted = wgtplc.subscribeCalculatedRrIntervalEvent(this); // // if(submitted) { // notifyDeviceStartedMeasurement(); // } // } // } // }
import android.app.Activity; import android.content.SharedPreferences; import android.preference.PreferenceManager; import hrv.band.app.device.antplus.AntPlusRRDataDevice; import hrv.band.app.device.msband.MSBandRRIntervalDevice;
hrvRRIntervalDevice.connect(); } return hrvRRIntervalDevice; } /** * Connects to ant+ device. */ public HRVRRIntervalDevice connectToAnt() { setDevice(Device.ANT); return connectToIntervalDevice(); } /** * Disconnects connected device. */ public HRVRRIntervalDevice disconnectDevices(HRVRRIntervalDevice hrvRRIntervalDevice) { setDevice(Device.NONE); if (hrvRRIntervalDevice != null) { hrvRRIntervalDevice.notifyDeviceStatusChanged(HRVDeviceStatus.DISCONNECTED); } return null; } public HRVRRIntervalDevice getDevice() { Device device = Device.values()[sharedPreferences.getInt(SELECTED_DEVICE_ID, 0)]; switch (device) { case MSBAND: return new MSBandRRIntervalDevice(activity); case ANT:
// Path: app/src/main/java/hrv/band/app/device/antplus/AntPlusRRDataDevice.java // public class AntPlusRRDataDevice // extends HRVRRIntervalDevice // implements AntPluginPcc.IDeviceStateChangeReceiver, // AntPluginPcc.IPluginAccessResultReceiver<AntPlusHeartRatePcc>, // AntPlusHeartRatePcc.ICalculatedRrIntervalReceiver { // // private final Activity activity; // private AntPlusHeartRatePcc wgtplc; // // public AntPlusRRDataDevice(Activity activity) { // this.activity = activity; // } // // @Override // public void onDeviceStateChange(DeviceState deviceState) { // if(deviceState == DeviceState.DEAD) // { // wgtplc = null; // } // } // // @Override // public void onResultReceived(AntPlusHeartRatePcc antPlusHeartRatePcc, RequestAccessResult requestAccessResult, DeviceState deviceState) { // // switch(requestAccessResult) { // case SUCCESS: // wgtplc = antPlusHeartRatePcc; // notifyDeviceStatusChanged(HRVDeviceStatus.CONNECTED); // break; // case USER_CANCELLED: // case SEARCH_TIMEOUT: // case OTHER_FAILURE: // notifyDeviceStatusChanged(HRVDeviceStatus.DISCONNECTED); // break; // default: // notifyDeviceStatusChanged(HRVDeviceStatus.DISCONNECTED); // } // } // // @Override // public void onNewCalculatedRrInterval(long l, EnumSet<EventFlag> enumSet, BigDecimal bigDecimal, AntPlusHeartRatePcc.RrFlag rrFlag) { // double rr = bigDecimal.longValue() / 1000.0; // this.rrMeasurements.add(rr); // notifyRRIntervalListeners(rr); // } // // // @Override // public void stopMeasuring() { // if(wgtplc != null) { // wgtplc.releaseAccess(); // notifyDeviceStatusChanged(HRVDeviceStatus.DISCONNECTED); // } // } // // @Override // public List<Double> getRRIntervals() { // return rrMeasurements; // } // // @Override // public void pauseMeasuring() { // stopMeasuring(); // } // // @Override // public void destroy() { // stopMeasuring(); // } // // @Override // public void connect() { // notifyDeviceStatusChanged(HRVDeviceStatus.CONNECTING); // // //Release the old access // if(wgtplc != null) { // wgtplc.releaseAccess(); // wgtplc = null; // } // // final AntPlusRRDataDevice helper = this; // // //Make access request // activity.runOnUiThread(new Runnable() { // @Override // public void run() { // AntPlusHeartRatePcc.requestAccess(activity, activity.getApplicationContext(), helper, helper); // } // }); // } // // @Override // public void tryStartRRIntervalMeasuring() { // if(wgtplc == null) // { // connect(); // } // else { // boolean submitted = wgtplc.subscribeCalculatedRrIntervalEvent(this); // // if(submitted) { // notifyDeviceStartedMeasurement(); // } // } // } // } // Path: app/src/main/java/hrv/band/app/device/ConnectionManager.java import android.app.Activity; import android.content.SharedPreferences; import android.preference.PreferenceManager; import hrv.band.app.device.antplus.AntPlusRRDataDevice; import hrv.band.app.device.msband.MSBandRRIntervalDevice; hrvRRIntervalDevice.connect(); } return hrvRRIntervalDevice; } /** * Connects to ant+ device. */ public HRVRRIntervalDevice connectToAnt() { setDevice(Device.ANT); return connectToIntervalDevice(); } /** * Disconnects connected device. */ public HRVRRIntervalDevice disconnectDevices(HRVRRIntervalDevice hrvRRIntervalDevice) { setDevice(Device.NONE); if (hrvRRIntervalDevice != null) { hrvRRIntervalDevice.notifyDeviceStatusChanged(HRVDeviceStatus.DISCONNECTED); } return null; } public HRVRRIntervalDevice getDevice() { Device device = Device.values()[sharedPreferences.getInt(SELECTED_DEVICE_ID, 0)]; switch (device) { case MSBAND: return new MSBandRRIntervalDevice(activity); case ANT:
return new AntPlusRRDataDevice(activity);
HRVBand/hrv-band
app/src/test/java/ui/presenter/HistoryPresenterTest.java
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/IHistoryPresenter.java // public interface IHistoryPresenter { // // List<Measurement> getMeasurements(); // // void updateMeasurements(Date date); // // String[] getPageTitles(); // // List<Fragment> createFragments(); // // int getTitlePosition(HRVParameterEnum value); // // boolean setDrawStrategy(int id, Date date); // // void drawChart(ColumnChartView chart, HRVParameterEnum hrvValue, Context context); // }
import android.content.Context; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import java.util.ArrayList; import java.util.Date; import java.util.List; import hrv.band.app.model.HRVParameterSettings; import hrv.band.app.model.Measurement; import hrv.band.app.ui.presenter.HistoryPresenter; import hrv.band.app.ui.presenter.IHistoryPresenter; import hrv.band.app.ui.view.activity.IHistoryView; import hrv.band.app.ui.view.activity.history.measurementstrategy.AbstractParameterLoadStrategy; import static junit.framework.Assert.assertEquals; import static org.mockito.Mockito.when;
package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 22.04.2017. */ @RunWith(RobolectricTestRunner.class) public class HistoryPresenterTest {
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/IHistoryPresenter.java // public interface IHistoryPresenter { // // List<Measurement> getMeasurements(); // // void updateMeasurements(Date date); // // String[] getPageTitles(); // // List<Fragment> createFragments(); // // int getTitlePosition(HRVParameterEnum value); // // boolean setDrawStrategy(int id, Date date); // // void drawChart(ColumnChartView chart, HRVParameterEnum hrvValue, Context context); // } // Path: app/src/test/java/ui/presenter/HistoryPresenterTest.java import android.content.Context; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import java.util.ArrayList; import java.util.Date; import java.util.List; import hrv.band.app.model.HRVParameterSettings; import hrv.band.app.model.Measurement; import hrv.band.app.ui.presenter.HistoryPresenter; import hrv.band.app.ui.presenter.IHistoryPresenter; import hrv.band.app.ui.view.activity.IHistoryView; import hrv.band.app.ui.view.activity.history.measurementstrategy.AbstractParameterLoadStrategy; import static junit.framework.Assert.assertEquals; import static org.mockito.Mockito.when; package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 22.04.2017. */ @RunWith(RobolectricTestRunner.class) public class HistoryPresenterTest {
private IHistoryPresenter presenter;
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/activity/WebActivity.java
// Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String GOOGLE_FORMS_HOST_URL = "docs.google.com"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String HRVBAND_HOST_URL = "hrvband.de"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String WEBSITE_URL = "http://" + HRVBAND_HOST_URL;
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import hrv.band.app.R; import hrv.band.app.ui.presenter.IWebPresenter; import hrv.band.app.ui.presenter.WebPresenter; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.GOOGLE_FORMS_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.HRVBAND_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.WEBSITE_URL;
package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 04.02.2017 * <p> * This Activity contains a web view and shows the app website. */ public class WebActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, IWebView { public static final String WEBSITE_URL_ID = "website_url_id"; private WebView webView; private IWebPresenter webPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); settingUpNavigationBar(toolbar); webPresenter = new WebPresenter(this); settingUpWebView(); } private void settingUpWebView() { webView = findViewById(R.id.webView); String url = getIntent().getStringExtra(WEBSITE_URL_ID);
// Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String GOOGLE_FORMS_HOST_URL = "docs.google.com"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String HRVBAND_HOST_URL = "hrvband.de"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String WEBSITE_URL = "http://" + HRVBAND_HOST_URL; // Path: app/src/main/java/hrv/band/app/ui/view/activity/WebActivity.java import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import hrv.band.app.R; import hrv.band.app.ui.presenter.IWebPresenter; import hrv.band.app.ui.presenter.WebPresenter; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.GOOGLE_FORMS_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.HRVBAND_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.WEBSITE_URL; package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 04.02.2017 * <p> * This Activity contains a web view and shows the app website. */ public class WebActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, IWebView { public static final String WEBSITE_URL_ID = "website_url_id"; private WebView webView; private IWebPresenter webPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); settingUpNavigationBar(toolbar); webPresenter = new WebPresenter(this); settingUpWebView(); } private void settingUpWebView() { webView = findViewById(R.id.webView); String url = getIntent().getStringExtra(WEBSITE_URL_ID);
if (!url.contains(HRVBAND_HOST_URL) && !url.contains(GOOGLE_FORMS_HOST_URL) ) {
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/activity/WebActivity.java
// Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String GOOGLE_FORMS_HOST_URL = "docs.google.com"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String HRVBAND_HOST_URL = "hrvband.de"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String WEBSITE_URL = "http://" + HRVBAND_HOST_URL;
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import hrv.band.app.R; import hrv.band.app.ui.presenter.IWebPresenter; import hrv.band.app.ui.presenter.WebPresenter; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.GOOGLE_FORMS_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.HRVBAND_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.WEBSITE_URL;
package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 04.02.2017 * <p> * This Activity contains a web view and shows the app website. */ public class WebActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, IWebView { public static final String WEBSITE_URL_ID = "website_url_id"; private WebView webView; private IWebPresenter webPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); settingUpNavigationBar(toolbar); webPresenter = new WebPresenter(this); settingUpWebView(); } private void settingUpWebView() { webView = findViewById(R.id.webView); String url = getIntent().getStringExtra(WEBSITE_URL_ID);
// Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String GOOGLE_FORMS_HOST_URL = "docs.google.com"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String HRVBAND_HOST_URL = "hrvband.de"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String WEBSITE_URL = "http://" + HRVBAND_HOST_URL; // Path: app/src/main/java/hrv/band/app/ui/view/activity/WebActivity.java import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import hrv.band.app.R; import hrv.band.app.ui.presenter.IWebPresenter; import hrv.band.app.ui.presenter.WebPresenter; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.GOOGLE_FORMS_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.HRVBAND_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.WEBSITE_URL; package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 04.02.2017 * <p> * This Activity contains a web view and shows the app website. */ public class WebActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, IWebView { public static final String WEBSITE_URL_ID = "website_url_id"; private WebView webView; private IWebPresenter webPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); settingUpNavigationBar(toolbar); webPresenter = new WebPresenter(this); settingUpWebView(); } private void settingUpWebView() { webView = findViewById(R.id.webView); String url = getIntent().getStringExtra(WEBSITE_URL_ID);
if (!url.contains(HRVBAND_HOST_URL) && !url.contains(GOOGLE_FORMS_HOST_URL) ) {
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/activity/WebActivity.java
// Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String GOOGLE_FORMS_HOST_URL = "docs.google.com"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String HRVBAND_HOST_URL = "hrvband.de"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String WEBSITE_URL = "http://" + HRVBAND_HOST_URL;
import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import hrv.band.app.R; import hrv.band.app.ui.presenter.IWebPresenter; import hrv.band.app.ui.presenter.WebPresenter; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.GOOGLE_FORMS_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.HRVBAND_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.WEBSITE_URL;
package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 04.02.2017 * <p> * This Activity contains a web view and shows the app website. */ public class WebActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, IWebView { public static final String WEBSITE_URL_ID = "website_url_id"; private WebView webView; private IWebPresenter webPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); settingUpNavigationBar(toolbar); webPresenter = new WebPresenter(this); settingUpWebView(); } private void settingUpWebView() { webView = findViewById(R.id.webView); String url = getIntent().getStringExtra(WEBSITE_URL_ID); if (!url.contains(HRVBAND_HOST_URL) && !url.contains(GOOGLE_FORMS_HOST_URL) ) {
// Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String GOOGLE_FORMS_HOST_URL = "docs.google.com"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String HRVBAND_HOST_URL = "hrvband.de"; // // Path: app/src/main/java/hrv/band/app/ui/view/activity/web/WebsiteUrls.java // public static final String WEBSITE_URL = "http://" + HRVBAND_HOST_URL; // Path: app/src/main/java/hrv/band/app/ui/view/activity/WebActivity.java import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import hrv.band.app.R; import hrv.band.app.ui.presenter.IWebPresenter; import hrv.band.app.ui.presenter.WebPresenter; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.GOOGLE_FORMS_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.HRVBAND_HOST_URL; import static hrv.band.app.ui.view.activity.web.WebsiteUrls.WEBSITE_URL; package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 04.02.2017 * <p> * This Activity contains a web view and shows the app website. */ public class WebActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, IWebView { public static final String WEBSITE_URL_ID = "website_url_id"; private WebView webView; private IWebPresenter webPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); settingUpNavigationBar(toolbar); webPresenter = new WebPresenter(this); settingUpWebView(); } private void settingUpWebView() { webView = findViewById(R.id.webView); String url = getIntent().getStringExtra(WEBSITE_URL_ID); if (!url.contains(HRVBAND_HOST_URL) && !url.contains(GOOGLE_FORMS_HOST_URL) ) {
url = WEBSITE_URL;
HRVBand/hrv-band
app/src/test/java/ui/view/fragment/MeasureRRFragmentTest.java
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // }
import android.os.Build; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.support.v4.SupportFragmentTestUtil; import java.util.Date; import hrv.band.app.BuildConfig; import hrv.band.app.model.Measurement; import hrv.band.app.ui.view.fragment.MeasuredRRFragment; import static junit.framework.Assert.assertNotNull;
package ui.view.fragment; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 31.01.2017 * * Tests for {@link MeasuredRRFragment} */ @Config(constants = BuildConfig.class, sdk = {Build.VERSION_CODES.LOLLIPOP/*, Build.VERSION_CODES.KITKAT*/}) @RunWith(RobolectricTestRunner.class) public class MeasureRRFragmentTest {
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // Path: app/src/test/java/ui/view/fragment/MeasureRRFragmentTest.java import android.os.Build; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.support.v4.SupportFragmentTestUtil; import java.util.Date; import hrv.band.app.BuildConfig; import hrv.band.app.model.Measurement; import hrv.band.app.ui.view.fragment.MeasuredRRFragment; import static junit.framework.Assert.assertNotNull; package ui.view.fragment; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 31.01.2017 * * Tests for {@link MeasuredRRFragment} */ @Config(constants = BuildConfig.class, sdk = {Build.VERSION_CODES.LOLLIPOP/*, Build.VERSION_CODES.KITKAT*/}) @RunWith(RobolectricTestRunner.class) public class MeasureRRFragmentTest {
private static Measurement parameter;
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/activity/SavableMeasurementActivity.java
// Path: app/src/main/java/hrv/band/app/ui/view/fragment/MeasuredDetailsEditFragment.java // public class MeasuredDetailsEditFragment extends Fragment implements IMeasuredDetailsView { // // /** // * rootView of this Fragment. // **/ // private View rootView; // // /** // * Returns a new instance of this fragment. // * // * @return a new instance of this fragment. // */ // public static MeasuredDetailsEditFragment newInstance() { // return new MeasuredDetailsEditFragment(); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // rootView = inflater.inflate(R.layout.hrv_measurement_fragment_details, container, false); // // Spinner spinner = rootView.findViewById(R.id.measure_categories); // AbstractCategoryAdapter spinnerArrayAdapter = new MeasurementCategoryAdapter(getContext()); // // spinner.setAdapter(spinnerArrayAdapter); // // return rootView; // } // // /** // * Returns the rating of the user for the actual measurement. // * // * @return the rating of the user for the actual measurement. // */ // @Override // public float getRating() { // if (rootView == null) { // return 0; // } // RatingBar ratingbar = rootView.findViewById(R.id.measure_rating); // return ratingbar.getRating(); // } // // /** // * Returns the chosen category. // * // * @return the chosen category. // */ // @Override // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (rootView == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // Spinner spinner = rootView.findViewById(R.id.measure_categories); // int position = spinner.getSelectedItemPosition(); // return MeasurementCategoryAdapter.MeasureCategory.values()[position]; // } // // /** // * Returns the note the user entered. // * // * @return the note the user entered. // */ // @Override // public String getNote() { // if (rootView == null) { // return ""; // } // TextView note = rootView.findViewById(R.id.measure_note); // return note.getText().toString(); // } // // @Override // public Fragment getFragment() { // return this; // } // }
import android.support.v4.app.Fragment; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import java.util.List; import hrv.band.app.R; import hrv.band.app.ui.view.fragment.IMeasuredDetailsView; import hrv.band.app.ui.view.fragment.MeasuredDetailsEditFragment; import hrv.band.app.ui.view.fragment.TextDialogFragment;
package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 19.01.2017 * <p> * This Activity holds the Fragments which shows the actual HRV Measurement. */ public class SavableMeasurementActivity extends AbstractMeasurementActivity { private IMeasuredDetailsView measuredDetailsEditFragment; @Override protected int getContentViewId() { return R.layout.activity_hrv_measurement; } @Override protected int getViewPagerID() { return R.id.measure_details_viewpager; } @Override protected int getTabID() { return R.id.measure_details_tabs; } @Override protected void addDetailsFragment(List<Fragment> fragments) {
// Path: app/src/main/java/hrv/band/app/ui/view/fragment/MeasuredDetailsEditFragment.java // public class MeasuredDetailsEditFragment extends Fragment implements IMeasuredDetailsView { // // /** // * rootView of this Fragment. // **/ // private View rootView; // // /** // * Returns a new instance of this fragment. // * // * @return a new instance of this fragment. // */ // public static MeasuredDetailsEditFragment newInstance() { // return new MeasuredDetailsEditFragment(); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // rootView = inflater.inflate(R.layout.hrv_measurement_fragment_details, container, false); // // Spinner spinner = rootView.findViewById(R.id.measure_categories); // AbstractCategoryAdapter spinnerArrayAdapter = new MeasurementCategoryAdapter(getContext()); // // spinner.setAdapter(spinnerArrayAdapter); // // return rootView; // } // // /** // * Returns the rating of the user for the actual measurement. // * // * @return the rating of the user for the actual measurement. // */ // @Override // public float getRating() { // if (rootView == null) { // return 0; // } // RatingBar ratingbar = rootView.findViewById(R.id.measure_rating); // return ratingbar.getRating(); // } // // /** // * Returns the chosen category. // * // * @return the chosen category. // */ // @Override // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (rootView == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // Spinner spinner = rootView.findViewById(R.id.measure_categories); // int position = spinner.getSelectedItemPosition(); // return MeasurementCategoryAdapter.MeasureCategory.values()[position]; // } // // /** // * Returns the note the user entered. // * // * @return the note the user entered. // */ // @Override // public String getNote() { // if (rootView == null) { // return ""; // } // TextView note = rootView.findViewById(R.id.measure_note); // return note.getText().toString(); // } // // @Override // public Fragment getFragment() { // return this; // } // } // Path: app/src/main/java/hrv/band/app/ui/view/activity/SavableMeasurementActivity.java import android.support.v4.app.Fragment; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import java.util.List; import hrv.band.app.R; import hrv.band.app.ui.view.fragment.IMeasuredDetailsView; import hrv.band.app.ui.view.fragment.MeasuredDetailsEditFragment; import hrv.band.app.ui.view.fragment.TextDialogFragment; package hrv.band.app.ui.view.activity; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 19.01.2017 * <p> * This Activity holds the Fragments which shows the actual HRV Measurement. */ public class SavableMeasurementActivity extends AbstractMeasurementActivity { private IMeasuredDetailsView measuredDetailsEditFragment; @Override protected int getContentViewId() { return R.layout.activity_hrv_measurement; } @Override protected int getViewPagerID() { return R.id.measure_details_viewpager; } @Override protected int getTabID() { return R.id.measure_details_tabs; } @Override protected void addDetailsFragment(List<Fragment> fragments) {
measuredDetailsEditFragment = MeasuredDetailsEditFragment.newInstance();
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/activity/history/measurementstrategy/ParameterLoadWeekStrategy.java
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // }
import android.content.Context; import android.support.annotation.NonNull; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import hrv.band.app.model.Measurement;
package hrv.band.app.ui.view.activity.history.measurementstrategy; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 25.03.2017 * <p> * Loads parameter from given week. */ public class ParameterLoadWeekStrategy extends AbstractParameterLoadStrategy { public ParameterLoadWeekStrategy(Context context) { super(context); } @Override
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // Path: app/src/main/java/hrv/band/app/ui/view/activity/history/measurementstrategy/ParameterLoadWeekStrategy.java import android.content.Context; import android.support.annotation.NonNull; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import hrv.band.app.model.Measurement; package hrv.band.app.ui.view.activity.history.measurementstrategy; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 25.03.2017 * <p> * Loads parameter from given week. */ public class ParameterLoadWeekStrategy extends AbstractParameterLoadStrategy { public ParameterLoadWeekStrategy(Context context) { super(context); } @Override
public List<Measurement> loadParameter(Date date) {
HRVBand/hrv-band
app/src/test/java/ui/presenter/SettingsPresenterTest.java
// Path: app/src/main/java/hrv/band/app/ui/presenter/ISettingsPresenter.java // public interface ISettingsPresenter { // boolean hasFileWritePermission(); // // boolean getFileWritePermission(); // // boolean isRecordLengthValid(String o); // // void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/SettingsPresenter.java // public class SettingsPresenter implements ISettingsPresenter { // private static final int EXPORT_DATABASE_REQUEST_ID = 200; // // private ISettingsView settingsView; // // // public SettingsPresenter(ISettingsView settingsView) { // this.settingsView = settingsView; // } // // @Override // public boolean hasFileWritePermission() { // return ContextCompat.checkSelfPermission(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE) // == PackageManager.PERMISSION_GRANTED; // } // /** // * Tries to get the file write permission // * // * @return Returns false if permission could not be granted, true otherwise // */ // @Override // public boolean getFileWritePermission() { // if (!canMakeSmores()) { // return false; // } // // if (hasFileWritePermission()) { // return true; // } // // if (ActivityCompat.shouldShowRequestPermissionRationale(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // // settingsView.showSnackbar(R.string.settings_request_ext_write_message, // new View.OnClickListener() { // @Override // public void onClick(View view) { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // }); // } else { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // // return true; // } // // private void requestWritePermission(int requestId) { // ActivityCompat.requestPermissions(settingsView.getSettingsActivity(), // new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestId); // } // // @Override // public void onRequestPermissionsResult(int requestCode, // String[] permissions, int[] grantResults) { // if (requestCode == EXPORT_DATABASE_REQUEST_ID // && (grantResults.length > 0 // && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // // settingsView.startExportFragment(); // } // } // // @Override // public boolean isRecordLengthValid(String recordLength) { // boolean matchesNumber = recordLength.matches("[0-9]+"); // boolean matchesLength = recordLength.matches("[0-9]{2,6}+"); // // if (!matchesNumber) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.invalid_measurement_length_character); // return false; // } else if(!matchesLength) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.settings_invalid_measurement_length); // return false; // } // return true; // } // // private boolean canMakeSmores() { // return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1; // } // } // // Path: app/src/main/java/hrv/band/app/ui/view/fragment/ISettingsView.java // public interface ISettingsView { // Activity getSettingsActivity(); // // void showSnackbar(int messageId, View.OnClickListener clickListener); // // void showAlertDialog(int titleId, int messageId); // // void startExportFragment(); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import hrv.band.app.ui.presenter.ISettingsPresenter; import hrv.band.app.ui.presenter.SettingsPresenter; import hrv.band.app.ui.view.fragment.ISettingsView; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue;
package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 15.04.2017. */ @RunWith(MockitoJUnitRunner.class) public class SettingsPresenterTest { @Mock
// Path: app/src/main/java/hrv/band/app/ui/presenter/ISettingsPresenter.java // public interface ISettingsPresenter { // boolean hasFileWritePermission(); // // boolean getFileWritePermission(); // // boolean isRecordLengthValid(String o); // // void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/SettingsPresenter.java // public class SettingsPresenter implements ISettingsPresenter { // private static final int EXPORT_DATABASE_REQUEST_ID = 200; // // private ISettingsView settingsView; // // // public SettingsPresenter(ISettingsView settingsView) { // this.settingsView = settingsView; // } // // @Override // public boolean hasFileWritePermission() { // return ContextCompat.checkSelfPermission(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE) // == PackageManager.PERMISSION_GRANTED; // } // /** // * Tries to get the file write permission // * // * @return Returns false if permission could not be granted, true otherwise // */ // @Override // public boolean getFileWritePermission() { // if (!canMakeSmores()) { // return false; // } // // if (hasFileWritePermission()) { // return true; // } // // if (ActivityCompat.shouldShowRequestPermissionRationale(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // // settingsView.showSnackbar(R.string.settings_request_ext_write_message, // new View.OnClickListener() { // @Override // public void onClick(View view) { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // }); // } else { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // // return true; // } // // private void requestWritePermission(int requestId) { // ActivityCompat.requestPermissions(settingsView.getSettingsActivity(), // new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestId); // } // // @Override // public void onRequestPermissionsResult(int requestCode, // String[] permissions, int[] grantResults) { // if (requestCode == EXPORT_DATABASE_REQUEST_ID // && (grantResults.length > 0 // && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // // settingsView.startExportFragment(); // } // } // // @Override // public boolean isRecordLengthValid(String recordLength) { // boolean matchesNumber = recordLength.matches("[0-9]+"); // boolean matchesLength = recordLength.matches("[0-9]{2,6}+"); // // if (!matchesNumber) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.invalid_measurement_length_character); // return false; // } else if(!matchesLength) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.settings_invalid_measurement_length); // return false; // } // return true; // } // // private boolean canMakeSmores() { // return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1; // } // } // // Path: app/src/main/java/hrv/band/app/ui/view/fragment/ISettingsView.java // public interface ISettingsView { // Activity getSettingsActivity(); // // void showSnackbar(int messageId, View.OnClickListener clickListener); // // void showAlertDialog(int titleId, int messageId); // // void startExportFragment(); // } // Path: app/src/test/java/ui/presenter/SettingsPresenterTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import hrv.band.app.ui.presenter.ISettingsPresenter; import hrv.band.app.ui.presenter.SettingsPresenter; import hrv.band.app.ui.view.fragment.ISettingsView; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 15.04.2017. */ @RunWith(MockitoJUnitRunner.class) public class SettingsPresenterTest { @Mock
ISettingsView settingsView;
HRVBand/hrv-band
app/src/test/java/ui/presenter/SettingsPresenterTest.java
// Path: app/src/main/java/hrv/band/app/ui/presenter/ISettingsPresenter.java // public interface ISettingsPresenter { // boolean hasFileWritePermission(); // // boolean getFileWritePermission(); // // boolean isRecordLengthValid(String o); // // void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/SettingsPresenter.java // public class SettingsPresenter implements ISettingsPresenter { // private static final int EXPORT_DATABASE_REQUEST_ID = 200; // // private ISettingsView settingsView; // // // public SettingsPresenter(ISettingsView settingsView) { // this.settingsView = settingsView; // } // // @Override // public boolean hasFileWritePermission() { // return ContextCompat.checkSelfPermission(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE) // == PackageManager.PERMISSION_GRANTED; // } // /** // * Tries to get the file write permission // * // * @return Returns false if permission could not be granted, true otherwise // */ // @Override // public boolean getFileWritePermission() { // if (!canMakeSmores()) { // return false; // } // // if (hasFileWritePermission()) { // return true; // } // // if (ActivityCompat.shouldShowRequestPermissionRationale(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // // settingsView.showSnackbar(R.string.settings_request_ext_write_message, // new View.OnClickListener() { // @Override // public void onClick(View view) { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // }); // } else { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // // return true; // } // // private void requestWritePermission(int requestId) { // ActivityCompat.requestPermissions(settingsView.getSettingsActivity(), // new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestId); // } // // @Override // public void onRequestPermissionsResult(int requestCode, // String[] permissions, int[] grantResults) { // if (requestCode == EXPORT_DATABASE_REQUEST_ID // && (grantResults.length > 0 // && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // // settingsView.startExportFragment(); // } // } // // @Override // public boolean isRecordLengthValid(String recordLength) { // boolean matchesNumber = recordLength.matches("[0-9]+"); // boolean matchesLength = recordLength.matches("[0-9]{2,6}+"); // // if (!matchesNumber) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.invalid_measurement_length_character); // return false; // } else if(!matchesLength) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.settings_invalid_measurement_length); // return false; // } // return true; // } // // private boolean canMakeSmores() { // return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1; // } // } // // Path: app/src/main/java/hrv/band/app/ui/view/fragment/ISettingsView.java // public interface ISettingsView { // Activity getSettingsActivity(); // // void showSnackbar(int messageId, View.OnClickListener clickListener); // // void showAlertDialog(int titleId, int messageId); // // void startExportFragment(); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import hrv.band.app.ui.presenter.ISettingsPresenter; import hrv.band.app.ui.presenter.SettingsPresenter; import hrv.band.app.ui.view.fragment.ISettingsView; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue;
package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 15.04.2017. */ @RunWith(MockitoJUnitRunner.class) public class SettingsPresenterTest { @Mock ISettingsView settingsView;
// Path: app/src/main/java/hrv/band/app/ui/presenter/ISettingsPresenter.java // public interface ISettingsPresenter { // boolean hasFileWritePermission(); // // boolean getFileWritePermission(); // // boolean isRecordLengthValid(String o); // // void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/SettingsPresenter.java // public class SettingsPresenter implements ISettingsPresenter { // private static final int EXPORT_DATABASE_REQUEST_ID = 200; // // private ISettingsView settingsView; // // // public SettingsPresenter(ISettingsView settingsView) { // this.settingsView = settingsView; // } // // @Override // public boolean hasFileWritePermission() { // return ContextCompat.checkSelfPermission(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE) // == PackageManager.PERMISSION_GRANTED; // } // /** // * Tries to get the file write permission // * // * @return Returns false if permission could not be granted, true otherwise // */ // @Override // public boolean getFileWritePermission() { // if (!canMakeSmores()) { // return false; // } // // if (hasFileWritePermission()) { // return true; // } // // if (ActivityCompat.shouldShowRequestPermissionRationale(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // // settingsView.showSnackbar(R.string.settings_request_ext_write_message, // new View.OnClickListener() { // @Override // public void onClick(View view) { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // }); // } else { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // // return true; // } // // private void requestWritePermission(int requestId) { // ActivityCompat.requestPermissions(settingsView.getSettingsActivity(), // new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestId); // } // // @Override // public void onRequestPermissionsResult(int requestCode, // String[] permissions, int[] grantResults) { // if (requestCode == EXPORT_DATABASE_REQUEST_ID // && (grantResults.length > 0 // && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // // settingsView.startExportFragment(); // } // } // // @Override // public boolean isRecordLengthValid(String recordLength) { // boolean matchesNumber = recordLength.matches("[0-9]+"); // boolean matchesLength = recordLength.matches("[0-9]{2,6}+"); // // if (!matchesNumber) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.invalid_measurement_length_character); // return false; // } else if(!matchesLength) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.settings_invalid_measurement_length); // return false; // } // return true; // } // // private boolean canMakeSmores() { // return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1; // } // } // // Path: app/src/main/java/hrv/band/app/ui/view/fragment/ISettingsView.java // public interface ISettingsView { // Activity getSettingsActivity(); // // void showSnackbar(int messageId, View.OnClickListener clickListener); // // void showAlertDialog(int titleId, int messageId); // // void startExportFragment(); // } // Path: app/src/test/java/ui/presenter/SettingsPresenterTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import hrv.band.app.ui.presenter.ISettingsPresenter; import hrv.band.app.ui.presenter.SettingsPresenter; import hrv.band.app.ui.view.fragment.ISettingsView; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 15.04.2017. */ @RunWith(MockitoJUnitRunner.class) public class SettingsPresenterTest { @Mock ISettingsView settingsView;
private ISettingsPresenter presenter;
HRVBand/hrv-band
app/src/test/java/ui/presenter/SettingsPresenterTest.java
// Path: app/src/main/java/hrv/band/app/ui/presenter/ISettingsPresenter.java // public interface ISettingsPresenter { // boolean hasFileWritePermission(); // // boolean getFileWritePermission(); // // boolean isRecordLengthValid(String o); // // void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/SettingsPresenter.java // public class SettingsPresenter implements ISettingsPresenter { // private static final int EXPORT_DATABASE_REQUEST_ID = 200; // // private ISettingsView settingsView; // // // public SettingsPresenter(ISettingsView settingsView) { // this.settingsView = settingsView; // } // // @Override // public boolean hasFileWritePermission() { // return ContextCompat.checkSelfPermission(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE) // == PackageManager.PERMISSION_GRANTED; // } // /** // * Tries to get the file write permission // * // * @return Returns false if permission could not be granted, true otherwise // */ // @Override // public boolean getFileWritePermission() { // if (!canMakeSmores()) { // return false; // } // // if (hasFileWritePermission()) { // return true; // } // // if (ActivityCompat.shouldShowRequestPermissionRationale(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // // settingsView.showSnackbar(R.string.settings_request_ext_write_message, // new View.OnClickListener() { // @Override // public void onClick(View view) { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // }); // } else { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // // return true; // } // // private void requestWritePermission(int requestId) { // ActivityCompat.requestPermissions(settingsView.getSettingsActivity(), // new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestId); // } // // @Override // public void onRequestPermissionsResult(int requestCode, // String[] permissions, int[] grantResults) { // if (requestCode == EXPORT_DATABASE_REQUEST_ID // && (grantResults.length > 0 // && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // // settingsView.startExportFragment(); // } // } // // @Override // public boolean isRecordLengthValid(String recordLength) { // boolean matchesNumber = recordLength.matches("[0-9]+"); // boolean matchesLength = recordLength.matches("[0-9]{2,6}+"); // // if (!matchesNumber) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.invalid_measurement_length_character); // return false; // } else if(!matchesLength) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.settings_invalid_measurement_length); // return false; // } // return true; // } // // private boolean canMakeSmores() { // return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1; // } // } // // Path: app/src/main/java/hrv/band/app/ui/view/fragment/ISettingsView.java // public interface ISettingsView { // Activity getSettingsActivity(); // // void showSnackbar(int messageId, View.OnClickListener clickListener); // // void showAlertDialog(int titleId, int messageId); // // void startExportFragment(); // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import hrv.band.app.ui.presenter.ISettingsPresenter; import hrv.band.app.ui.presenter.SettingsPresenter; import hrv.band.app.ui.view.fragment.ISettingsView; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue;
package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 15.04.2017. */ @RunWith(MockitoJUnitRunner.class) public class SettingsPresenterTest { @Mock ISettingsView settingsView; private ISettingsPresenter presenter; @Before public void setup() {
// Path: app/src/main/java/hrv/band/app/ui/presenter/ISettingsPresenter.java // public interface ISettingsPresenter { // boolean hasFileWritePermission(); // // boolean getFileWritePermission(); // // boolean isRecordLengthValid(String o); // // void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/SettingsPresenter.java // public class SettingsPresenter implements ISettingsPresenter { // private static final int EXPORT_DATABASE_REQUEST_ID = 200; // // private ISettingsView settingsView; // // // public SettingsPresenter(ISettingsView settingsView) { // this.settingsView = settingsView; // } // // @Override // public boolean hasFileWritePermission() { // return ContextCompat.checkSelfPermission(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE) // == PackageManager.PERMISSION_GRANTED; // } // /** // * Tries to get the file write permission // * // * @return Returns false if permission could not be granted, true otherwise // */ // @Override // public boolean getFileWritePermission() { // if (!canMakeSmores()) { // return false; // } // // if (hasFileWritePermission()) { // return true; // } // // if (ActivityCompat.shouldShowRequestPermissionRationale(settingsView.getSettingsActivity(), // Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // // settingsView.showSnackbar(R.string.settings_request_ext_write_message, // new View.OnClickListener() { // @Override // public void onClick(View view) { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // }); // } else { // requestWritePermission(EXPORT_DATABASE_REQUEST_ID); // } // // return true; // } // // private void requestWritePermission(int requestId) { // ActivityCompat.requestPermissions(settingsView.getSettingsActivity(), // new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestId); // } // // @Override // public void onRequestPermissionsResult(int requestCode, // String[] permissions, int[] grantResults) { // if (requestCode == EXPORT_DATABASE_REQUEST_ID // && (grantResults.length > 0 // && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // // settingsView.startExportFragment(); // } // } // // @Override // public boolean isRecordLengthValid(String recordLength) { // boolean matchesNumber = recordLength.matches("[0-9]+"); // boolean matchesLength = recordLength.matches("[0-9]{2,6}+"); // // if (!matchesNumber) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.invalid_measurement_length_character); // return false; // } else if(!matchesLength) { // settingsView.showAlertDialog(R.string.invalid_input, R.string.settings_invalid_measurement_length); // return false; // } // return true; // } // // private boolean canMakeSmores() { // return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1; // } // } // // Path: app/src/main/java/hrv/band/app/ui/view/fragment/ISettingsView.java // public interface ISettingsView { // Activity getSettingsActivity(); // // void showSnackbar(int messageId, View.OnClickListener clickListener); // // void showAlertDialog(int titleId, int messageId); // // void startExportFragment(); // } // Path: app/src/test/java/ui/presenter/SettingsPresenterTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import hrv.band.app.ui.presenter.ISettingsPresenter; import hrv.band.app.ui.presenter.SettingsPresenter; import hrv.band.app.ui.view.fragment.ISettingsView; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 15.04.2017. */ @RunWith(MockitoJUnitRunner.class) public class SettingsPresenterTest { @Mock ISettingsView settingsView; private ISettingsPresenter presenter; @Before public void setup() {
presenter = new SettingsPresenter(settingsView);
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/presenter/IMeasuringPresenter.java
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // }
import java.util.Date; import java.util.List; import hrv.band.app.model.Measurement;
package hrv.band.app.ui.presenter; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 23.04.2017 */ public interface IMeasuringPresenter { int getDuration();
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // Path: app/src/main/java/hrv/band/app/ui/presenter/IMeasuringPresenter.java import java.util.Date; import java.util.List; import hrv.band.app.model.Measurement; package hrv.band.app.ui.presenter; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 23.04.2017 */ public interface IMeasuringPresenter { int getDuration();
Measurement createMeasurement(List<Double> rrInterval, Date time);
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/fragment/measuring/listener/MeasurementClickListener.java
// Path: app/src/main/java/hrv/band/app/device/HRVRRIntervalDevice.java // public abstract class HRVRRIntervalDevice implements HRVRRIntervalEventInitiator { // // private final List<HRVRRIntervalListener> listeners = new ArrayList<>(); // private final List<HRVRRDeviceListener> deviceListeners = new ArrayList<>(); // protected List<Double> rrMeasurements = new ArrayList<>(); // // public abstract void connect(); // public abstract void tryStartRRIntervalMeasuring(); // public abstract void stopMeasuring(); // public abstract void destroy(); // public abstract void pauseMeasuring(); // // public List<Double> getRRIntervals() { // return rrMeasurements; // } // // public void clearRRIntervals() { // rrMeasurements = new ArrayList<>(); // } // // @Override // public void notifyRRIntervalListeners(double rrValue) { // for (HRVRRIntervalListener listener: listeners) { // HRVRRIntervalEvent event = new HRVRRIntervalEvent(); // event.setRr(rrValue); // listener.newRRInterval(event); // } // } // // @Override // public void addRRIntervalListener(HRVRRIntervalListener toAdd) { // listeners.add(toAdd); // } // // public void notifyDeviceStartedMeasurement() { // for (HRVRRDeviceListener listener: deviceListeners) { // listener.deviceStartedMeasurement(); // } // } // // public void notifyDeviceStatusChanged(HRVDeviceStatus status) { // for(HRVRRDeviceListener listener : deviceListeners) { // listener.deviceStatusChanged(status); // } // } // // public void notifyDeviceError(String error) { // for (HRVRRDeviceListener listener: deviceListeners) { // listener.deviceError(error); // } // } // // public void addDeviceListener(HRVRRDeviceListener toAdd) {deviceListeners.add(toAdd); } // }
import android.view.View; import hrv.band.app.R; import hrv.band.app.device.HRVRRIntervalDevice; import hrv.band.app.ui.view.fragment.IMeasuringView;
package hrv.band.app.ui.view.fragment.measuring.listener; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 23.04.2017 * * Click listener handling the clicks in this fragment. */ public class MeasurementClickListener implements View.OnClickListener { private IMeasuringView measuringView; public MeasurementClickListener(IMeasuringView measuringView) { this.measuringView = measuringView; } @Override public void onClick(View view) { if (view.getId() == R.id.progressBar) { startMeasurement(); } } private void startMeasurement() { if (measuringView.isAnimationRunning()) { measuringView.showCancelDialog(); } else {
// Path: app/src/main/java/hrv/band/app/device/HRVRRIntervalDevice.java // public abstract class HRVRRIntervalDevice implements HRVRRIntervalEventInitiator { // // private final List<HRVRRIntervalListener> listeners = new ArrayList<>(); // private final List<HRVRRDeviceListener> deviceListeners = new ArrayList<>(); // protected List<Double> rrMeasurements = new ArrayList<>(); // // public abstract void connect(); // public abstract void tryStartRRIntervalMeasuring(); // public abstract void stopMeasuring(); // public abstract void destroy(); // public abstract void pauseMeasuring(); // // public List<Double> getRRIntervals() { // return rrMeasurements; // } // // public void clearRRIntervals() { // rrMeasurements = new ArrayList<>(); // } // // @Override // public void notifyRRIntervalListeners(double rrValue) { // for (HRVRRIntervalListener listener: listeners) { // HRVRRIntervalEvent event = new HRVRRIntervalEvent(); // event.setRr(rrValue); // listener.newRRInterval(event); // } // } // // @Override // public void addRRIntervalListener(HRVRRIntervalListener toAdd) { // listeners.add(toAdd); // } // // public void notifyDeviceStartedMeasurement() { // for (HRVRRDeviceListener listener: deviceListeners) { // listener.deviceStartedMeasurement(); // } // } // // public void notifyDeviceStatusChanged(HRVDeviceStatus status) { // for(HRVRRDeviceListener listener : deviceListeners) { // listener.deviceStatusChanged(status); // } // } // // public void notifyDeviceError(String error) { // for (HRVRRDeviceListener listener: deviceListeners) { // listener.deviceError(error); // } // } // // public void addDeviceListener(HRVRRDeviceListener toAdd) {deviceListeners.add(toAdd); } // } // Path: app/src/main/java/hrv/band/app/ui/view/fragment/measuring/listener/MeasurementClickListener.java import android.view.View; import hrv.band.app.R; import hrv.band.app.device.HRVRRIntervalDevice; import hrv.band.app.ui.view.fragment.IMeasuringView; package hrv.band.app.ui.view.fragment.measuring.listener; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 23.04.2017 * * Click listener handling the clicks in this fragment. */ public class MeasurementClickListener implements View.OnClickListener { private IMeasuringView measuringView; public MeasurementClickListener(IMeasuringView measuringView) { this.measuringView = measuringView; } @Override public void onClick(View view) { if (view.getId() == R.id.progressBar) { startMeasurement(); } } private void startMeasurement() { if (measuringView.isAnimationRunning()) { measuringView.showCancelDialog(); } else {
final HRVRRIntervalDevice hrvRrIntervalDevice = measuringView.getHrvRrIntervalDevice();
HRVBand/hrv-band
app/src/test/java/ui/presenter/MeasuringPresenterTest.java
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/IMeasuringPresenter.java // public interface IMeasuringPresenter { // int getDuration(); // // Measurement createMeasurement(List<Double> rrInterval, Date time); // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.Date; import java.util.List; import hrv.band.app.model.Measurement; import hrv.band.app.ui.presenter.IMeasuringPresenter; import hrv.band.app.ui.presenter.MeasuringPresenter; import hrv.band.app.ui.view.fragment.IMeasuringView; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull;
package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 27.04.2017 */ public class MeasuringPresenterTest { private IMeasuringPresenter presenter; private List<Double> rrInterval; @Mock private IMeasuringView measuringView; @Before public void setup() { MockitoAnnotations.initMocks(this); presenter = new MeasuringPresenter(measuringView); rrInterval = new ArrayList<>(); } @Test public void createMeasurementTest() { rrInterval.add(1.0); rrInterval.add(1.0); rrInterval.add(1.0); rrInterval.add(1.0);
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/IMeasuringPresenter.java // public interface IMeasuringPresenter { // int getDuration(); // // Measurement createMeasurement(List<Double> rrInterval, Date time); // } // Path: app/src/test/java/ui/presenter/MeasuringPresenterTest.java import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.Date; import java.util.List; import hrv.band.app.model.Measurement; import hrv.band.app.ui.presenter.IMeasuringPresenter; import hrv.band.app.ui.presenter.MeasuringPresenter; import hrv.band.app.ui.view.fragment.IMeasuringView; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 27.04.2017 */ public class MeasuringPresenterTest { private IMeasuringPresenter presenter; private List<Double> rrInterval; @Mock private IMeasuringView measuringView; @Before public void setup() { MockitoAnnotations.initMocks(this); presenter = new MeasuringPresenter(measuringView); rrInterval = new ArrayList<>(); } @Test public void createMeasurementTest() { rrInterval.add(1.0); rrInterval.add(1.0); rrInterval.add(1.0); rrInterval.add(1.0);
Measurement measurement = presenter.createMeasurement(rrInterval, new Date());
HRVBand/hrv-band
app/src/test/java/ui/presenter/HRVParameterPresenterTest.java
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/IHRVParameterPresenter.java // public interface IHRVParameterPresenter { // List<HRVParameter> getHRVParameters(); // void calculateParameters(); // }
import org.junit.Test; import java.util.Date; import hrv.band.app.model.Measurement; import hrv.band.app.ui.presenter.HRVParameterPresenter; import hrv.band.app.ui.presenter.IHRVParameterPresenter; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue;
package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 17.04.2017. */ public class HRVParameterPresenterTest { private IHRVParameterPresenter presenter; @Test public void calculateParameterTest() {
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // // Path: app/src/main/java/hrv/band/app/ui/presenter/IHRVParameterPresenter.java // public interface IHRVParameterPresenter { // List<HRVParameter> getHRVParameters(); // void calculateParameters(); // } // Path: app/src/test/java/ui/presenter/HRVParameterPresenterTest.java import org.junit.Test; import java.util.Date; import hrv.band.app.model.Measurement; import hrv.band.app.ui.presenter.HRVParameterPresenter; import hrv.band.app.ui.presenter.IHRVParameterPresenter; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; package ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 17.04.2017. */ public class HRVParameterPresenterTest { private IHRVParameterPresenter presenter; @Test public void calculateParameterTest() {
Measurement.MeasurementBuilder builder = new Measurement.MeasurementBuilder(new Date(1000), new double[]{1, 1, 1, 1, 1});
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/presenter/SettingsPresenter.java
// Path: app/src/main/java/hrv/band/app/ui/view/fragment/ISettingsView.java // public interface ISettingsView { // Activity getSettingsActivity(); // // void showSnackbar(int messageId, View.OnClickListener clickListener); // // void showAlertDialog(int titleId, int messageId); // // void startExportFragment(); // }
import android.Manifest; import android.content.pm.PackageManager; import android.os.Build; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.view.View; import hrv.band.app.R; import hrv.band.app.ui.view.fragment.ISettingsView;
package hrv.band.app.ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 15.04.2017. */ public class SettingsPresenter implements ISettingsPresenter { private static final int EXPORT_DATABASE_REQUEST_ID = 200;
// Path: app/src/main/java/hrv/band/app/ui/view/fragment/ISettingsView.java // public interface ISettingsView { // Activity getSettingsActivity(); // // void showSnackbar(int messageId, View.OnClickListener clickListener); // // void showAlertDialog(int titleId, int messageId); // // void startExportFragment(); // } // Path: app/src/main/java/hrv/band/app/ui/presenter/SettingsPresenter.java import android.Manifest; import android.content.pm.PackageManager; import android.os.Build; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.view.View; import hrv.band.app.R; import hrv.band.app.ui.view.fragment.ISettingsView; package hrv.band.app.ui.presenter; /** * Copyright (c) 2017 * Created by Thomas on 15.04.2017. */ public class SettingsPresenter implements ISettingsPresenter { private static final int EXPORT_DATABASE_REQUEST_ID = 200;
private ISettingsView settingsView;
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/adapter/StatisticValueAdapter.java
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // }
import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Locale; import hrv.HRVLibFacade; import hrv.RRData; import hrv.band.app.R; import hrv.band.app.model.Measurement; import hrv.band.app.ui.view.fragment.HistoryFragment; import hrv.calc.parameter.HRVParameter; import hrv.calc.parameter.HRVParameterEnum; import units.TimeUnit;
package hrv.band.app.ui.view.adapter; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 19.01.2017 * <p> * This adapter holds the hrv parameters to show in the {@link HistoryFragment}. */ public class StatisticValueAdapter extends BaseAdapter { /** * The context of activity holding the adapter. **/ private final Context context; /** * The hrv type to display in the fragment. **/ private final HRVParameterEnum type; /** * The hrv values to display in fragment as string. **/ private List<String> values; /** * The hrv parameters to display. **/
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // Path: app/src/main/java/hrv/band/app/ui/view/adapter/StatisticValueAdapter.java import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Locale; import hrv.HRVLibFacade; import hrv.RRData; import hrv.band.app.R; import hrv.band.app.model.Measurement; import hrv.band.app.ui.view.fragment.HistoryFragment; import hrv.calc.parameter.HRVParameter; import hrv.calc.parameter.HRVParameterEnum; import units.TimeUnit; package hrv.band.app.ui.view.adapter; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 19.01.2017 * <p> * This adapter holds the hrv parameters to show in the {@link HistoryFragment}. */ public class StatisticValueAdapter extends BaseAdapter { /** * The context of activity holding the adapter. **/ private final Context context; /** * The hrv type to display in the fragment. **/ private final HRVParameterEnum type; /** * The hrv values to display in fragment as string. **/ private List<String> values; /** * The hrv parameters to display. **/
private List<Measurement> parameters;
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/fragment/CancelMeasuringDialogFragment.java
// Path: app/src/main/java/hrv/band/app/ui/view/activity/IMainView.java // public interface IMainView { // void startActivity(Class<? extends Activity> activity); // // void startActivity(Class<? extends Activity> activity, String extraId, String extra); // // void startFeedbackDialog(); // // void startSurveyDialog(); // // Activity getMainActivity(); // // void openShareIntent(); // // void rateApp(); // // void stopMeasuring(); // // }
import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.TextView; import hrv.band.app.R; import hrv.band.app.ui.view.activity.IMainView;
package hrv.band.app.ui.view.fragment; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 19.01.2017 * <p> * This dialog allows the user to cancel the measurement. */ public class CancelMeasuringDialogFragment extends DialogFragment { public static CancelMeasuringDialogFragment newInstance() { return new CancelMeasuringDialogFragment(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); final View view = View.inflate(getActivity(), R.layout.dialog_simple_text, null); TextView textView = view.findViewById(R.id.dialog_textview); textView.setText(getResources().getString(R.string.measure_cancel_desc)); builder.setView(view) .setPositiveButton(R.string.common_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Activity activity = getActivity();
// Path: app/src/main/java/hrv/band/app/ui/view/activity/IMainView.java // public interface IMainView { // void startActivity(Class<? extends Activity> activity); // // void startActivity(Class<? extends Activity> activity, String extraId, String extra); // // void startFeedbackDialog(); // // void startSurveyDialog(); // // Activity getMainActivity(); // // void openShareIntent(); // // void rateApp(); // // void stopMeasuring(); // // } // Path: app/src/main/java/hrv/band/app/ui/view/fragment/CancelMeasuringDialogFragment.java import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.TextView; import hrv.band.app.R; import hrv.band.app.ui.view.activity.IMainView; package hrv.band.app.ui.view.fragment; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 19.01.2017 * <p> * This dialog allows the user to cancel the measurement. */ public class CancelMeasuringDialogFragment extends DialogFragment { public static CancelMeasuringDialogFragment newInstance() { return new CancelMeasuringDialogFragment(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); final View view = View.inflate(getActivity(), R.layout.dialog_simple_text, null); TextView textView = view.findViewById(R.id.dialog_textview); textView.setText(getResources().getString(R.string.measure_cancel_desc)); builder.setView(view) .setPositiveButton(R.string.common_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Activity activity = getActivity();
if (activity instanceof IMainView) {
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/activity/history/measurementstrategy/ParameterLoadMonthStrategy.java
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // }
import android.content.Context; import android.support.annotation.NonNull; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import hrv.band.app.model.Measurement;
package hrv.band.app.ui.view.activity.history.measurementstrategy; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 25.03.2017 * <p> * Loads parameter of given month. */ public class ParameterLoadMonthStrategy extends AbstractParameterLoadStrategy { public ParameterLoadMonthStrategy(Context context) { super(context); } @Override
// Path: app/src/main/java/hrv/band/app/model/Measurement.java // public class Measurement implements Parcelable { // // // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods // public static final Parcelable.Creator<Measurement> CREATOR = new Parcelable.Creator<Measurement>() { // @Override // public Measurement createFromParcel(Parcel in) { // return new Measurement(in); // } // @Override // public Measurement[] newArray(int size) { // return new Measurement[size]; // } // }; // private final Date time; // private final double[] rrIntervals; // private final double rating; // private final MeasurementCategoryAdapter.MeasureCategory category; // private final String note; // // // example constructor that takes a Parcel and gives you an object populated with it's values // private Measurement(Parcel in) { // this.time = (Date) in.readValue(getClass().getClassLoader()); // // int rrIntervalLength= in.readInt(); // this.rrIntervals = new double[rrIntervalLength]; // in.readDoubleArray(rrIntervals); // this.rating = in.readDouble(); // this.category = (MeasurementCategoryAdapter.MeasureCategory) in.readSerializable(); // this.note = in.readString(); // } // // public Measurement(MeasurementBuilder builder) { // this.time = builder.time; // this.rrIntervals = builder.rrIntervals; // this.rating = builder.rating; // this.category = builder.category; // this.note = builder.note; // } // // /** // * Creates a new HRVParameter-Object from a ALLHRVIndiceCalculator object // * At the time the data unit can not be changed according to the incoming data // * thats why the data has to be converted to the units given in the HRVValue class // * // * @param time Time when the measurement began // * @param rr Original RR-Data // * @return New Measurement object // */ // public static MeasurementBuilder from(Date time, double[] rr) { // // return new MeasurementBuilder(time, rr); // } // // @Override // public int describeContents() { // return 0; // } // // // write your object's data to the passed-in Parcel // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeValue(time); // out.writeInt(rrIntervals.length); // out.writeDoubleArray(rrIntervals); // out.writeDouble(rating); // out.writeSerializable(category); // out.writeString(note); // } // // public Date getTime() { // return time; // } // // public double[] getRRIntervals() { // return rrIntervals; // } // // public double getRating() { // return rating; // } // // public MeasurementCategoryAdapter.MeasureCategory getCategory() { // if (category == null) { // return MeasurementCategoryAdapter.MeasureCategory.GENERAL; // } // return category; // } // // public String getNote() { // if (note == null) { // return ""; // } // return note; // } // // @Override // public boolean equals(Object other) // { // if(other == null) { // return false; // } // if(other == this) { // return true; // } // if(!(other instanceof Measurement)) { // return false; // } // // Measurement param = (Measurement)other; // // return param.getTime().equals(this.getTime()); // } // // @Override // public int hashCode() { // return Objects.hashCode(getTime()); // } // // /** // * Class builder for {@link Measurement}. // */ // public static class MeasurementBuilder { // private Date time; // private double[] rrIntervals; // private double rating; // private MeasurementCategoryAdapter.MeasureCategory category; // private String note; // // public MeasurementBuilder(Date time, double[] rrIntervals) { // this.time = time; // this.rrIntervals = rrIntervals; // } // // public MeasurementBuilder(Measurement parameter) { // this.time = parameter.getTime(); // this.rrIntervals = parameter.getRRIntervals(); // } // // // public MeasurementBuilder rating(double rating) { // this.rating = rating; // return this; // } // public MeasurementBuilder category(MeasurementCategoryAdapter.MeasureCategory category) { // this.category = category; // return this; // } // public MeasurementBuilder note(String note) { // this.note = note; // return this; // } // // public Measurement build() { // return new Measurement(this); // } // } // } // Path: app/src/main/java/hrv/band/app/ui/view/activity/history/measurementstrategy/ParameterLoadMonthStrategy.java import android.content.Context; import android.support.annotation.NonNull; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import hrv.band.app.model.Measurement; package hrv.band.app.ui.view.activity.history.measurementstrategy; /** * Copyright (c) 2017 * Created by Thomas Czogalik on 25.03.2017 * <p> * Loads parameter of given month. */ public class ParameterLoadMonthStrategy extends AbstractParameterLoadStrategy { public ParameterLoadMonthStrategy(Context context) { super(context); } @Override
public List<Measurement> loadParameter(Date date) {
HRVBand/hrv-band
app/src/main/java/hrv/band/app/ui/view/fragment/ExportFragment.java
// Path: app/src/main/java/hrv/band/app/ui/presenter/ExportPresenter.java // public class ExportPresenter implements IExportPresenter { // private IExportView view; // // public ExportPresenter(IExportView view) { // this.view = view; // } // // @Override // public void exportDatabase() { // Context context = view.getExportContext(); // HRVSQLController sql = new HRVSQLController(context); // try { // CharSequence text; // if (!sql.exportDB()) { // text = context.getResources().getText(R.string.sentence_export_failed); // } else { // text = context.getResources().getText(R.string.sentence_export_worked); // } // view.showToast(text); // } catch (IOException e) { // Log.e(e.getClass().getName(), "IOException", e); // } // } // }
import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.widget.TextView; import android.widget.Toast; import hrv.band.app.R; import hrv.band.app.ui.presenter.ExportPresenter; import hrv.band.app.ui.presenter.IExportPresenter;
package hrv.band.app.ui.view.fragment; /** * Copyright (c) 2017 * Created by Julian Martin on 19.01.2017 * <p> * Dialog asking the user to export his data. */ public class ExportFragment extends DialogFragment implements IExportView { private IExportPresenter presenter; public static ExportFragment newInstance() { return new ExportFragment(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
// Path: app/src/main/java/hrv/band/app/ui/presenter/ExportPresenter.java // public class ExportPresenter implements IExportPresenter { // private IExportView view; // // public ExportPresenter(IExportView view) { // this.view = view; // } // // @Override // public void exportDatabase() { // Context context = view.getExportContext(); // HRVSQLController sql = new HRVSQLController(context); // try { // CharSequence text; // if (!sql.exportDB()) { // text = context.getResources().getText(R.string.sentence_export_failed); // } else { // text = context.getResources().getText(R.string.sentence_export_worked); // } // view.showToast(text); // } catch (IOException e) { // Log.e(e.getClass().getName(), "IOException", e); // } // } // } // Path: app/src/main/java/hrv/band/app/ui/view/fragment/ExportFragment.java import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.widget.TextView; import android.widget.Toast; import hrv.band.app.R; import hrv.band.app.ui.presenter.ExportPresenter; import hrv.band.app.ui.presenter.IExportPresenter; package hrv.band.app.ui.view.fragment; /** * Copyright (c) 2017 * Created by Julian Martin on 19.01.2017 * <p> * Dialog asking the user to export his data. */ public class ExportFragment extends DialogFragment implements IExportView { private IExportPresenter presenter; public static ExportFragment newInstance() { return new ExportFragment(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
presenter = new ExportPresenter(this);
tangqifa/Common-App-Architecture
app/src/main/java/com/kejiwen/architecture/adapter/ClassroomAdapter.java
// Path: ListViewHelper_Library/src/com/shizhefei/view/listviewhelper/IDataAdapter.java // public interface IDataAdapter<DATA> extends ListAdapter { // // public abstract void setData(DATA data, boolean isRefresh); // // public abstract DATA getData(); // // public void notifyDataSetChanged(); // // } // // Path: app/src/main/java/com/kejiwen/architecture/activity/CommonWebViewActivity.java // public class CommonWebViewActivity extends BaseActivity { // private final static String TAG = "CommonWebViewActivity"; // // private WebView mWebView; // private String mUrl; // // @Override // protected void onCreate(Bundle savedInstanceState) { // setContentView(R.layout.common_webview); // super.onCreate(savedInstanceState); // mTitleBar.setBackButton(R.mipmap.titlebar_back_arrow, this); // // mUrl = getIntent().getStringExtra("url"); // mWebView = (WebView) findViewById(R.id.webview); // if (!TextUtils.isEmpty(mUrl)) mWebView.loadUrl(mUrl); // mWebView.getSettings().setJavaScriptEnabled(true);// 设置使用够执行JS脚本 // mWebView.setWebViewClient(new WebViewClient() { // @Override // public boolean shouldOverrideUrlLoading(WebView view, String url) { // mTitleBar.setTitle(view.getTitle()); // view.loadUrl(url);// 使用当前WebView处理跳转 // return true;// true表示此事件在此处被处理,不需要再广播 // } // // @Override // public void onPageFinished(WebView view, String url) { // super.onPageFinished(view, url); // mTitleBar.setTitle(view.getTitle()); // } // // @Override // public void onPageStarted(WebView view, String url, Bitmap favicon) { // super.onPageStarted(view, url, favicon); // mTitleBar.setTitle(view.getTitle()); // } // // @Override // // 转向错误时的处理 // public void onReceivedError(WebView view, int errorCode, // String description, String failingUrl) { // } // }); // } // // // 默认点回退键,会退出Activity,需监听按键操作,使回退在WebView内发生 // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // mWebView.goBack(); // return true; // } // return super.onKeyDown(keyCode, event); // } // // @Override // public void onBackStack() { // if (mWebView.canGoBack()) { // mWebView.goBack(); // } else { // finish(); // } // // } // // @Override // protected int getTitleBarRes() { // return R.id.titlebar; // } // } // // Path: app/src/main/java/com/kejiwen/architecture/model/ClassroomItem.java // public class ClassroomItem { // private String title; // private String date; // private String url; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // }
import java.util.ArrayList; import java.util.List; import com.shizhefei.view.listviewhelper.IDataAdapter; import com.kejiwen.architecture.R; import com.kejiwen.architecture.activity.CommonWebViewActivity; import com.kejiwen.architecture.model.ClassroomItem; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView;
} @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ClassroomItem item = mClassroomItems.get(position); ItemHolder holder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.classroom_listview_item, parent, false); holder = new ItemHolder(); holder.dateTv = (TextView) convertView.findViewById(R.id.classroom_list_item_date); holder.titleTv = (TextView) convertView.findViewById(R.id.classroom_list_item_title); convertView.setTag(holder); } else { holder = (ItemHolder) convertView.getTag(); } holder.titleTv.setText(mClassroomItems.get(position).getTitle()); holder.dateTv.setText(mClassroomItems.get(position).getDate()); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
// Path: ListViewHelper_Library/src/com/shizhefei/view/listviewhelper/IDataAdapter.java // public interface IDataAdapter<DATA> extends ListAdapter { // // public abstract void setData(DATA data, boolean isRefresh); // // public abstract DATA getData(); // // public void notifyDataSetChanged(); // // } // // Path: app/src/main/java/com/kejiwen/architecture/activity/CommonWebViewActivity.java // public class CommonWebViewActivity extends BaseActivity { // private final static String TAG = "CommonWebViewActivity"; // // private WebView mWebView; // private String mUrl; // // @Override // protected void onCreate(Bundle savedInstanceState) { // setContentView(R.layout.common_webview); // super.onCreate(savedInstanceState); // mTitleBar.setBackButton(R.mipmap.titlebar_back_arrow, this); // // mUrl = getIntent().getStringExtra("url"); // mWebView = (WebView) findViewById(R.id.webview); // if (!TextUtils.isEmpty(mUrl)) mWebView.loadUrl(mUrl); // mWebView.getSettings().setJavaScriptEnabled(true);// 设置使用够执行JS脚本 // mWebView.setWebViewClient(new WebViewClient() { // @Override // public boolean shouldOverrideUrlLoading(WebView view, String url) { // mTitleBar.setTitle(view.getTitle()); // view.loadUrl(url);// 使用当前WebView处理跳转 // return true;// true表示此事件在此处被处理,不需要再广播 // } // // @Override // public void onPageFinished(WebView view, String url) { // super.onPageFinished(view, url); // mTitleBar.setTitle(view.getTitle()); // } // // @Override // public void onPageStarted(WebView view, String url, Bitmap favicon) { // super.onPageStarted(view, url, favicon); // mTitleBar.setTitle(view.getTitle()); // } // // @Override // // 转向错误时的处理 // public void onReceivedError(WebView view, int errorCode, // String description, String failingUrl) { // } // }); // } // // // 默认点回退键,会退出Activity,需监听按键操作,使回退在WebView内发生 // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // mWebView.goBack(); // return true; // } // return super.onKeyDown(keyCode, event); // } // // @Override // public void onBackStack() { // if (mWebView.canGoBack()) { // mWebView.goBack(); // } else { // finish(); // } // // } // // @Override // protected int getTitleBarRes() { // return R.id.titlebar; // } // } // // Path: app/src/main/java/com/kejiwen/architecture/model/ClassroomItem.java // public class ClassroomItem { // private String title; // private String date; // private String url; // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // } // Path: app/src/main/java/com/kejiwen/architecture/adapter/ClassroomAdapter.java import java.util.ArrayList; import java.util.List; import com.shizhefei.view.listviewhelper.IDataAdapter; import com.kejiwen.architecture.R; import com.kejiwen.architecture.activity.CommonWebViewActivity; import com.kejiwen.architecture.model.ClassroomItem; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { final ClassroomItem item = mClassroomItems.get(position); ItemHolder holder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.classroom_listview_item, parent, false); holder = new ItemHolder(); holder.dateTv = (TextView) convertView.findViewById(R.id.classroom_list_item_date); holder.titleTv = (TextView) convertView.findViewById(R.id.classroom_list_item_title); convertView.setTag(holder); } else { holder = (ItemHolder) convertView.getTag(); } holder.titleTv.setText(mClassroomItems.get(position).getTitle()); holder.dateTv.setText(mClassroomItems.get(position).getDate()); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) {
Intent it = new Intent(mContext, CommonWebViewActivity.class);
tangqifa/Common-App-Architecture
app/src/main/java/com/kejiwen/architecture/customview/TitleBar.java
// Path: app/src/main/java/com/kejiwen/architecture/listener/OnBackStackListener.java // public interface OnBackStackListener { // public void onBackStack(); // }
import android.app.Activity; import android.content.Context; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.TextView; import com.kejiwen.architecture.R; import com.kejiwen.architecture.listener.OnBackStackListener;
package com.kejiwen.architecture.customview; public final class TitleBar { private Context mContext; private View mRoot; private ImageButton mBackButton; private TextView mTitle; private ImageButton mSettingButton; public TitleBar(Activity activity, int titleId) { this(activity.getWindow().getDecorView(), titleId); mContext = activity; } public TitleBar(View view, int titleId) { mRoot = view.findViewById(titleId); mBackButton = (ImageButton) mRoot.findViewById(R.id.back); mTitle = (TextView) mRoot.findViewById(R.id.title); mSettingButton = (ImageButton) mRoot.findViewById(R.id.settings); } public void setTitleVisibility(boolean visibility) { if (visibility) { mRoot.setVisibility(View.VISIBLE); } else { mRoot.setVisibility(View.GONE); } } public void setTitle(CharSequence title) { mTitle.setText(title); } public void setTitle(int titleRes) { setTitle(mContext.getText(titleRes)); }
// Path: app/src/main/java/com/kejiwen/architecture/listener/OnBackStackListener.java // public interface OnBackStackListener { // public void onBackStack(); // } // Path: app/src/main/java/com/kejiwen/architecture/customview/TitleBar.java import android.app.Activity; import android.content.Context; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.TextView; import com.kejiwen.architecture.R; import com.kejiwen.architecture.listener.OnBackStackListener; package com.kejiwen.architecture.customview; public final class TitleBar { private Context mContext; private View mRoot; private ImageButton mBackButton; private TextView mTitle; private ImageButton mSettingButton; public TitleBar(Activity activity, int titleId) { this(activity.getWindow().getDecorView(), titleId); mContext = activity; } public TitleBar(View view, int titleId) { mRoot = view.findViewById(titleId); mBackButton = (ImageButton) mRoot.findViewById(R.id.back); mTitle = (TextView) mRoot.findViewById(R.id.title); mSettingButton = (ImageButton) mRoot.findViewById(R.id.settings); } public void setTitleVisibility(boolean visibility) { if (visibility) { mRoot.setVisibility(View.VISIBLE); } else { mRoot.setVisibility(View.GONE); } } public void setTitle(CharSequence title) { mTitle.setText(title); } public void setTitle(int titleRes) { setTitle(mContext.getText(titleRes)); }
public void setBackButton(int resid, final OnBackStackListener listener) {
tangqifa/Common-App-Architecture
app/src/main/java/com/kejiwen/architecture/activity/BaseActivity.java
// Path: app/src/main/java/com/kejiwen/architecture/customview/TitleBar.java // public final class TitleBar { // private Context mContext; // // private View mRoot; // private ImageButton mBackButton; // private TextView mTitle; // private ImageButton mSettingButton; // // public TitleBar(Activity activity, int titleId) { // this(activity.getWindow().getDecorView(), titleId); // mContext = activity; // } // // public TitleBar(View view, int titleId) { // mRoot = view.findViewById(titleId); // mBackButton = (ImageButton) mRoot.findViewById(R.id.back); // mTitle = (TextView) mRoot.findViewById(R.id.title); // mSettingButton = (ImageButton) mRoot.findViewById(R.id.settings); // } // // public void setTitleVisibility(boolean visibility) { // if (visibility) { // mRoot.setVisibility(View.VISIBLE); // } else { // mRoot.setVisibility(View.GONE); // } // } // // public void setTitle(CharSequence title) { // mTitle.setText(title); // } // // public void setTitle(int titleRes) { // setTitle(mContext.getText(titleRes)); // } // // // public void setBackButton(int resid, final OnBackStackListener listener) { // if (resid > 0) { // mBackButton.setImageResource(resid); // } // if (listener != null) { // mBackButton.setOnClickListener( // new OnClickListener() { // @Override // public void onClick(View v) { // listener.onBackStack(); // } // }); // mBackButton.setFocusable(true); // } // } // // public ImageButton setSettingButton(int resid, OnClickListener listener) { // if (resid > 0) { // mSettingButton.setImageResource(resid); // } // if (listener != null) { // mSettingButton.setOnClickListener(listener); // mSettingButton.setVisibility(View.VISIBLE); // } else { // mSettingButton.setVisibility(View.GONE); // } // return mSettingButton; // } // // // public void setBackground(int id) { // mRoot.setBackgroundResource(id); // } // // public void setBackgroundColor(int color) { // mRoot.setBackgroundColor(color); // } // // } // // Path: app/src/main/java/com/kejiwen/architecture/listener/OnBackStackListener.java // public interface OnBackStackListener { // public void onBackStack(); // }
import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Window; import android.view.WindowManager; import com.readystatesoftware.systembartint.SystemBarTintManager; import com.kejiwen.architecture.R; import com.kejiwen.architecture.customview.TitleBar; import com.kejiwen.architecture.listener.OnBackStackListener;
package com.kejiwen.architecture.activity; public abstract class BaseActivity extends FragmentActivity implements OnBackStackListener{ private final static String TAG = "BaseActivity";
// Path: app/src/main/java/com/kejiwen/architecture/customview/TitleBar.java // public final class TitleBar { // private Context mContext; // // private View mRoot; // private ImageButton mBackButton; // private TextView mTitle; // private ImageButton mSettingButton; // // public TitleBar(Activity activity, int titleId) { // this(activity.getWindow().getDecorView(), titleId); // mContext = activity; // } // // public TitleBar(View view, int titleId) { // mRoot = view.findViewById(titleId); // mBackButton = (ImageButton) mRoot.findViewById(R.id.back); // mTitle = (TextView) mRoot.findViewById(R.id.title); // mSettingButton = (ImageButton) mRoot.findViewById(R.id.settings); // } // // public void setTitleVisibility(boolean visibility) { // if (visibility) { // mRoot.setVisibility(View.VISIBLE); // } else { // mRoot.setVisibility(View.GONE); // } // } // // public void setTitle(CharSequence title) { // mTitle.setText(title); // } // // public void setTitle(int titleRes) { // setTitle(mContext.getText(titleRes)); // } // // // public void setBackButton(int resid, final OnBackStackListener listener) { // if (resid > 0) { // mBackButton.setImageResource(resid); // } // if (listener != null) { // mBackButton.setOnClickListener( // new OnClickListener() { // @Override // public void onClick(View v) { // listener.onBackStack(); // } // }); // mBackButton.setFocusable(true); // } // } // // public ImageButton setSettingButton(int resid, OnClickListener listener) { // if (resid > 0) { // mSettingButton.setImageResource(resid); // } // if (listener != null) { // mSettingButton.setOnClickListener(listener); // mSettingButton.setVisibility(View.VISIBLE); // } else { // mSettingButton.setVisibility(View.GONE); // } // return mSettingButton; // } // // // public void setBackground(int id) { // mRoot.setBackgroundResource(id); // } // // public void setBackgroundColor(int color) { // mRoot.setBackgroundColor(color); // } // // } // // Path: app/src/main/java/com/kejiwen/architecture/listener/OnBackStackListener.java // public interface OnBackStackListener { // public void onBackStack(); // } // Path: app/src/main/java/com/kejiwen/architecture/activity/BaseActivity.java import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Window; import android.view.WindowManager; import com.readystatesoftware.systembartint.SystemBarTintManager; import com.kejiwen.architecture.R; import com.kejiwen.architecture.customview.TitleBar; import com.kejiwen.architecture.listener.OnBackStackListener; package com.kejiwen.architecture.activity; public abstract class BaseActivity extends FragmentActivity implements OnBackStackListener{ private final static String TAG = "BaseActivity";
protected TitleBar mTitleBar;
tangqifa/Common-App-Architecture
app/src/main/java/com/kejiwen/architecture/utils/LogHelperDebug.java
// Path: app/src/main/java/com/kejiwen/architecture/constant/FeatureConfig.java // public class FeatureConfig { // // // Global control on debug log // public static final boolean DEBUG_LOG = true; // // // Switch for online server // public static final boolean ONLINE_SERVER = true; // // public static final String OFFLINE_SERVER_URL = "http://p.api.tongbaotu.test/"; // public static final String ONLINE_SERVER_URL = "http://api2.tongbaotu.com/"; // // public static final String API_HOST_NAME = ONLINE_SERVER ? ONLINE_SERVER_URL : OFFLINE_SERVER_URL; // }
import android.util.Log; import com.kejiwen.architecture.constant.FeatureConfig; import java.io.PrintWriter; import java.io.StringWriter;
package com.kejiwen.architecture.utils; public class LogHelperDebug { public static final String TAG = "com.kejiwen.architecture"; public static void d(String subTag, String msg) {
// Path: app/src/main/java/com/kejiwen/architecture/constant/FeatureConfig.java // public class FeatureConfig { // // // Global control on debug log // public static final boolean DEBUG_LOG = true; // // // Switch for online server // public static final boolean ONLINE_SERVER = true; // // public static final String OFFLINE_SERVER_URL = "http://p.api.tongbaotu.test/"; // public static final String ONLINE_SERVER_URL = "http://api2.tongbaotu.com/"; // // public static final String API_HOST_NAME = ONLINE_SERVER ? ONLINE_SERVER_URL : OFFLINE_SERVER_URL; // } // Path: app/src/main/java/com/kejiwen/architecture/utils/LogHelperDebug.java import android.util.Log; import com.kejiwen.architecture.constant.FeatureConfig; import java.io.PrintWriter; import java.io.StringWriter; package com.kejiwen.architecture.utils; public class LogHelperDebug { public static final String TAG = "com.kejiwen.architecture"; public static void d(String subTag, String msg) {
if (FeatureConfig.DEBUG_LOG)
tangqifa/Common-App-Architecture
app/src/main/java/com/kejiwen/architecture/activity/LoginActivity.java
// Path: app/src/main/java/com/kejiwen/architecture/constant/Constants.java // public class Constants { // // public static final String KEY_LOGIN_USER_NAME = "key_login_user_name"; // public static final String KEY_LOGIN_PASSWORD = "key_login_password"; // public static final String KEY_LOGIN_USER_NAME_VALUE = "key_login_user_name_value"; // public static final String KEY_LOGIN_PASSWORD_VALUE = "key_login_password_value"; // } // // Path: app/src/main/java/com/kejiwen/architecture/constant/FeatureConfig.java // public class FeatureConfig { // // // Global control on debug log // public static final boolean DEBUG_LOG = true; // // // Switch for online server // public static final boolean ONLINE_SERVER = true; // // public static final String OFFLINE_SERVER_URL = "http://p.api.tongbaotu.test/"; // public static final String ONLINE_SERVER_URL = "http://api2.tongbaotu.com/"; // // public static final String API_HOST_NAME = ONLINE_SERVER ? ONLINE_SERVER_URL : OFFLINE_SERVER_URL; // } // // Path: app/src/main/java/com/kejiwen/architecture/utils/SharePreferenceUtils.java // public class SharePreferenceUtils { // // public static void setLongPref(Context context, String key, // Long value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putLong(key, value).commit(); // } // // public static long getLongPref(Context context, String key, // long defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getLong(key, defaultValue); // } // // public static void setIntPref(Context context, String key, // int value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putInt(key, value).commit(); // } // // public static int getIntPref(Context context, String key, // int defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getInt(key, defaultValue); // } // // public static void setStringPref(Context context, String key, // String value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putString(key, value).commit(); // } // // public static String getStringPref(Context context, String key, // String defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getString(key, defaultValue); // } // // public static boolean getBooleanPref(Context context, // String key, boolean defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getBoolean(key, defaultValue); // } // // public static void setBooleanPref(Context context, String key, // boolean value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putBoolean(key, value).commit(); // } // // public static void removePref(Context context, String key) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().remove(key).commit(); // } // // public static void setStringSecPref(Context context, String key, // String value) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // preferences.put(key, value); // } // // public static String getStringSecPref(Context context, String key, // String defaultValue) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // return preferences.getString(key); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.kejiwen.architecture.R; import com.kejiwen.architecture.constant.Constants; import com.kejiwen.architecture.constant.FeatureConfig; import com.kejiwen.architecture.utils.SharePreferenceUtils;
private String mUserNameStr; private String mPasswordStr; private Button mLoginBtn; private InputMethodManager mImm; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.login); super.onCreate(savedInstanceState); initView(); initData(); } private void initView() { mTitleBar.setTitle("登录"); mUserName = (EditText) findViewById(R.id.login_name); mPassword = (EditText) findViewById(R.id.login_password); mForgetPassword = (TextView) findViewById(R.id.login_forget_password); mForgetPassword.setOnClickListener(this); mLoginBtn = (Button) findViewById(R.id.login_btn); mLoginBtn.setOnClickListener(this); } @Override protected int getTitleBarRes() { return R.id.titlebar; } private void initData() {
// Path: app/src/main/java/com/kejiwen/architecture/constant/Constants.java // public class Constants { // // public static final String KEY_LOGIN_USER_NAME = "key_login_user_name"; // public static final String KEY_LOGIN_PASSWORD = "key_login_password"; // public static final String KEY_LOGIN_USER_NAME_VALUE = "key_login_user_name_value"; // public static final String KEY_LOGIN_PASSWORD_VALUE = "key_login_password_value"; // } // // Path: app/src/main/java/com/kejiwen/architecture/constant/FeatureConfig.java // public class FeatureConfig { // // // Global control on debug log // public static final boolean DEBUG_LOG = true; // // // Switch for online server // public static final boolean ONLINE_SERVER = true; // // public static final String OFFLINE_SERVER_URL = "http://p.api.tongbaotu.test/"; // public static final String ONLINE_SERVER_URL = "http://api2.tongbaotu.com/"; // // public static final String API_HOST_NAME = ONLINE_SERVER ? ONLINE_SERVER_URL : OFFLINE_SERVER_URL; // } // // Path: app/src/main/java/com/kejiwen/architecture/utils/SharePreferenceUtils.java // public class SharePreferenceUtils { // // public static void setLongPref(Context context, String key, // Long value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putLong(key, value).commit(); // } // // public static long getLongPref(Context context, String key, // long defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getLong(key, defaultValue); // } // // public static void setIntPref(Context context, String key, // int value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putInt(key, value).commit(); // } // // public static int getIntPref(Context context, String key, // int defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getInt(key, defaultValue); // } // // public static void setStringPref(Context context, String key, // String value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putString(key, value).commit(); // } // // public static String getStringPref(Context context, String key, // String defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getString(key, defaultValue); // } // // public static boolean getBooleanPref(Context context, // String key, boolean defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getBoolean(key, defaultValue); // } // // public static void setBooleanPref(Context context, String key, // boolean value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putBoolean(key, value).commit(); // } // // public static void removePref(Context context, String key) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().remove(key).commit(); // } // // public static void setStringSecPref(Context context, String key, // String value) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // preferences.put(key, value); // } // // public static String getStringSecPref(Context context, String key, // String defaultValue) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // return preferences.getString(key); // } // } // Path: app/src/main/java/com/kejiwen/architecture/activity/LoginActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.kejiwen.architecture.R; import com.kejiwen.architecture.constant.Constants; import com.kejiwen.architecture.constant.FeatureConfig; import com.kejiwen.architecture.utils.SharePreferenceUtils; private String mUserNameStr; private String mPasswordStr; private Button mLoginBtn; private InputMethodManager mImm; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.login); super.onCreate(savedInstanceState); initView(); initData(); } private void initView() { mTitleBar.setTitle("登录"); mUserName = (EditText) findViewById(R.id.login_name); mPassword = (EditText) findViewById(R.id.login_password); mForgetPassword = (TextView) findViewById(R.id.login_forget_password); mForgetPassword.setOnClickListener(this); mLoginBtn = (Button) findViewById(R.id.login_btn); mLoginBtn.setOnClickListener(this); } @Override protected int getTitleBarRes() { return R.id.titlebar; } private void initData() {
String name = SharePreferenceUtils.getStringSecPref(this, Constants.KEY_LOGIN_USER_NAME, "");
tangqifa/Common-App-Architecture
app/src/main/java/com/kejiwen/architecture/activity/LoginActivity.java
// Path: app/src/main/java/com/kejiwen/architecture/constant/Constants.java // public class Constants { // // public static final String KEY_LOGIN_USER_NAME = "key_login_user_name"; // public static final String KEY_LOGIN_PASSWORD = "key_login_password"; // public static final String KEY_LOGIN_USER_NAME_VALUE = "key_login_user_name_value"; // public static final String KEY_LOGIN_PASSWORD_VALUE = "key_login_password_value"; // } // // Path: app/src/main/java/com/kejiwen/architecture/constant/FeatureConfig.java // public class FeatureConfig { // // // Global control on debug log // public static final boolean DEBUG_LOG = true; // // // Switch for online server // public static final boolean ONLINE_SERVER = true; // // public static final String OFFLINE_SERVER_URL = "http://p.api.tongbaotu.test/"; // public static final String ONLINE_SERVER_URL = "http://api2.tongbaotu.com/"; // // public static final String API_HOST_NAME = ONLINE_SERVER ? ONLINE_SERVER_URL : OFFLINE_SERVER_URL; // } // // Path: app/src/main/java/com/kejiwen/architecture/utils/SharePreferenceUtils.java // public class SharePreferenceUtils { // // public static void setLongPref(Context context, String key, // Long value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putLong(key, value).commit(); // } // // public static long getLongPref(Context context, String key, // long defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getLong(key, defaultValue); // } // // public static void setIntPref(Context context, String key, // int value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putInt(key, value).commit(); // } // // public static int getIntPref(Context context, String key, // int defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getInt(key, defaultValue); // } // // public static void setStringPref(Context context, String key, // String value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putString(key, value).commit(); // } // // public static String getStringPref(Context context, String key, // String defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getString(key, defaultValue); // } // // public static boolean getBooleanPref(Context context, // String key, boolean defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getBoolean(key, defaultValue); // } // // public static void setBooleanPref(Context context, String key, // boolean value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putBoolean(key, value).commit(); // } // // public static void removePref(Context context, String key) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().remove(key).commit(); // } // // public static void setStringSecPref(Context context, String key, // String value) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // preferences.put(key, value); // } // // public static String getStringSecPref(Context context, String key, // String defaultValue) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // return preferences.getString(key); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.kejiwen.architecture.R; import com.kejiwen.architecture.constant.Constants; import com.kejiwen.architecture.constant.FeatureConfig; import com.kejiwen.architecture.utils.SharePreferenceUtils;
private String mUserNameStr; private String mPasswordStr; private Button mLoginBtn; private InputMethodManager mImm; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.login); super.onCreate(savedInstanceState); initView(); initData(); } private void initView() { mTitleBar.setTitle("登录"); mUserName = (EditText) findViewById(R.id.login_name); mPassword = (EditText) findViewById(R.id.login_password); mForgetPassword = (TextView) findViewById(R.id.login_forget_password); mForgetPassword.setOnClickListener(this); mLoginBtn = (Button) findViewById(R.id.login_btn); mLoginBtn.setOnClickListener(this); } @Override protected int getTitleBarRes() { return R.id.titlebar; } private void initData() {
// Path: app/src/main/java/com/kejiwen/architecture/constant/Constants.java // public class Constants { // // public static final String KEY_LOGIN_USER_NAME = "key_login_user_name"; // public static final String KEY_LOGIN_PASSWORD = "key_login_password"; // public static final String KEY_LOGIN_USER_NAME_VALUE = "key_login_user_name_value"; // public static final String KEY_LOGIN_PASSWORD_VALUE = "key_login_password_value"; // } // // Path: app/src/main/java/com/kejiwen/architecture/constant/FeatureConfig.java // public class FeatureConfig { // // // Global control on debug log // public static final boolean DEBUG_LOG = true; // // // Switch for online server // public static final boolean ONLINE_SERVER = true; // // public static final String OFFLINE_SERVER_URL = "http://p.api.tongbaotu.test/"; // public static final String ONLINE_SERVER_URL = "http://api2.tongbaotu.com/"; // // public static final String API_HOST_NAME = ONLINE_SERVER ? ONLINE_SERVER_URL : OFFLINE_SERVER_URL; // } // // Path: app/src/main/java/com/kejiwen/architecture/utils/SharePreferenceUtils.java // public class SharePreferenceUtils { // // public static void setLongPref(Context context, String key, // Long value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putLong(key, value).commit(); // } // // public static long getLongPref(Context context, String key, // long defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getLong(key, defaultValue); // } // // public static void setIntPref(Context context, String key, // int value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putInt(key, value).commit(); // } // // public static int getIntPref(Context context, String key, // int defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getInt(key, defaultValue); // } // // public static void setStringPref(Context context, String key, // String value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putString(key, value).commit(); // } // // public static String getStringPref(Context context, String key, // String defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getString(key, defaultValue); // } // // public static boolean getBooleanPref(Context context, // String key, boolean defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getBoolean(key, defaultValue); // } // // public static void setBooleanPref(Context context, String key, // boolean value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putBoolean(key, value).commit(); // } // // public static void removePref(Context context, String key) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().remove(key).commit(); // } // // public static void setStringSecPref(Context context, String key, // String value) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // preferences.put(key, value); // } // // public static String getStringSecPref(Context context, String key, // String defaultValue) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // return preferences.getString(key); // } // } // Path: app/src/main/java/com/kejiwen/architecture/activity/LoginActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.kejiwen.architecture.R; import com.kejiwen.architecture.constant.Constants; import com.kejiwen.architecture.constant.FeatureConfig; import com.kejiwen.architecture.utils.SharePreferenceUtils; private String mUserNameStr; private String mPasswordStr; private Button mLoginBtn; private InputMethodManager mImm; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.login); super.onCreate(savedInstanceState); initView(); initData(); } private void initView() { mTitleBar.setTitle("登录"); mUserName = (EditText) findViewById(R.id.login_name); mPassword = (EditText) findViewById(R.id.login_password); mForgetPassword = (TextView) findViewById(R.id.login_forget_password); mForgetPassword.setOnClickListener(this); mLoginBtn = (Button) findViewById(R.id.login_btn); mLoginBtn.setOnClickListener(this); } @Override protected int getTitleBarRes() { return R.id.titlebar; } private void initData() {
String name = SharePreferenceUtils.getStringSecPref(this, Constants.KEY_LOGIN_USER_NAME, "");
tangqifa/Common-App-Architecture
app/src/main/java/com/kejiwen/architecture/activity/LoginActivity.java
// Path: app/src/main/java/com/kejiwen/architecture/constant/Constants.java // public class Constants { // // public static final String KEY_LOGIN_USER_NAME = "key_login_user_name"; // public static final String KEY_LOGIN_PASSWORD = "key_login_password"; // public static final String KEY_LOGIN_USER_NAME_VALUE = "key_login_user_name_value"; // public static final String KEY_LOGIN_PASSWORD_VALUE = "key_login_password_value"; // } // // Path: app/src/main/java/com/kejiwen/architecture/constant/FeatureConfig.java // public class FeatureConfig { // // // Global control on debug log // public static final boolean DEBUG_LOG = true; // // // Switch for online server // public static final boolean ONLINE_SERVER = true; // // public static final String OFFLINE_SERVER_URL = "http://p.api.tongbaotu.test/"; // public static final String ONLINE_SERVER_URL = "http://api2.tongbaotu.com/"; // // public static final String API_HOST_NAME = ONLINE_SERVER ? ONLINE_SERVER_URL : OFFLINE_SERVER_URL; // } // // Path: app/src/main/java/com/kejiwen/architecture/utils/SharePreferenceUtils.java // public class SharePreferenceUtils { // // public static void setLongPref(Context context, String key, // Long value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putLong(key, value).commit(); // } // // public static long getLongPref(Context context, String key, // long defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getLong(key, defaultValue); // } // // public static void setIntPref(Context context, String key, // int value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putInt(key, value).commit(); // } // // public static int getIntPref(Context context, String key, // int defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getInt(key, defaultValue); // } // // public static void setStringPref(Context context, String key, // String value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putString(key, value).commit(); // } // // public static String getStringPref(Context context, String key, // String defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getString(key, defaultValue); // } // // public static boolean getBooleanPref(Context context, // String key, boolean defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getBoolean(key, defaultValue); // } // // public static void setBooleanPref(Context context, String key, // boolean value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putBoolean(key, value).commit(); // } // // public static void removePref(Context context, String key) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().remove(key).commit(); // } // // public static void setStringSecPref(Context context, String key, // String value) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // preferences.put(key, value); // } // // public static String getStringSecPref(Context context, String key, // String defaultValue) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // return preferences.getString(key); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.kejiwen.architecture.R; import com.kejiwen.architecture.constant.Constants; import com.kejiwen.architecture.constant.FeatureConfig; import com.kejiwen.architecture.utils.SharePreferenceUtils;
@Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.login); super.onCreate(savedInstanceState); initView(); initData(); } private void initView() { mTitleBar.setTitle("登录"); mUserName = (EditText) findViewById(R.id.login_name); mPassword = (EditText) findViewById(R.id.login_password); mForgetPassword = (TextView) findViewById(R.id.login_forget_password); mForgetPassword.setOnClickListener(this); mLoginBtn = (Button) findViewById(R.id.login_btn); mLoginBtn.setOnClickListener(this); } @Override protected int getTitleBarRes() { return R.id.titlebar; } private void initData() { String name = SharePreferenceUtils.getStringSecPref(this, Constants.KEY_LOGIN_USER_NAME, ""); mUserName.setText(name); if (!TextUtils.isEmpty(name)) { mUserName.setSelection(name.length()); mPassword.requestFocus(); }
// Path: app/src/main/java/com/kejiwen/architecture/constant/Constants.java // public class Constants { // // public static final String KEY_LOGIN_USER_NAME = "key_login_user_name"; // public static final String KEY_LOGIN_PASSWORD = "key_login_password"; // public static final String KEY_LOGIN_USER_NAME_VALUE = "key_login_user_name_value"; // public static final String KEY_LOGIN_PASSWORD_VALUE = "key_login_password_value"; // } // // Path: app/src/main/java/com/kejiwen/architecture/constant/FeatureConfig.java // public class FeatureConfig { // // // Global control on debug log // public static final boolean DEBUG_LOG = true; // // // Switch for online server // public static final boolean ONLINE_SERVER = true; // // public static final String OFFLINE_SERVER_URL = "http://p.api.tongbaotu.test/"; // public static final String ONLINE_SERVER_URL = "http://api2.tongbaotu.com/"; // // public static final String API_HOST_NAME = ONLINE_SERVER ? ONLINE_SERVER_URL : OFFLINE_SERVER_URL; // } // // Path: app/src/main/java/com/kejiwen/architecture/utils/SharePreferenceUtils.java // public class SharePreferenceUtils { // // public static void setLongPref(Context context, String key, // Long value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putLong(key, value).commit(); // } // // public static long getLongPref(Context context, String key, // long defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getLong(key, defaultValue); // } // // public static void setIntPref(Context context, String key, // int value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putInt(key, value).commit(); // } // // public static int getIntPref(Context context, String key, // int defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getInt(key, defaultValue); // } // // public static void setStringPref(Context context, String key, // String value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putString(key, value).commit(); // } // // public static String getStringPref(Context context, String key, // String defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getString(key, defaultValue); // } // // public static boolean getBooleanPref(Context context, // String key, boolean defaultValue) { // return PreferenceManager.getDefaultSharedPreferences( // context).getBoolean(key, defaultValue); // } // // public static void setBooleanPref(Context context, String key, // boolean value) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().putBoolean(key, value).commit(); // } // // public static void removePref(Context context, String key) { // PreferenceManager.getDefaultSharedPreferences(context) // .edit().remove(key).commit(); // } // // public static void setStringSecPref(Context context, String key, // String value) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // preferences.put(key, value); // } // // public static String getStringSecPref(Context context, String key, // String defaultValue) { // SecurePreferences preferences = SecurePreferences.getInstance(context, true); // return preferences.getString(key); // } // } // Path: app/src/main/java/com/kejiwen/architecture/activity/LoginActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.kejiwen.architecture.R; import com.kejiwen.architecture.constant.Constants; import com.kejiwen.architecture.constant.FeatureConfig; import com.kejiwen.architecture.utils.SharePreferenceUtils; @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.login); super.onCreate(savedInstanceState); initView(); initData(); } private void initView() { mTitleBar.setTitle("登录"); mUserName = (EditText) findViewById(R.id.login_name); mPassword = (EditText) findViewById(R.id.login_password); mForgetPassword = (TextView) findViewById(R.id.login_forget_password); mForgetPassword.setOnClickListener(this); mLoginBtn = (Button) findViewById(R.id.login_btn); mLoginBtn.setOnClickListener(this); } @Override protected int getTitleBarRes() { return R.id.titlebar; } private void initData() { String name = SharePreferenceUtils.getStringSecPref(this, Constants.KEY_LOGIN_USER_NAME, ""); mUserName.setText(name); if (!TextUtils.isEmpty(name)) { mUserName.setSelection(name.length()); mPassword.requestFocus(); }
if (FeatureConfig.DEBUG_LOG) {
tangqifa/Common-App-Architecture
app/src/main/java/com/kejiwen/architecture/customview/SlideShowView.java
// Path: app/src/main/java/com/kejiwen/architecture/listener/OnPageClickListener.java // public interface OnPageClickListener { // public void onPageClick(int position); // }
import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import com.kejiwen.architecture.R; import com.kejiwen.architecture.listener.OnPageClickListener;
package com.kejiwen.architecture.customview; @SuppressLint("HandlerLeak") public class SlideShowView extends FrameLayout { private List<ImageView> imageViewsList; private List<ImageView> dotViewsList; private LinearLayout mLinearLayout;
// Path: app/src/main/java/com/kejiwen/architecture/listener/OnPageClickListener.java // public interface OnPageClickListener { // public void onPageClick(int position); // } // Path: app/src/main/java/com/kejiwen/architecture/customview/SlideShowView.java import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.os.Parcelable; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import com.kejiwen.architecture.R; import com.kejiwen.architecture.listener.OnPageClickListener; package com.kejiwen.architecture.customview; @SuppressLint("HandlerLeak") public class SlideShowView extends FrameLayout { private List<ImageView> imageViewsList; private List<ImageView> dotViewsList; private LinearLayout mLinearLayout;
private OnPageClickListener mPageOnClickListener;
felipebravom/AffectiveTweets
src/main/java/weka/filters/unsupervised/attribute/TweetToSentiStrengthFeatureVector.java
// Path: src/main/java/affective/core/SentiStrengthEvaluator.java // public class SentiStrengthEvaluator extends LexiconEvaluator { // // // /** For serialization. */ // private static final long serialVersionUID = -2094228012480778199L; // // /** The SentiStrengh object. */ // protected transient SentiStrength sentiStrength; // // // /** // * initializes the Object // * // * @param file the file with the lexicon // * @param name the prefix for all the attributes calculated from this lexicon // */ // public SentiStrengthEvaluator(String file,String name) { // super(file,name); // // // // this.featureNames=new ArrayList<String>(); // this.featureNames.add(name+"-posScore"); // this.featureNames.add(name+"-negScore"); // // } // // // /* (non-Javadoc) // * @see affective.core.LexiconEvaluator#processDict() // */ // @Override // public void processDict() throws IOException { // this.sentiStrength = new SentiStrength(); // String sentiParams[] = {"sentidata", this.path, "trinary"}; // this.sentiStrength.initialise(sentiParams); // } // // // // /* (non-Javadoc) // * @see affective.core.LexiconEvaluator#evaluateTweet(java.util.List) // */ // @Override // public Map<String, Double> evaluateTweet(List<String> tokens) { // // Map<String, Double> strengthScores = new HashMap<String, Double>(); // // String sentence = ""; // for (int i = 0; i < tokens.size(); i++) { // sentence += tokens.get(i); // if (i < tokens.size() - 1) { // sentence += "+"; // } // } // // String result = sentiStrength.computeSentimentScores(sentence); // // String[] values = result.split(" "); // strengthScores.put(name+"-posScore", Double.parseDouble(values[0])); // strengthScores.put(name+"-negScore", Double.parseDouble(values[1])); // // return strengthScores; // } // // }
import weka.core.OptionMetadata; import weka.core.SparseInstance; import weka.core.TechnicalInformation; import weka.core.WekaPackageManager; import weka.core.TechnicalInformation.Type; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import affective.core.SentiStrengthEvaluator; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances;
att.add(new Attribute("SentiStrength-negScore")); Instances result = new Instances(inputFormat.relationName(), att, 0); // set the class index result.setClassIndex(inputFormat.classIndex()); return result; } /* (non-Javadoc) * @see weka.filters.SimpleFilter#process(weka.core.Instances) */ @Override protected Instances process(Instances instances) throws Exception { // set upper value for text index m_textIndex.setUpper(instances.numAttributes() - 1); Instances result = getOutputFormat(); // reference to the content of the message, users index start from zero Attribute attrCont = instances.attribute(this.m_textIndex.getIndex()); // SentiStrength is re-intialized in each batch as it is not serializable
// Path: src/main/java/affective/core/SentiStrengthEvaluator.java // public class SentiStrengthEvaluator extends LexiconEvaluator { // // // /** For serialization. */ // private static final long serialVersionUID = -2094228012480778199L; // // /** The SentiStrengh object. */ // protected transient SentiStrength sentiStrength; // // // /** // * initializes the Object // * // * @param file the file with the lexicon // * @param name the prefix for all the attributes calculated from this lexicon // */ // public SentiStrengthEvaluator(String file,String name) { // super(file,name); // // // // this.featureNames=new ArrayList<String>(); // this.featureNames.add(name+"-posScore"); // this.featureNames.add(name+"-negScore"); // // } // // // /* (non-Javadoc) // * @see affective.core.LexiconEvaluator#processDict() // */ // @Override // public void processDict() throws IOException { // this.sentiStrength = new SentiStrength(); // String sentiParams[] = {"sentidata", this.path, "trinary"}; // this.sentiStrength.initialise(sentiParams); // } // // // // /* (non-Javadoc) // * @see affective.core.LexiconEvaluator#evaluateTweet(java.util.List) // */ // @Override // public Map<String, Double> evaluateTweet(List<String> tokens) { // // Map<String, Double> strengthScores = new HashMap<String, Double>(); // // String sentence = ""; // for (int i = 0; i < tokens.size(); i++) { // sentence += tokens.get(i); // if (i < tokens.size() - 1) { // sentence += "+"; // } // } // // String result = sentiStrength.computeSentimentScores(sentence); // // String[] values = result.split(" "); // strengthScores.put(name+"-posScore", Double.parseDouble(values[0])); // strengthScores.put(name+"-negScore", Double.parseDouble(values[1])); // // return strengthScores; // } // // } // Path: src/main/java/weka/filters/unsupervised/attribute/TweetToSentiStrengthFeatureVector.java import weka.core.OptionMetadata; import weka.core.SparseInstance; import weka.core.TechnicalInformation; import weka.core.WekaPackageManager; import weka.core.TechnicalInformation.Type; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import affective.core.SentiStrengthEvaluator; import weka.core.Attribute; import weka.core.Instance; import weka.core.Instances; att.add(new Attribute("SentiStrength-negScore")); Instances result = new Instances(inputFormat.relationName(), att, 0); // set the class index result.setClassIndex(inputFormat.classIndex()); return result; } /* (non-Javadoc) * @see weka.filters.SimpleFilter#process(weka.core.Instances) */ @Override protected Instances process(Instances instances) throws Exception { // set upper value for text index m_textIndex.setUpper(instances.numAttributes() - 1); Instances result = getOutputFormat(); // reference to the content of the message, users index start from zero Attribute attrCont = instances.attribute(this.m_textIndex.getIndex()); // SentiStrength is re-intialized in each batch as it is not serializable
SentiStrengthEvaluator sentiStrengthEvaluator=new SentiStrengthEvaluator(
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/servlet/MockAutomationTestRunServlet.java
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import org.openqa.grid.internal.ProxySet; import org.openqa.grid.internal.Registry; import com.rmn.qa.RequestMatcher; import com.rmn.qa.aws.VmManager;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.servlet; public class MockAutomationTestRunServlet extends AutomationTestRunServlet { private ProxySet proxySet;
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/test/java/com/rmn/qa/servlet/MockAutomationTestRunServlet.java import org.openqa.grid.internal.ProxySet; import org.openqa.grid.internal.Registry; import com.rmn.qa.RequestMatcher; import com.rmn.qa.aws.VmManager; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.servlet; public class MockAutomationTestRunServlet extends AutomationTestRunServlet { private ProxySet proxySet;
public MockAutomationTestRunServlet(Registry registry, boolean initThreads, VmManager ec2,RequestMatcher requestMatcher){
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/servlet/MockAutomationTestRunServlet.java
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import org.openqa.grid.internal.ProxySet; import org.openqa.grid.internal.Registry; import com.rmn.qa.RequestMatcher; import com.rmn.qa.aws.VmManager;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.servlet; public class MockAutomationTestRunServlet extends AutomationTestRunServlet { private ProxySet proxySet;
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/test/java/com/rmn/qa/servlet/MockAutomationTestRunServlet.java import org.openqa.grid.internal.ProxySet; import org.openqa.grid.internal.Registry; import com.rmn.qa.RequestMatcher; import com.rmn.qa.aws.VmManager; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.servlet; public class MockAutomationTestRunServlet extends AutomationTestRunServlet { private ProxySet proxySet;
public MockAutomationTestRunServlet(Registry registry, boolean initThreads, VmManager ec2,RequestMatcher requestMatcher){
RetailMeNot/SeleniumGridScaler
src/main/java/com/rmn/qa/task/AutomationNodeCleanupTask.java
// Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.*; import com.rmn.qa.aws.VmManager; import org.openqa.grid.internal.ProxySet; import org.openqa.grid.internal.RemoteProxy; import org.openqa.grid.internal.TestSlot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; /** * Cleanup task which moves {@link com.rmn.qa.AutomationDynamicNode nodes} into the correct status depending on their lifecycle. The purpose of this * task is to terminate nodes once current load is sufficient to allow for the node to be safely shutdown * @author mhardin */ public class AutomationNodeCleanupTask extends AbstractAutomationCleanupTask { private static final Logger log = LoggerFactory.getLogger(AutomationNodeCleanupTask.class);
// Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/main/java/com/rmn/qa/task/AutomationNodeCleanupTask.java import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.*; import com.rmn.qa.aws.VmManager; import org.openqa.grid.internal.ProxySet; import org.openqa.grid.internal.RemoteProxy; import org.openqa.grid.internal.TestSlot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; /** * Cleanup task which moves {@link com.rmn.qa.AutomationDynamicNode nodes} into the correct status depending on their lifecycle. The purpose of this * task is to terminate nodes once current load is sufficient to allow for the node to be safely shutdown * @author mhardin */ public class AutomationNodeCleanupTask extends AbstractAutomationCleanupTask { private static final Logger log = LoggerFactory.getLogger(AutomationNodeCleanupTask.class);
private VmManager ec2;
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/task/MockAutomationHubCleanupTask.java
// Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import org.openqa.grid.internal.ProxySet; import java.util.Date; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; // We're extending the task so we can override the created date behavior public class MockAutomationHubCleanupTask extends AutomationHubCleanupTask { private Object createdDate; private ProxySet proxySet;
// Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/test/java/com/rmn/qa/task/MockAutomationHubCleanupTask.java import org.openqa.grid.internal.ProxySet; import java.util.Date; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; // We're extending the task so we can override the created date behavior public class MockAutomationHubCleanupTask extends AutomationHubCleanupTask { private Object createdDate; private ProxySet proxySet;
public MockAutomationHubCleanupTask(RegistryRetriever retrieveContext, VmManager ec2, String instanceId) {
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/task/MockAutomationHubCleanupTask.java
// Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import org.openqa.grid.internal.ProxySet; import java.util.Date; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; // We're extending the task so we can override the created date behavior public class MockAutomationHubCleanupTask extends AutomationHubCleanupTask { private Object createdDate; private ProxySet proxySet;
// Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/test/java/com/rmn/qa/task/MockAutomationHubCleanupTask.java import org.openqa.grid.internal.ProxySet; import java.util.Date; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; // We're extending the task so we can override the created date behavior public class MockAutomationHubCleanupTask extends AutomationHubCleanupTask { private Object createdDate; private ProxySet proxySet;
public MockAutomationHubCleanupTask(RegistryRetriever retrieveContext, VmManager ec2, String instanceId) {
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/AbstractAutomationCleanupTaskTest.java
// Path: src/main/java/com/rmn/qa/task/AbstractAutomationCleanupTask.java // public abstract class AbstractAutomationCleanupTask extends Thread { // // private static final Logger log = LoggerFactory.getLogger(AbstractAutomationCleanupTask.class); // // protected RegistryRetriever registryRetriever; // private Throwable t; // // public AbstractAutomationCleanupTask(RegistryRetriever registryRetriever) { // this.registryRetriever = registryRetriever; // } // // @Override // public void run() { // try{ // this.doWork(); // }catch(Throwable t) { // this.t = t; // log.error(String.format("Error executing cleanup thread [%s]: %s", getDescription(), t), t); // } // } // // /** // * Performs the work of the task // */ // public abstract void doWork(); // // /** // * Returns the description of the task // * @return // */ // public abstract String getDescription(); // // /** // * Returns the exception of this task if any was encountered // * @return // */ // public Throwable getThrowable() { // return t; // } // // }
import org.junit.Test; import com.rmn.qa.task.AbstractAutomationCleanupTask; import junit.framework.Assert;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa; /** * Created by mhardin on 4/25/14. */ public class AbstractAutomationCleanupTaskTest { @Test public void testExceptionHandled() { TestTask task = new TestTask(null); task.run(); Assert.assertEquals("Correct exception should have been thrown",task.getThrowable(),task.re); }
// Path: src/main/java/com/rmn/qa/task/AbstractAutomationCleanupTask.java // public abstract class AbstractAutomationCleanupTask extends Thread { // // private static final Logger log = LoggerFactory.getLogger(AbstractAutomationCleanupTask.class); // // protected RegistryRetriever registryRetriever; // private Throwable t; // // public AbstractAutomationCleanupTask(RegistryRetriever registryRetriever) { // this.registryRetriever = registryRetriever; // } // // @Override // public void run() { // try{ // this.doWork(); // }catch(Throwable t) { // this.t = t; // log.error(String.format("Error executing cleanup thread [%s]: %s", getDescription(), t), t); // } // } // // /** // * Performs the work of the task // */ // public abstract void doWork(); // // /** // * Returns the description of the task // * @return // */ // public abstract String getDescription(); // // /** // * Returns the exception of this task if any was encountered // * @return // */ // public Throwable getThrowable() { // return t; // } // // } // Path: src/test/java/com/rmn/qa/AbstractAutomationCleanupTaskTest.java import org.junit.Test; import com.rmn.qa.task.AbstractAutomationCleanupTask; import junit.framework.Assert; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa; /** * Created by mhardin on 4/25/14. */ public class AbstractAutomationCleanupTaskTest { @Test public void testExceptionHandled() { TestTask task = new TestTask(null); task.run(); Assert.assertEquals("Correct exception should have been thrown",task.getThrowable(),task.re); }
private static class TestTask extends AbstractAutomationCleanupTask {
RetailMeNot/SeleniumGridScaler
src/main/java/com/rmn/qa/task/AutomationReaperTask.java
// Path: src/main/java/com/rmn/qa/AutomationContext.java // public class AutomationContext { // // private static final Logger log = LoggerFactory.getLogger(AutomationContext.class); // private static final int DEFAULT_MAX_THREAD_COUNT = 150; // private static AutomationRunContext context = new AutomationRunContext(); // // // Singleton to maintain a context object // // /** // * Returns the singleton {@link com.rmn.qa.AutomationRunContext context} instance // * @return // */ // public static AutomationRunContext getContext() { // return AutomationContext.context; // } // // /** // * Clears out the previous context. Used for unit testing // */ // public static void refreshContext() { // AutomationContext.context = new AutomationRunContext(); // } // // static { // String totalNodeCount = System.getProperty("totalNodeCount"); // // Default to 150 if node count was not passed in // if(totalNodeCount == null) { // getContext().setTotalNodeCount(AutomationContext.DEFAULT_MAX_THREAD_COUNT); // log.warn("Defaulting node count to " + AutomationContext.DEFAULT_MAX_THREAD_COUNT); // } else { // getContext().setTotalNodeCount(Integer.parseInt(totalNodeCount)); // } // } // // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationContext; import com.rmn.qa.AutomationUtils; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; import java.util.List;
package com.rmn.qa.task; public class AutomationReaperTask extends AbstractAutomationCleanupTask { private static final Logger log = LoggerFactory.getLogger(AutomationReaperTask.class); @VisibleForTesting static final String NAME = "VM Reaper Task";
// Path: src/main/java/com/rmn/qa/AutomationContext.java // public class AutomationContext { // // private static final Logger log = LoggerFactory.getLogger(AutomationContext.class); // private static final int DEFAULT_MAX_THREAD_COUNT = 150; // private static AutomationRunContext context = new AutomationRunContext(); // // // Singleton to maintain a context object // // /** // * Returns the singleton {@link com.rmn.qa.AutomationRunContext context} instance // * @return // */ // public static AutomationRunContext getContext() { // return AutomationContext.context; // } // // /** // * Clears out the previous context. Used for unit testing // */ // public static void refreshContext() { // AutomationContext.context = new AutomationRunContext(); // } // // static { // String totalNodeCount = System.getProperty("totalNodeCount"); // // Default to 150 if node count was not passed in // if(totalNodeCount == null) { // getContext().setTotalNodeCount(AutomationContext.DEFAULT_MAX_THREAD_COUNT); // log.warn("Defaulting node count to " + AutomationContext.DEFAULT_MAX_THREAD_COUNT); // } else { // getContext().setTotalNodeCount(Integer.parseInt(totalNodeCount)); // } // } // // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/main/java/com/rmn/qa/task/AutomationReaperTask.java import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationContext; import com.rmn.qa.AutomationUtils; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; import java.util.List; package com.rmn.qa.task; public class AutomationReaperTask extends AbstractAutomationCleanupTask { private static final Logger log = LoggerFactory.getLogger(AutomationReaperTask.class); @VisibleForTesting static final String NAME = "VM Reaper Task";
private VmManager ec2;
RetailMeNot/SeleniumGridScaler
src/main/java/com/rmn/qa/task/AutomationReaperTask.java
// Path: src/main/java/com/rmn/qa/AutomationContext.java // public class AutomationContext { // // private static final Logger log = LoggerFactory.getLogger(AutomationContext.class); // private static final int DEFAULT_MAX_THREAD_COUNT = 150; // private static AutomationRunContext context = new AutomationRunContext(); // // // Singleton to maintain a context object // // /** // * Returns the singleton {@link com.rmn.qa.AutomationRunContext context} instance // * @return // */ // public static AutomationRunContext getContext() { // return AutomationContext.context; // } // // /** // * Clears out the previous context. Used for unit testing // */ // public static void refreshContext() { // AutomationContext.context = new AutomationRunContext(); // } // // static { // String totalNodeCount = System.getProperty("totalNodeCount"); // // Default to 150 if node count was not passed in // if(totalNodeCount == null) { // getContext().setTotalNodeCount(AutomationContext.DEFAULT_MAX_THREAD_COUNT); // log.warn("Defaulting node count to " + AutomationContext.DEFAULT_MAX_THREAD_COUNT); // } else { // getContext().setTotalNodeCount(Integer.parseInt(totalNodeCount)); // } // } // // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationContext; import com.rmn.qa.AutomationUtils; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; import java.util.List;
package com.rmn.qa.task; public class AutomationReaperTask extends AbstractAutomationCleanupTask { private static final Logger log = LoggerFactory.getLogger(AutomationReaperTask.class); @VisibleForTesting static final String NAME = "VM Reaper Task"; private VmManager ec2; /** * Constructs a registry task with the specified context retrieval mechanism * @param registryRetriever Represents the retrieval mechanism you wish to use */
// Path: src/main/java/com/rmn/qa/AutomationContext.java // public class AutomationContext { // // private static final Logger log = LoggerFactory.getLogger(AutomationContext.class); // private static final int DEFAULT_MAX_THREAD_COUNT = 150; // private static AutomationRunContext context = new AutomationRunContext(); // // // Singleton to maintain a context object // // /** // * Returns the singleton {@link com.rmn.qa.AutomationRunContext context} instance // * @return // */ // public static AutomationRunContext getContext() { // return AutomationContext.context; // } // // /** // * Clears out the previous context. Used for unit testing // */ // public static void refreshContext() { // AutomationContext.context = new AutomationRunContext(); // } // // static { // String totalNodeCount = System.getProperty("totalNodeCount"); // // Default to 150 if node count was not passed in // if(totalNodeCount == null) { // getContext().setTotalNodeCount(AutomationContext.DEFAULT_MAX_THREAD_COUNT); // log.warn("Defaulting node count to " + AutomationContext.DEFAULT_MAX_THREAD_COUNT); // } else { // getContext().setTotalNodeCount(Integer.parseInt(totalNodeCount)); // } // } // // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/main/java/com/rmn/qa/task/AutomationReaperTask.java import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationContext; import com.rmn.qa.AutomationUtils; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; import java.util.List; package com.rmn.qa.task; public class AutomationReaperTask extends AbstractAutomationCleanupTask { private static final Logger log = LoggerFactory.getLogger(AutomationReaperTask.class); @VisibleForTesting static final String NAME = "VM Reaper Task"; private VmManager ec2; /** * Constructs a registry task with the specified context retrieval mechanism * @param registryRetriever Represents the retrieval mechanism you wish to use */
public AutomationReaperTask(RegistryRetriever registryRetriever,VmManager ec2) {
RetailMeNot/SeleniumGridScaler
src/main/java/com/rmn/qa/task/AutomationReaperTask.java
// Path: src/main/java/com/rmn/qa/AutomationContext.java // public class AutomationContext { // // private static final Logger log = LoggerFactory.getLogger(AutomationContext.class); // private static final int DEFAULT_MAX_THREAD_COUNT = 150; // private static AutomationRunContext context = new AutomationRunContext(); // // // Singleton to maintain a context object // // /** // * Returns the singleton {@link com.rmn.qa.AutomationRunContext context} instance // * @return // */ // public static AutomationRunContext getContext() { // return AutomationContext.context; // } // // /** // * Clears out the previous context. Used for unit testing // */ // public static void refreshContext() { // AutomationContext.context = new AutomationRunContext(); // } // // static { // String totalNodeCount = System.getProperty("totalNodeCount"); // // Default to 150 if node count was not passed in // if(totalNodeCount == null) { // getContext().setTotalNodeCount(AutomationContext.DEFAULT_MAX_THREAD_COUNT); // log.warn("Defaulting node count to " + AutomationContext.DEFAULT_MAX_THREAD_COUNT); // } else { // getContext().setTotalNodeCount(Integer.parseInt(totalNodeCount)); // } // } // // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationContext; import com.rmn.qa.AutomationUtils; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; import java.util.List;
package com.rmn.qa.task; public class AutomationReaperTask extends AbstractAutomationCleanupTask { private static final Logger log = LoggerFactory.getLogger(AutomationReaperTask.class); @VisibleForTesting static final String NAME = "VM Reaper Task"; private VmManager ec2; /** * Constructs a registry task with the specified context retrieval mechanism * @param registryRetriever Represents the retrieval mechanism you wish to use */ public AutomationReaperTask(RegistryRetriever registryRetriever,VmManager ec2) { super(registryRetriever); this.ec2 = ec2; } @Override public void doWork() { log.info("Running " + AutomationReaperTask.NAME); DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); Filter filter = new Filter("tag:LaunchSource"); filter.withValues("SeleniumGridScalerPlugin"); describeInstancesRequest.withFilters(filter); List<Reservation> reservations = ec2.describeInstances(describeInstancesRequest); for(Reservation reservation : reservations) { for(Instance instance : reservation.getInstances()) { // Look for orphaned nodes
// Path: src/main/java/com/rmn/qa/AutomationContext.java // public class AutomationContext { // // private static final Logger log = LoggerFactory.getLogger(AutomationContext.class); // private static final int DEFAULT_MAX_THREAD_COUNT = 150; // private static AutomationRunContext context = new AutomationRunContext(); // // // Singleton to maintain a context object // // /** // * Returns the singleton {@link com.rmn.qa.AutomationRunContext context} instance // * @return // */ // public static AutomationRunContext getContext() { // return AutomationContext.context; // } // // /** // * Clears out the previous context. Used for unit testing // */ // public static void refreshContext() { // AutomationContext.context = new AutomationRunContext(); // } // // static { // String totalNodeCount = System.getProperty("totalNodeCount"); // // Default to 150 if node count was not passed in // if(totalNodeCount == null) { // getContext().setTotalNodeCount(AutomationContext.DEFAULT_MAX_THREAD_COUNT); // log.warn("Defaulting node count to " + AutomationContext.DEFAULT_MAX_THREAD_COUNT); // } else { // getContext().setTotalNodeCount(Integer.parseInt(totalNodeCount)); // } // } // // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/main/java/com/rmn/qa/task/AutomationReaperTask.java import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationContext; import com.rmn.qa.AutomationUtils; import com.rmn.qa.RegistryRetriever; import com.rmn.qa.aws.VmManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; import java.util.List; package com.rmn.qa.task; public class AutomationReaperTask extends AbstractAutomationCleanupTask { private static final Logger log = LoggerFactory.getLogger(AutomationReaperTask.class); @VisibleForTesting static final String NAME = "VM Reaper Task"; private VmManager ec2; /** * Constructs a registry task with the specified context retrieval mechanism * @param registryRetriever Represents the retrieval mechanism you wish to use */ public AutomationReaperTask(RegistryRetriever registryRetriever,VmManager ec2) { super(registryRetriever); this.ec2 = ec2; } @Override public void doWork() { log.info("Running " + AutomationReaperTask.NAME); DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); Filter filter = new Filter("tag:LaunchSource"); filter.withValues("SeleniumGridScalerPlugin"); describeInstancesRequest.withFilters(filter); List<Reservation> reservations = ec2.describeInstances(describeInstancesRequest); for(Reservation reservation : reservations) { for(Instance instance : reservation.getInstances()) { // Look for orphaned nodes
Date threshold = AutomationUtils.modifyDate(new Date(),-30, Calendar.MINUTE);
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/task/MockAutomationNodeCleanupTask.java
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import com.rmn.qa.aws.VmManager; import org.openqa.grid.internal.ProxySet; import com.rmn.qa.RequestMatcher; import com.rmn.qa.RegistryRetriever;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; public class MockAutomationNodeCleanupTask extends AutomationNodeCleanupTask { private ProxySet proxySet;
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/test/java/com/rmn/qa/task/MockAutomationNodeCleanupTask.java import com.rmn.qa.aws.VmManager; import org.openqa.grid.internal.ProxySet; import com.rmn.qa.RequestMatcher; import com.rmn.qa.RegistryRetriever; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; public class MockAutomationNodeCleanupTask extends AutomationNodeCleanupTask { private ProxySet proxySet;
public MockAutomationNodeCleanupTask(RegistryRetriever retrieveContext, VmManager ec2, RequestMatcher requestMatcher) {
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/task/MockAutomationNodeCleanupTask.java
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import com.rmn.qa.aws.VmManager; import org.openqa.grid.internal.ProxySet; import com.rmn.qa.RequestMatcher; import com.rmn.qa.RegistryRetriever;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; public class MockAutomationNodeCleanupTask extends AutomationNodeCleanupTask { private ProxySet proxySet;
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/test/java/com/rmn/qa/task/MockAutomationNodeCleanupTask.java import com.rmn.qa.aws.VmManager; import org.openqa.grid.internal.ProxySet; import com.rmn.qa.RequestMatcher; import com.rmn.qa.RegistryRetriever; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; public class MockAutomationNodeCleanupTask extends AutomationNodeCleanupTask { private ProxySet proxySet;
public MockAutomationNodeCleanupTask(RegistryRetriever retrieveContext, VmManager ec2, RequestMatcher requestMatcher) {
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/task/MockAutomationNodeCleanupTask.java
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // }
import com.rmn.qa.aws.VmManager; import org.openqa.grid.internal.ProxySet; import com.rmn.qa.RequestMatcher; import com.rmn.qa.RegistryRetriever;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; public class MockAutomationNodeCleanupTask extends AutomationNodeCleanupTask { private ProxySet proxySet;
// Path: src/main/java/com/rmn/qa/RequestMatcher.java // public interface RequestMatcher { // // /** // * Returns the number of free threads which satisfy the conditions of the parameters // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumFreeThreadsForParameters(ProxySet proxySet, AutomationRunRequest runRequest); // // /** // * Returns the number of in progress tests which match the request passed in // * @param proxySet Set of current registered proxy objects // * @param runRequest Request used to match against // * @return // */ // int getNumInProgressTests(ProxySet proxySet, AutomationRunRequest runRequest); // // } // // Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // // Path: src/main/java/com/rmn/qa/aws/VmManager.java // public interface VmManager { // // /** // * Launches the specified instances // * @param uuid UUID of the requesting test run // * @param os OS of the requesting test run // * @param browser Browser of the requesting test run // * @param hubHostName Hub host name for the nodes to register with // * @param nodeCount Number of nodes to be started // * @param maxSessions Number of max sessions per node // * @return // */ // // TODO Refactor into AutomationRunRequest // List<Instance> launchNodes(String uuid, String os, String browser, String hubHostName, int nodeCount, int maxSessions) throws NodesCouldNotBeStartedException; // // /** // * Terminates the specified instance // * @param instanceId // */ // // TODO Rename to be node or instance in the name // boolean terminateInstance(String instanceId); // // /** // * Returns a list of reservations as defined in the {@link com.amazonaws.services.ec2.model.DescribeInstancesRequest DescribeInstancesRequest} // * @param describeInstancesRequest // * @return // */ // List<Reservation> describeInstances(DescribeInstancesRequest describeInstancesRequest); // } // Path: src/test/java/com/rmn/qa/task/MockAutomationNodeCleanupTask.java import com.rmn.qa.aws.VmManager; import org.openqa.grid.internal.ProxySet; import com.rmn.qa.RequestMatcher; import com.rmn.qa.RegistryRetriever; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; public class MockAutomationNodeCleanupTask extends AutomationNodeCleanupTask { private ProxySet proxySet;
public MockAutomationNodeCleanupTask(RegistryRetriever retrieveContext, VmManager ec2, RequestMatcher requestMatcher) {
RetailMeNot/SeleniumGridScaler
src/main/java/com/rmn/qa/task/AbstractAutomationCleanupTask.java
// Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // }
import com.rmn.qa.RegistryRetriever; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; /** * Base task class that has exception/running handling for other tasks to extend with their * own implementations * @author mhardin */ public abstract class AbstractAutomationCleanupTask extends Thread { private static final Logger log = LoggerFactory.getLogger(AbstractAutomationCleanupTask.class);
// Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // Path: src/main/java/com/rmn/qa/task/AbstractAutomationCleanupTask.java import com.rmn.qa.RegistryRetriever; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; /** * Base task class that has exception/running handling for other tasks to extend with their * own implementations * @author mhardin */ public abstract class AbstractAutomationCleanupTask extends Thread { private static final Logger log = LoggerFactory.getLogger(AbstractAutomationCleanupTask.class);
protected RegistryRetriever registryRetriever;
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/aws/VmManagerTest.java
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // }
import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.rmn.qa.AutomationConstants; import com.rmn.qa.NodesCouldNotBeStartedException; import junit.framework.Assert; import org.apache.commons.collections.CollectionUtils; import org.junit.After; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.aws; public class VmManagerTest { @After public void clear() {
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // } // Path: src/test/java/com/rmn/qa/aws/VmManagerTest.java import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.rmn.qa.AutomationConstants; import com.rmn.qa.NodesCouldNotBeStartedException; import junit.framework.Assert; import org.apache.commons.collections.CollectionUtils; import org.junit.After; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.aws; public class VmManagerTest { @After public void clear() {
System.clearProperty(AutomationConstants.AWS_ACCESS_KEY);
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/aws/VmManagerTest.java
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // }
import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.rmn.qa.AutomationConstants; import com.rmn.qa.NodesCouldNotBeStartedException; import junit.framework.Assert; import org.apache.commons.collections.CollectionUtils; import org.junit.After; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties;
String accessKey = "foo",privateKey = "bar"; properties.setProperty(AutomationConstants.AWS_ACCESS_KEY,accessKey); properties.setProperty(AutomationConstants.AWS_PRIVATE_KEY,privateKey); String region = "east"; AwsVmManager AwsVmManager = new AwsVmManager(client,properties,region); BasicAWSCredentials credentials = AwsVmManager.getCredentials(); Assert.assertEquals("Access key IDs should match",accessKey,credentials.getAWSAccessKeyId()); Assert.assertEquals("Access key IDs should match",privateKey,credentials.getAWSSecretKey()); } @Test // Test if System property access/private keys have priority over the property value ones public void testSystemPropertyPrecedence() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); Properties properties = new Properties(); String accessKey = "foo",privateKey = "bar"; System.setProperty(AutomationConstants.AWS_ACCESS_KEY, accessKey); System.setProperty(AutomationConstants.AWS_PRIVATE_KEY, privateKey); properties.setProperty(AutomationConstants.AWS_ACCESS_KEY, "gibberish"); properties.setProperty(AutomationConstants.AWS_PRIVATE_KEY,"moreGibberish"); String region = "east"; AwsVmManager AwsVmManager = new com.rmn.qa.aws.AwsVmManager(client,properties,region); BasicAWSCredentials credentials = AwsVmManager.getCredentials(); Assert.assertEquals("Access key IDs should match", accessKey, credentials.getAWSAccessKeyId()); Assert.assertEquals("Access key IDs should match", privateKey, credentials.getAWSSecretKey()); } @Test // Happy path test flow for launching nodes
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // } // Path: src/test/java/com/rmn/qa/aws/VmManagerTest.java import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.rmn.qa.AutomationConstants; import com.rmn.qa.NodesCouldNotBeStartedException; import junit.framework.Assert; import org.apache.commons.collections.CollectionUtils; import org.junit.After; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; String accessKey = "foo",privateKey = "bar"; properties.setProperty(AutomationConstants.AWS_ACCESS_KEY,accessKey); properties.setProperty(AutomationConstants.AWS_PRIVATE_KEY,privateKey); String region = "east"; AwsVmManager AwsVmManager = new AwsVmManager(client,properties,region); BasicAWSCredentials credentials = AwsVmManager.getCredentials(); Assert.assertEquals("Access key IDs should match",accessKey,credentials.getAWSAccessKeyId()); Assert.assertEquals("Access key IDs should match",privateKey,credentials.getAWSSecretKey()); } @Test // Test if System property access/private keys have priority over the property value ones public void testSystemPropertyPrecedence() { MockAmazonEc2Client client = new MockAmazonEc2Client(null); Properties properties = new Properties(); String accessKey = "foo",privateKey = "bar"; System.setProperty(AutomationConstants.AWS_ACCESS_KEY, accessKey); System.setProperty(AutomationConstants.AWS_PRIVATE_KEY, privateKey); properties.setProperty(AutomationConstants.AWS_ACCESS_KEY, "gibberish"); properties.setProperty(AutomationConstants.AWS_PRIVATE_KEY,"moreGibberish"); String region = "east"; AwsVmManager AwsVmManager = new com.rmn.qa.aws.AwsVmManager(client,properties,region); BasicAWSCredentials credentials = AwsVmManager.getCredentials(); Assert.assertEquals("Access key IDs should match", accessKey, credentials.getAWSAccessKeyId()); Assert.assertEquals("Access key IDs should match", privateKey, credentials.getAWSSecretKey()); } @Test // Happy path test flow for launching nodes
public void testLaunchNodes() throws NodesCouldNotBeStartedException{
RetailMeNot/SeleniumGridScaler
src/test/java/com/rmn/qa/task/MockAutomationNodeRegistryTask.java
// Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // }
import com.rmn.qa.RegistryRetriever; import org.openqa.grid.internal.ProxySet;
/* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; /** * Created by mhardin on 4/24/14. */ public class MockAutomationNodeRegistryTask extends AutomationNodeRegistryTask { private ProxySet proxySet;
// Path: src/main/java/com/rmn/qa/RegistryRetriever.java // public interface RegistryRetriever { // // /** // * Retrieves a Selenium Registry // * @return // */ // Registry retrieveRegistry(); // // } // Path: src/test/java/com/rmn/qa/task/MockAutomationNodeRegistryTask.java import com.rmn.qa.RegistryRetriever; import org.openqa.grid.internal.ProxySet; /* * Copyright (C) 2014 RetailMeNot, Inc. * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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. */ package com.rmn.qa.task; /** * Created by mhardin on 4/24/14. */ public class MockAutomationNodeRegistryTask extends AutomationNodeRegistryTask { private ProxySet proxySet;
public MockAutomationNodeRegistryTask(RegistryRetriever retrieveContext) {
RetailMeNot/SeleniumGridScaler
src/main/java/com/rmn/qa/aws/AwsVmManager.java
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // }
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; import org.openqa.selenium.remote.BrowserType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationConstants; import com.rmn.qa.AutomationUtils; import com.rmn.qa.NodesCouldNotBeStartedException;
* @param properties {@link java.util.Properties Properties} to use for EC2 config loading * @param region Region inside of AWS to use */ public AwsVmManager(final AmazonEC2Client client, final Properties properties, final String region) { this.client = client; this.awsProperties = properties; this.region = region; } /** * Initializes the AWS properties from the default properties file. Allows the user to override the default * properties if desired * * @return */ Properties initAWSProperties() { Properties properties = new Properties(); String propertiesLocation = System.getProperty("propertyFileLocation"); // If the user passed in an AWS config file, go ahead and use it instead of the default one if (propertiesLocation != null) { File f = new File(propertiesLocation); try { InputStream is = new FileInputStream(f); properties.load(is); } catch (IOException e) { throw new RuntimeException("Could not load custom aws.properties", e); } } else { InputStream stream = AwsVmManager.class.getClassLoader().getResourceAsStream(
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // } // Path: src/main/java/com/rmn/qa/aws/AwsVmManager.java import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; import org.openqa.selenium.remote.BrowserType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationConstants; import com.rmn.qa.AutomationUtils; import com.rmn.qa.NodesCouldNotBeStartedException; * @param properties {@link java.util.Properties Properties} to use for EC2 config loading * @param region Region inside of AWS to use */ public AwsVmManager(final AmazonEC2Client client, final Properties properties, final String region) { this.client = client; this.awsProperties = properties; this.region = region; } /** * Initializes the AWS properties from the default properties file. Allows the user to override the default * properties if desired * * @return */ Properties initAWSProperties() { Properties properties = new Properties(); String propertiesLocation = System.getProperty("propertyFileLocation"); // If the user passed in an AWS config file, go ahead and use it instead of the default one if (propertiesLocation != null) { File f = new File(propertiesLocation); try { InputStream is = new FileInputStream(f); properties.load(is); } catch (IOException e) { throw new RuntimeException("Could not load custom aws.properties", e); } } else { InputStream stream = AwsVmManager.class.getClassLoader().getResourceAsStream(
AutomationConstants.AWS_DEFAULT_RESOURCE_NAME);
RetailMeNot/SeleniumGridScaler
src/main/java/com/rmn/qa/aws/AwsVmManager.java
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // }
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; import org.openqa.selenium.remote.BrowserType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationConstants; import com.rmn.qa.AutomationUtils; import com.rmn.qa.NodesCouldNotBeStartedException;
* @return */ @VisibleForTesting BasicAWSCredentials getCredentials() { // Give the system property credentials precedence over ones found in the config file String accessKey = System.getProperty(AutomationConstants.AWS_ACCESS_KEY); if (accessKey == null) { accessKey = awsProperties.getProperty(AutomationConstants.AWS_ACCESS_KEY); if (accessKey == null) { throw new IllegalArgumentException(String.format( "AWS Access Key must be passed in by the [%s] system property or be present in the AWS config file", AutomationConstants.AWS_ACCESS_KEY)); } } String privateKey = System.getProperty(AutomationConstants.AWS_PRIVATE_KEY); if (privateKey == null) { privateKey = awsProperties.getProperty(AutomationConstants.AWS_PRIVATE_KEY); if (privateKey == null) { throw new IllegalArgumentException(String.format( "AWS Private Key must be passed in by the [%s] system property or be present in the AWS config file", AutomationConstants.AWS_PRIVATE_KEY)); } } return new BasicAWSCredentials(accessKey, privateKey); } public List<Instance> launchNodes(final String amiId, final String instanceType, final int numberToStart,
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // } // Path: src/main/java/com/rmn/qa/aws/AwsVmManager.java import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; import org.openqa.selenium.remote.BrowserType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationConstants; import com.rmn.qa.AutomationUtils; import com.rmn.qa.NodesCouldNotBeStartedException; * @return */ @VisibleForTesting BasicAWSCredentials getCredentials() { // Give the system property credentials precedence over ones found in the config file String accessKey = System.getProperty(AutomationConstants.AWS_ACCESS_KEY); if (accessKey == null) { accessKey = awsProperties.getProperty(AutomationConstants.AWS_ACCESS_KEY); if (accessKey == null) { throw new IllegalArgumentException(String.format( "AWS Access Key must be passed in by the [%s] system property or be present in the AWS config file", AutomationConstants.AWS_ACCESS_KEY)); } } String privateKey = System.getProperty(AutomationConstants.AWS_PRIVATE_KEY); if (privateKey == null) { privateKey = awsProperties.getProperty(AutomationConstants.AWS_PRIVATE_KEY); if (privateKey == null) { throw new IllegalArgumentException(String.format( "AWS Private Key must be passed in by the [%s] system property or be present in the AWS config file", AutomationConstants.AWS_PRIVATE_KEY)); } } return new BasicAWSCredentials(accessKey, privateKey); } public List<Instance> launchNodes(final String amiId, final String instanceType, final int numberToStart,
final String userData, final boolean terminateOnShutdown) throws NodesCouldNotBeStartedException {
RetailMeNot/SeleniumGridScaler
src/main/java/com/rmn/qa/aws/AwsVmManager.java
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // }
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; import org.openqa.selenium.remote.BrowserType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationConstants; import com.rmn.qa.AutomationUtils; import com.rmn.qa.NodesCouldNotBeStartedException;
if (keyName != null) { log.info("Setting keyname:" + keyName); runRequest.withKeyName(keyName); } log.info("Sending run request to AWS..."); RunInstancesResult runInstancesResult = getResults(runRequest, 0); log.info("Run request result returned. Adding tags"); // Tag the instances with the standard RMN AWS data List<Instance> instances = runInstancesResult.getReservation().getInstances(); if (instances.size() == 0) { throw new NodesCouldNotBeStartedException(String.format( "Error starting up nodes -- count was zero and did not match expected count of %d", numberToStart)); } associateTags(new Date().toString(), instances); return instances; } /** * {@inheritDoc} */ @Override public List<Instance> launchNodes(final String uuid, String os, final String browser, final String hubHostName, final int nodeCount, final int maxSessions) throws NodesCouldNotBeStartedException { // Unspecified OS will default to Linux if (null == os) {
// Path: src/main/java/com/rmn/qa/AutomationConstants.java // public interface AutomationConstants { // // // These NODE_CONFIG_* constants represent key names in the node configs // String CONFIG_CREATED_DATE = "createdDate"; // String CONFIG_MAX_SESSION = "maxSession"; // String CONFIG_BROWSER = "createdBrowser"; // String CONFIG_OS = "createdOs"; // // This is the value that will be in the desired capabilities that our node registers with // // Runtime value of the hub instance id that gets passed in as a system property. Also used in the node config // String INSTANCE_ID = "instanceId"; // // IP address of the hub that will be passed in as a system property // String IP_ADDRESS = "ipAddress"; // // Test run UUID // String UUID = "uuid"; // String WINDOWS_PROPERTY_NAME="node.windows.json"; // String LINUX_PROPERTY_NAME="node.linux.json"; // String EXTRA_CAPABILITIES_PROPERTY_NAME="extraCapabilities"; // String AWS_ACCESS_KEY="awsAccessKey"; // String AWS_PRIVATE_KEY="awsSecretKey"; // String AWS_DEFAULT_RESOURCE_NAME= "aws.properties.default"; // String REAPER_THREAD_CONFIG = "useReaperThread"; // } // // Path: src/main/java/com/rmn/qa/AutomationUtils.java // public final class AutomationUtils { // // /** // * Modifies the specified date // * @param dateToModify Date to modify // * @param unitsToModify Number of units to modify (e.g. 6 for 6 seconds) // * @param unitType Measurement type (e.g. Calendar.SECONDS) // * @return Modified date // */ // public static Date modifyDate(Date dateToModify,int unitsToModify,int unitType) { // Calendar c = Calendar.getInstance(); // c.setTime(dateToModify); // // Add 60 seconds so we're as close to the hour as we can be instead of adding 55 again // c.add(unitType,unitsToModify); // return c.getTime(); // } // // /** // * Returns true if the current time is after the specified date, false otherwise // * @param dateToCheck Date to check against the current time // * @param unitsToCheckWith Number of units to add/subtract from dateToCheck // * @param unitType Unit type (e.g. Calendar.MINUTES) // * @return // */ // public static boolean isCurrentTimeAfterDate(Date dateToCheck,int unitsToCheckWith,int unitType) { // Date targetDate = AutomationUtils.modifyDate(dateToCheck,unitsToCheckWith,unitType); // return new Date().after(targetDate); // } // // /** // * Returns true if the strings are lower case equal // * @param string1 First string to compare // * @param string2 Second string to compare // * @return // */ // public static boolean lowerCaseMatch(String string1, String string2) { // string2 = string2.toLowerCase().replace(" ",""); // return string2.equals(string1.toLowerCase().replace(" ", "")); // } // // } // // Path: src/main/java/com/rmn/qa/NodesCouldNotBeStartedException.java // public class NodesCouldNotBeStartedException extends Exception { // public NodesCouldNotBeStartedException(String msg) { // super(msg); // } // // public NodesCouldNotBeStartedException(String msg, Throwable t) { // super(msg,t); // } // } // Path: src/main/java/com/rmn/qa/aws/AwsVmManager.java import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.codec.binary.Base64; import org.openqa.selenium.remote.BrowserType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStateChange; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.google.common.annotations.VisibleForTesting; import com.rmn.qa.AutomationConstants; import com.rmn.qa.AutomationUtils; import com.rmn.qa.NodesCouldNotBeStartedException; if (keyName != null) { log.info("Setting keyname:" + keyName); runRequest.withKeyName(keyName); } log.info("Sending run request to AWS..."); RunInstancesResult runInstancesResult = getResults(runRequest, 0); log.info("Run request result returned. Adding tags"); // Tag the instances with the standard RMN AWS data List<Instance> instances = runInstancesResult.getReservation().getInstances(); if (instances.size() == 0) { throw new NodesCouldNotBeStartedException(String.format( "Error starting up nodes -- count was zero and did not match expected count of %d", numberToStart)); } associateTags(new Date().toString(), instances); return instances; } /** * {@inheritDoc} */ @Override public List<Instance> launchNodes(final String uuid, String os, final String browser, final String hubHostName, final int nodeCount, final int maxSessions) throws NodesCouldNotBeStartedException { // Unspecified OS will default to Linux if (null == os) {
if (AutomationUtils.lowerCaseMatch(browser, "internet explorer")) {
tdumitrescu/cmme-editor
src/DataStruct/CMMEOldVersionParser.java
// Path: src/DataStruct/XMLReader.java // public class XMLReader // { // /*----------------------------------------------------------------------*/ // /* Class variables */ // // static final String ValParserName="org.apache.xerces.parsers.SAXParser", // NonvalParserName="gnu.xml.aelfred2.SAXDriver"; // static SAXBuilder builder, // noEntityBuilder=null; // static boolean inited=false; // // /*----------------------------------------------------------------------*/ // // /*----------------------------------------------------------------------*/ // /* Instance variables */ // // /*----------------------------------------------------------------------*/ // // /*------------------------------------------------------------------------ // Inner Class: CMMEEntityResolver // Implements: org.xml.sax.EntityResolver // Purpose: Resolves entities so that the CMME music schema is always // loaded from the same location (regardless of the location of // individual .cmme.xml docs) // ------------------------------------------------------------------------*/ // // static class CMMEEntityResolver implements EntityResolver // { // /* base data directory for finding CMME Schema file */ // String database; // // /*------------------------------------------------------------------------ // Constructor: CMMEEntityResolver(String db) // Purpose: Initialize custom entity resolver // Parameters: // Input: String db - base data directory // Output: - // Return: - // ------------------------------------------------------------------------*/ // // public CMMEEntityResolver(String db) // { // database=db; // } // // public InputSource resolveEntity(String publicId,String systemId) // { // InputSource inputSource; // if (systemId.matches(".*cmme\\.xsd")) { // String schemaFileName = "cmme.xsd"; // if (database == null) { // java.io.InputStream inputStream = getClass().getResourceAsStream(schemaFileName); // inputSource = new InputSource(inputStream); // } // else { // inputSource = new InputSource(database+"music/" + schemaFileName); // } // } // else { // inputSource = null; // } // return inputSource; // } // } // // /*----------------------------------------------------------------------*/ // /* Class methods */ // // /*------------------------------------------------------------------------ // Method: void initparser(String db,boolean validate) // Purpose: Create XML parser // Parameters: // Input: String db - base data directory // boolean validate - whether to validate XML input // Output: - // Return: - // ------------------------------------------------------------------------*/ // // public static void initparser(String db,boolean validate) // { // if (validate) // { // /* validates based on XML Schema */ // builder=new SAXBuilder(ValParserName,true); // builder.setFeature("http://apache.org/xml/features/validation/schema", // true); // builder.setEntityResolver(new CMMEEntityResolver(db)); // } // else // builder=new SAXBuilder(NonvalParserName,false); // inited=true; // } // // /*------------------------------------------------------------------------ // Method: SAXBuilder getParser() // Purpose: Return XML parser // Parameters: // Input: - // Output: - // Return: Parser // ------------------------------------------------------------------------*/ // // public static SAXBuilder getNonValidatingParser() // { // if (inited && !builder.getValidation()) // return builder; // else // return new SAXBuilder(NonvalParserName,false); // } // // public static SAXBuilder getNoEntityParser() // { // if (noEntityBuilder==null) // { // noEntityBuilder=new SAXBuilder("org.apache.xerces.parsers.SAXParser",false); // noEntityBuilder.setFeature( // "http://apache.org/xml/features/nonvalidating/load-external-dtd",false); // } // // return noEntityBuilder; // } // // public static SAXBuilder getParser() // { // if (inited) // return builder; // System.err.println("XML Reader called before initialization"); // return null; // } // // /*------------------------------------------------------------------------ // Method: [] get*Val(Element el) // Purpose: Parse value in XML node // Parameters: // Input: Element el - element with value // Output: - // Return: value represented in el // ------------------------------------------------------------------------*/ // // public static char getCharVal(Element el) // { // if (el==null) // return ' '; // String eVal=el.getText(); // if (eVal.length()<1) // return ' '; // return eVal.charAt(0); // } // // public static char getCharVal(Object o) // { // return getCharVal((Element)o); // } // // public static int getIntVal(Element el) // { // return el==null ? -1 : Integer.parseInt(el.getText()); // } // // public static int getIntVal(Object o) // { // return getIntVal((Element)o); // } // }
import DataStruct.XMLReader; import org.jdom.*; import org.jdom.output.*; import java.net.*; import java.io.*; import java.util.*;
/*----------------------------------------------------------------------*/ /* Module : CMMEOldVersionParser.java Package : DataStruct Classes Included: CMMEOldVersionParser Purpose : Input of deprecated files (for conversion to current format) Programmer : Ted Dumitrescu Date Started : 3/1/07 Updates: */ /*----------------------------------------------------------------------*/ package DataStruct; /*----------------------------------------------------------------------*/ /* Imported packages */ /*----------------------------------------------------------------------*/ /*------------------------------------------------------------------------ Class: CMMEOldVersionParser Extends: - Purpose: Input of deprecated CMME music files ------------------------------------------------------------------------*/ public class CMMEOldVersionParser { /*----------------------------------------------------------------------*/ /* Class variables */ static Namespace cmmens; /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Instance variables */ public PieceData piece; /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Class methods */ /*----------------------------------------------------------------------*/ /* Instance methods */ /*------------------------------------------------------------------------ Constructor: CMMEOldVersionParser(String fn) Purpose: Parse local file Parameters: Input: String fn - filename for input Output: - ------------------------------------------------------------------------*/ public CMMEOldVersionParser(String fn) throws JDOMException,IOException {
// Path: src/DataStruct/XMLReader.java // public class XMLReader // { // /*----------------------------------------------------------------------*/ // /* Class variables */ // // static final String ValParserName="org.apache.xerces.parsers.SAXParser", // NonvalParserName="gnu.xml.aelfred2.SAXDriver"; // static SAXBuilder builder, // noEntityBuilder=null; // static boolean inited=false; // // /*----------------------------------------------------------------------*/ // // /*----------------------------------------------------------------------*/ // /* Instance variables */ // // /*----------------------------------------------------------------------*/ // // /*------------------------------------------------------------------------ // Inner Class: CMMEEntityResolver // Implements: org.xml.sax.EntityResolver // Purpose: Resolves entities so that the CMME music schema is always // loaded from the same location (regardless of the location of // individual .cmme.xml docs) // ------------------------------------------------------------------------*/ // // static class CMMEEntityResolver implements EntityResolver // { // /* base data directory for finding CMME Schema file */ // String database; // // /*------------------------------------------------------------------------ // Constructor: CMMEEntityResolver(String db) // Purpose: Initialize custom entity resolver // Parameters: // Input: String db - base data directory // Output: - // Return: - // ------------------------------------------------------------------------*/ // // public CMMEEntityResolver(String db) // { // database=db; // } // // public InputSource resolveEntity(String publicId,String systemId) // { // InputSource inputSource; // if (systemId.matches(".*cmme\\.xsd")) { // String schemaFileName = "cmme.xsd"; // if (database == null) { // java.io.InputStream inputStream = getClass().getResourceAsStream(schemaFileName); // inputSource = new InputSource(inputStream); // } // else { // inputSource = new InputSource(database+"music/" + schemaFileName); // } // } // else { // inputSource = null; // } // return inputSource; // } // } // // /*----------------------------------------------------------------------*/ // /* Class methods */ // // /*------------------------------------------------------------------------ // Method: void initparser(String db,boolean validate) // Purpose: Create XML parser // Parameters: // Input: String db - base data directory // boolean validate - whether to validate XML input // Output: - // Return: - // ------------------------------------------------------------------------*/ // // public static void initparser(String db,boolean validate) // { // if (validate) // { // /* validates based on XML Schema */ // builder=new SAXBuilder(ValParserName,true); // builder.setFeature("http://apache.org/xml/features/validation/schema", // true); // builder.setEntityResolver(new CMMEEntityResolver(db)); // } // else // builder=new SAXBuilder(NonvalParserName,false); // inited=true; // } // // /*------------------------------------------------------------------------ // Method: SAXBuilder getParser() // Purpose: Return XML parser // Parameters: // Input: - // Output: - // Return: Parser // ------------------------------------------------------------------------*/ // // public static SAXBuilder getNonValidatingParser() // { // if (inited && !builder.getValidation()) // return builder; // else // return new SAXBuilder(NonvalParserName,false); // } // // public static SAXBuilder getNoEntityParser() // { // if (noEntityBuilder==null) // { // noEntityBuilder=new SAXBuilder("org.apache.xerces.parsers.SAXParser",false); // noEntityBuilder.setFeature( // "http://apache.org/xml/features/nonvalidating/load-external-dtd",false); // } // // return noEntityBuilder; // } // // public static SAXBuilder getParser() // { // if (inited) // return builder; // System.err.println("XML Reader called before initialization"); // return null; // } // // /*------------------------------------------------------------------------ // Method: [] get*Val(Element el) // Purpose: Parse value in XML node // Parameters: // Input: Element el - element with value // Output: - // Return: value represented in el // ------------------------------------------------------------------------*/ // // public static char getCharVal(Element el) // { // if (el==null) // return ' '; // String eVal=el.getText(); // if (eVal.length()<1) // return ' '; // return eVal.charAt(0); // } // // public static char getCharVal(Object o) // { // return getCharVal((Element)o); // } // // public static int getIntVal(Element el) // { // return el==null ? -1 : Integer.parseInt(el.getText()); // } // // public static int getIntVal(Object o) // { // return getIntVal((Element)o); // } // } // Path: src/DataStruct/CMMEOldVersionParser.java import DataStruct.XMLReader; import org.jdom.*; import org.jdom.output.*; import java.net.*; import java.io.*; import java.util.*; /*----------------------------------------------------------------------*/ /* Module : CMMEOldVersionParser.java Package : DataStruct Classes Included: CMMEOldVersionParser Purpose : Input of deprecated files (for conversion to current format) Programmer : Ted Dumitrescu Date Started : 3/1/07 Updates: */ /*----------------------------------------------------------------------*/ package DataStruct; /*----------------------------------------------------------------------*/ /* Imported packages */ /*----------------------------------------------------------------------*/ /*------------------------------------------------------------------------ Class: CMMEOldVersionParser Extends: - Purpose: Input of deprecated CMME music files ------------------------------------------------------------------------*/ public class CMMEOldVersionParser { /*----------------------------------------------------------------------*/ /* Class variables */ static Namespace cmmens; /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Instance variables */ public PieceData piece; /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Class methods */ /*----------------------------------------------------------------------*/ /* Instance methods */ /*------------------------------------------------------------------------ Constructor: CMMEOldVersionParser(String fn) Purpose: Parse local file Parameters: Input: String fn - filename for input Output: - ------------------------------------------------------------------------*/ public CMMEOldVersionParser(String fn) throws JDOMException,IOException {
constructPieceData(XMLReader.getParser().build(fn));
tdumitrescu/cmme-editor
src/Util/GlobalConfig.java
// Path: src/DataStruct/XMLReader.java // public class XMLReader // { // /*----------------------------------------------------------------------*/ // /* Class variables */ // // static final String ValParserName="org.apache.xerces.parsers.SAXParser", // NonvalParserName="gnu.xml.aelfred2.SAXDriver"; // static SAXBuilder builder, // noEntityBuilder=null; // static boolean inited=false; // // /*----------------------------------------------------------------------*/ // // /*----------------------------------------------------------------------*/ // /* Instance variables */ // // /*----------------------------------------------------------------------*/ // // /*------------------------------------------------------------------------ // Inner Class: CMMEEntityResolver // Implements: org.xml.sax.EntityResolver // Purpose: Resolves entities so that the CMME music schema is always // loaded from the same location (regardless of the location of // individual .cmme.xml docs) // ------------------------------------------------------------------------*/ // // static class CMMEEntityResolver implements EntityResolver // { // /* base data directory for finding CMME Schema file */ // String database; // // /*------------------------------------------------------------------------ // Constructor: CMMEEntityResolver(String db) // Purpose: Initialize custom entity resolver // Parameters: // Input: String db - base data directory // Output: - // Return: - // ------------------------------------------------------------------------*/ // // public CMMEEntityResolver(String db) // { // database=db; // } // // public InputSource resolveEntity(String publicId,String systemId) // { // InputSource inputSource; // if (systemId.matches(".*cmme\\.xsd")) { // String schemaFileName = "cmme.xsd"; // if (database == null) { // java.io.InputStream inputStream = getClass().getResourceAsStream(schemaFileName); // inputSource = new InputSource(inputStream); // } // else { // inputSource = new InputSource(database+"music/" + schemaFileName); // } // } // else { // inputSource = null; // } // return inputSource; // } // } // // /*----------------------------------------------------------------------*/ // /* Class methods */ // // /*------------------------------------------------------------------------ // Method: void initparser(String db,boolean validate) // Purpose: Create XML parser // Parameters: // Input: String db - base data directory // boolean validate - whether to validate XML input // Output: - // Return: - // ------------------------------------------------------------------------*/ // // public static void initparser(String db,boolean validate) // { // if (validate) // { // /* validates based on XML Schema */ // builder=new SAXBuilder(ValParserName,true); // builder.setFeature("http://apache.org/xml/features/validation/schema", // true); // builder.setEntityResolver(new CMMEEntityResolver(db)); // } // else // builder=new SAXBuilder(NonvalParserName,false); // inited=true; // } // // /*------------------------------------------------------------------------ // Method: SAXBuilder getParser() // Purpose: Return XML parser // Parameters: // Input: - // Output: - // Return: Parser // ------------------------------------------------------------------------*/ // // public static SAXBuilder getNonValidatingParser() // { // if (inited && !builder.getValidation()) // return builder; // else // return new SAXBuilder(NonvalParserName,false); // } // // public static SAXBuilder getNoEntityParser() // { // if (noEntityBuilder==null) // { // noEntityBuilder=new SAXBuilder("org.apache.xerces.parsers.SAXParser",false); // noEntityBuilder.setFeature( // "http://apache.org/xml/features/nonvalidating/load-external-dtd",false); // } // // return noEntityBuilder; // } // // public static SAXBuilder getParser() // { // if (inited) // return builder; // System.err.println("XML Reader called before initialization"); // return null; // } // // /*------------------------------------------------------------------------ // Method: [] get*Val(Element el) // Purpose: Parse value in XML node // Parameters: // Input: Element el - element with value // Output: - // Return: value represented in el // ------------------------------------------------------------------------*/ // // public static char getCharVal(Element el) // { // if (el==null) // return ' '; // String eVal=el.getText(); // if (eVal.length()<1) // return ' '; // return eVal.charAt(0); // } // // public static char getCharVal(Object o) // { // return getCharVal((Element)o); // } // // public static int getIntVal(Element el) // { // return el==null ? -1 : Integer.parseInt(el.getText()); // } // // public static int getIntVal(Object o) // { // return getIntVal((Element)o); // } // }
import java.io.*; import java.net.URL; import java.util.*; import org.jdom.*; import DataStruct.XMLReader;
package Util; public class GlobalConfig { /*----------------------------------------------------------------------*/ /* Class variables/methods */ public static String get(String key) { return getConfigMap().getVal(key); } /* lazy-load config */ private static String CONFIG_LOC = "config/cmme-config.xml"; private static GlobalConfig configMap = null; private static GlobalConfig getConfigMap() { if (configMap == null) configMap = new GlobalConfig(AppContext.BaseDataURL + CONFIG_LOC); return configMap; } /*----------------------------------------------------------------------*/ /* Instance variables/methods */ private HashMap<String,String> config; public GlobalConfig(String configLoc) { config = readConfigFromFile(configLoc); } String getVal(String key) { return config.get(key); } private HashMap<String,String> readConfigFromFile(String configLoc) { Document configDoc; HashMap<String,String> cmap = new HashMap<String,String>(); try {
// Path: src/DataStruct/XMLReader.java // public class XMLReader // { // /*----------------------------------------------------------------------*/ // /* Class variables */ // // static final String ValParserName="org.apache.xerces.parsers.SAXParser", // NonvalParserName="gnu.xml.aelfred2.SAXDriver"; // static SAXBuilder builder, // noEntityBuilder=null; // static boolean inited=false; // // /*----------------------------------------------------------------------*/ // // /*----------------------------------------------------------------------*/ // /* Instance variables */ // // /*----------------------------------------------------------------------*/ // // /*------------------------------------------------------------------------ // Inner Class: CMMEEntityResolver // Implements: org.xml.sax.EntityResolver // Purpose: Resolves entities so that the CMME music schema is always // loaded from the same location (regardless of the location of // individual .cmme.xml docs) // ------------------------------------------------------------------------*/ // // static class CMMEEntityResolver implements EntityResolver // { // /* base data directory for finding CMME Schema file */ // String database; // // /*------------------------------------------------------------------------ // Constructor: CMMEEntityResolver(String db) // Purpose: Initialize custom entity resolver // Parameters: // Input: String db - base data directory // Output: - // Return: - // ------------------------------------------------------------------------*/ // // public CMMEEntityResolver(String db) // { // database=db; // } // // public InputSource resolveEntity(String publicId,String systemId) // { // InputSource inputSource; // if (systemId.matches(".*cmme\\.xsd")) { // String schemaFileName = "cmme.xsd"; // if (database == null) { // java.io.InputStream inputStream = getClass().getResourceAsStream(schemaFileName); // inputSource = new InputSource(inputStream); // } // else { // inputSource = new InputSource(database+"music/" + schemaFileName); // } // } // else { // inputSource = null; // } // return inputSource; // } // } // // /*----------------------------------------------------------------------*/ // /* Class methods */ // // /*------------------------------------------------------------------------ // Method: void initparser(String db,boolean validate) // Purpose: Create XML parser // Parameters: // Input: String db - base data directory // boolean validate - whether to validate XML input // Output: - // Return: - // ------------------------------------------------------------------------*/ // // public static void initparser(String db,boolean validate) // { // if (validate) // { // /* validates based on XML Schema */ // builder=new SAXBuilder(ValParserName,true); // builder.setFeature("http://apache.org/xml/features/validation/schema", // true); // builder.setEntityResolver(new CMMEEntityResolver(db)); // } // else // builder=new SAXBuilder(NonvalParserName,false); // inited=true; // } // // /*------------------------------------------------------------------------ // Method: SAXBuilder getParser() // Purpose: Return XML parser // Parameters: // Input: - // Output: - // Return: Parser // ------------------------------------------------------------------------*/ // // public static SAXBuilder getNonValidatingParser() // { // if (inited && !builder.getValidation()) // return builder; // else // return new SAXBuilder(NonvalParserName,false); // } // // public static SAXBuilder getNoEntityParser() // { // if (noEntityBuilder==null) // { // noEntityBuilder=new SAXBuilder("org.apache.xerces.parsers.SAXParser",false); // noEntityBuilder.setFeature( // "http://apache.org/xml/features/nonvalidating/load-external-dtd",false); // } // // return noEntityBuilder; // } // // public static SAXBuilder getParser() // { // if (inited) // return builder; // System.err.println("XML Reader called before initialization"); // return null; // } // // /*------------------------------------------------------------------------ // Method: [] get*Val(Element el) // Purpose: Parse value in XML node // Parameters: // Input: Element el - element with value // Output: - // Return: value represented in el // ------------------------------------------------------------------------*/ // // public static char getCharVal(Element el) // { // if (el==null) // return ' '; // String eVal=el.getText(); // if (eVal.length()<1) // return ' '; // return eVal.charAt(0); // } // // public static char getCharVal(Object o) // { // return getCharVal((Element)o); // } // // public static int getIntVal(Element el) // { // return el==null ? -1 : Integer.parseInt(el.getText()); // } // // public static int getIntVal(Object o) // { // return getIntVal((Element)o); // } // } // Path: src/Util/GlobalConfig.java import java.io.*; import java.net.URL; import java.util.*; import org.jdom.*; import DataStruct.XMLReader; package Util; public class GlobalConfig { /*----------------------------------------------------------------------*/ /* Class variables/methods */ public static String get(String key) { return getConfigMap().getVal(key); } /* lazy-load config */ private static String CONFIG_LOC = "config/cmme-config.xml"; private static GlobalConfig configMap = null; private static GlobalConfig getConfigMap() { if (configMap == null) configMap = new GlobalConfig(AppContext.BaseDataURL + CONFIG_LOC); return configMap; } /*----------------------------------------------------------------------*/ /* Instance variables/methods */ private HashMap<String,String> config; public GlobalConfig(String configLoc) { config = readConfigFromFile(configLoc); } String getVal(String key) { return config.get(key); } private HashMap<String,String> readConfigFromFile(String configLoc) { Document configDoc; HashMap<String,String> cmap = new HashMap<String,String>(); try {
configDoc = XMLReader.getNonValidatingParser().build(new URL(configLoc));
contentful/vault
core/src/main/java/com/contentful/vault/SyncRunnable.java
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName;
for (CDAEntry entry : syncedSpace.entries().values()) { processResource(entry); } } private void processDeleted(SynchronizedSpace syncedSpace) { for (String id : syncedSpace.deletedAssets()) { deleteAsset(id); } for (String id : syncedSpace.deletedEntries()) { deleteEntry(id); } } private String fetchSyncToken() { String token = null; Cursor cursor = db.rawQuery("SELECT `token` FROM sync_info", null); try { if (cursor.moveToFirst()) { token = cursor.getString(0); } } finally { cursor.close(); } return token; } private void saveSyncInfo(String syncToken) { AutoEscapeValues values = new AutoEscapeValues(); values.put("token", syncToken);
// Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String CREATED_AT = "created_at"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String REMOTE_ID = "remote_id"; // // Path: core/src/main/java/com/contentful/vault/BaseFields.java // public static final String UPDATED_AT = "updated_at"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ASSETS = "assets"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_ENTRY_TYPES = "entry_types"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_LINKS = "links"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static final String TABLE_SYNC_INFO = "sync_info"; // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String escape(String name) { // return String.format("`%s`", name); // } // // Path: core/src/main/java/com/contentful/vault/Sql.java // static String localizeName(String name, String locale) { // return String.format("%s$%s", name, locale); // } // Path: core/src/main/java/com/contentful/vault/SyncRunnable.java import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Build; import com.contentful.java.cda.CDAAsset; import com.contentful.java.cda.CDAEntry; import com.contentful.java.cda.CDAResource; import com.contentful.java.cda.CDAType; import com.contentful.java.cda.LocalizedResource; import com.contentful.java.cda.SynchronizedSpace; import java.io.IOException; import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import okhttp3.HttpUrl; import static android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE; import static com.contentful.java.cda.CDAType.ASSET; import static com.contentful.java.cda.CDAType.ENTRY; import static com.contentful.vault.BaseFields.CREATED_AT; import static com.contentful.vault.BaseFields.REMOTE_ID; import static com.contentful.vault.BaseFields.UPDATED_AT; import static com.contentful.vault.Sql.TABLE_ASSETS; import static com.contentful.vault.Sql.TABLE_ENTRY_TYPES; import static com.contentful.vault.Sql.TABLE_LINKS; import static com.contentful.vault.Sql.TABLE_SYNC_INFO; import static com.contentful.vault.Sql.escape; import static com.contentful.vault.Sql.localizeName; for (CDAEntry entry : syncedSpace.entries().values()) { processResource(entry); } } private void processDeleted(SynchronizedSpace syncedSpace) { for (String id : syncedSpace.deletedAssets()) { deleteAsset(id); } for (String id : syncedSpace.deletedEntries()) { deleteEntry(id); } } private String fetchSyncToken() { String token = null; Cursor cursor = db.rawQuery("SELECT `token` FROM sync_info", null); try { if (cursor.moveToFirst()) { token = cursor.getString(0); } } finally { cursor.close(); } return token; } private void saveSyncInfo(String syncToken) { AutoEscapeValues values = new AutoEscapeValues(); values.put("token", syncToken);
db.delete(TABLE_SYNC_INFO, null, null);