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
jchampemont/notedown
src/main/java/com/jeanchampemont/notedown/user/UserService.java
// Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // }
import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional;
/* * Copyright (C) 2014, 2015 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.user; /** * This service manages users of the application. * * @author Jean Champémont */ @Service public class UserService { private AuthenticationService authenticationService; private UserRepository repo; private PasswordEncoder encoder; @Autowired public UserService(AuthenticationService authenticationService, UserRepository repo, PasswordEncoder encoder) { this.authenticationService = authenticationService; this.repo = repo; this.encoder = encoder; } /** * @return whether or not the application has at least one registered user. */ @Transactional(readOnly = true) public boolean hasRegisteredUser() { return repo.findAll().iterator().hasNext(); } /** * Create the user. * The password is encoded. * * @param user * @return persisted user with encoded password */ @Transactional
// Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // } // Path: src/main/java/com/jeanchampemont/notedown/user/UserService.java import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; /* * Copyright (C) 2014, 2015 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.user; /** * This service manages users of the application. * * @author Jean Champémont */ @Service public class UserService { private AuthenticationService authenticationService; private UserRepository repo; private PasswordEncoder encoder; @Autowired public UserService(AuthenticationService authenticationService, UserRepository repo, PasswordEncoder encoder) { this.authenticationService = authenticationService; this.repo = repo; this.encoder = encoder; } /** * @return whether or not the application has at least one registered user. */ @Transactional(readOnly = true) public boolean hasRegisteredUser() { return repo.findAll().iterator().hasNext(); } /** * Create the user. * The password is encoded. * * @param user * @return persisted user with encoded password */ @Transactional
public User create(User user) {
jchampemont/notedown
src/main/java/com/jeanchampemont/notedown/user/UserService.java
// Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // }
import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional;
/** * Find a user for this email if it exists * * @param email * @return */ @Transactional(readOnly = true) @Cacheable("user") public Optional<User> getUserByEmail(String email) { return Optional.ofNullable(repo.findByEmailIgnoreCase(email)); } /** * Update user * This method does not update email or password. * Use changeEmail or changePassword instead. * * @param user * @return updated user */ @Transactional @CacheEvict(value = "user", key = "#user.email") public User update(User user) { User originalUser = repo.findByEmailIgnoreCase(user.getEmail()); User currentUser = authenticationService.getCurrentUser(); if (hasWriteAccess(currentUser, originalUser)) { originalUser.setLocale(user.getLocale()); originalUser.setDisplayName(user.getDisplayName()); return repo.save(originalUser); }
// Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // } // Path: src/main/java/com/jeanchampemont/notedown/user/UserService.java import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; /** * Find a user for this email if it exists * * @param email * @return */ @Transactional(readOnly = true) @Cacheable("user") public Optional<User> getUserByEmail(String email) { return Optional.ofNullable(repo.findByEmailIgnoreCase(email)); } /** * Update user * This method does not update email or password. * Use changeEmail or changePassword instead. * * @param user * @return updated user */ @Transactional @CacheEvict(value = "user", key = "#user.email") public User update(User user) { User originalUser = repo.findByEmailIgnoreCase(user.getEmail()); User currentUser = authenticationService.getCurrentUser(); if (hasWriteAccess(currentUser, originalUser)) { originalUser.setLocale(user.getLocale()); originalUser.setDisplayName(user.getDisplayName()); return repo.save(originalUser); }
throw new OperationNotAllowedException();
jchampemont/notedown
src/main/java/com/jeanchampemont/notedown/note/persistence/Note.java
// Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // }
import com.jeanchampemont.notedown.user.persistence.User; import org.hibernate.annotations.Type; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID;
/* * Copyright (C) 2014, 2015 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.note.persistence; @Entity @Table(name = "note") public class Note { @Id @Type(type = "uuid-char") private UUID id; @Column(name = "title", length = 64, nullable = false) private String title; @Column(name = "content", nullable = false) @Lob @Type(type = "org.hibernate.type.StringClobType") private String content; @Column(name = "last_modification", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date lastModification; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "user_id", nullable = false)
// Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // Path: src/main/java/com/jeanchampemont/notedown/note/persistence/Note.java import com.jeanchampemont.notedown.user.persistence.User; import org.hibernate.annotations.Type; import javax.persistence.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; /* * Copyright (C) 2014, 2015 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.note.persistence; @Entity @Table(name = "note") public class Note { @Id @Type(type = "uuid-char") private UUID id; @Column(name = "title", length = 64, nullable = false) private String title; @Column(name = "content", nullable = false) @Lob @Type(type = "org.hibernate.type.StringClobType") private String content; @Column(name = "last_modification", nullable = false) @Temporal(TemporalType.TIMESTAMP) private Date lastModification; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "user_id", nullable = false)
private User user;
jchampemont/notedown
src/test/java/com/jeanchampemont/notedown/user/UserServiceTest.java
// Path: src/main/java/com/jeanchampemont/notedown/NoteDownApplication.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // @EnableScheduling // public class NoteDownApplication { // // public static void main(String[] args) { // SpringApplication.run(NoteDownApplication.class, args); // } // // } // // Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // }
import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import com.jeanchampemont.notedown.NoteDownApplication; import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/* * Copyright (C) 2014 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.user; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = NoteDownApplication.class) public class UserServiceTest { private UserService sut;
// Path: src/main/java/com/jeanchampemont/notedown/NoteDownApplication.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // @EnableScheduling // public class NoteDownApplication { // // public static void main(String[] args) { // SpringApplication.run(NoteDownApplication.class, args); // } // // } // // Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // } // Path: src/test/java/com/jeanchampemont/notedown/user/UserServiceTest.java import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import com.jeanchampemont.notedown.NoteDownApplication; import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /* * Copyright (C) 2014 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.user; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = NoteDownApplication.class) public class UserServiceTest { private UserService sut;
private AuthenticationService authenticationServiceMock;
jchampemont/notedown
src/test/java/com/jeanchampemont/notedown/user/UserServiceTest.java
// Path: src/main/java/com/jeanchampemont/notedown/NoteDownApplication.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // @EnableScheduling // public class NoteDownApplication { // // public static void main(String[] args) { // SpringApplication.run(NoteDownApplication.class, args); // } // // } // // Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // }
import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import com.jeanchampemont.notedown.NoteDownApplication; import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/* * Copyright (C) 2014 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.user; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = NoteDownApplication.class) public class UserServiceTest { private UserService sut; private AuthenticationService authenticationServiceMock;
// Path: src/main/java/com/jeanchampemont/notedown/NoteDownApplication.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // @EnableScheduling // public class NoteDownApplication { // // public static void main(String[] args) { // SpringApplication.run(NoteDownApplication.class, args); // } // // } // // Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // } // Path: src/test/java/com/jeanchampemont/notedown/user/UserServiceTest.java import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import com.jeanchampemont.notedown.NoteDownApplication; import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /* * Copyright (C) 2014 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.user; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = NoteDownApplication.class) public class UserServiceTest { private UserService sut; private AuthenticationService authenticationServiceMock;
private UserRepository repoMock;
jchampemont/notedown
src/test/java/com/jeanchampemont/notedown/user/UserServiceTest.java
// Path: src/main/java/com/jeanchampemont/notedown/NoteDownApplication.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // @EnableScheduling // public class NoteDownApplication { // // public static void main(String[] args) { // SpringApplication.run(NoteDownApplication.class, args); // } // // } // // Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // }
import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import com.jeanchampemont.notedown.NoteDownApplication; import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/* * Copyright (C) 2014 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.user; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = NoteDownApplication.class) public class UserServiceTest { private UserService sut; private AuthenticationService authenticationServiceMock; private UserRepository repoMock; private PasswordEncoder encoderMock; @Before public void init() { authenticationServiceMock = mock(AuthenticationService.class); repoMock = mock(UserRepository.class); encoderMock = mock(PasswordEncoder.class); sut = new UserService(authenticationServiceMock, repoMock, encoderMock); } @Test public void testCreate() { String email = "[email protected]"; String password = "mySuperSecurePassword";
// Path: src/main/java/com/jeanchampemont/notedown/NoteDownApplication.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // @EnableScheduling // public class NoteDownApplication { // // public static void main(String[] args) { // SpringApplication.run(NoteDownApplication.class, args); // } // // } // // Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // } // Path: src/test/java/com/jeanchampemont/notedown/user/UserServiceTest.java import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import com.jeanchampemont.notedown.NoteDownApplication; import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /* * Copyright (C) 2014 NoteDown * * This file is part of the NoteDown project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jeanchampemont.notedown.user; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = NoteDownApplication.class) public class UserServiceTest { private UserService sut; private AuthenticationService authenticationServiceMock; private UserRepository repoMock; private PasswordEncoder encoderMock; @Before public void init() { authenticationServiceMock = mock(AuthenticationService.class); repoMock = mock(UserRepository.class); encoderMock = mock(PasswordEncoder.class); sut = new UserService(authenticationServiceMock, repoMock, encoderMock); } @Test public void testCreate() { String email = "[email protected]"; String password = "mySuperSecurePassword";
User user = new User();
jchampemont/notedown
src/test/java/com/jeanchampemont/notedown/user/UserServiceTest.java
// Path: src/main/java/com/jeanchampemont/notedown/NoteDownApplication.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // @EnableScheduling // public class NoteDownApplication { // // public static void main(String[] args) { // SpringApplication.run(NoteDownApplication.class, args); // } // // } // // Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // }
import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import com.jeanchampemont.notedown.NoteDownApplication; import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
Optional<User> result = sut.getUserByEmail(email); verify(repoMock).findByEmailIgnoreCase(email); assertFalse(result.isPresent()); } @Test public void testUpdate() { String locale = "fr"; String email = "[email protected]"; User user = new User(); user.setId(12); user.setEmail(email); user.setLocale(locale); when(repoMock.findByEmailIgnoreCase(email)).thenReturn(user); when(authenticationServiceMock.getCurrentUser()).thenReturn(user); when(repoMock.save(user)).thenReturn(user); User result = sut.update(user); verify(repoMock).findByEmailIgnoreCase(email); verify(repoMock).save(user); verify(authenticationServiceMock).getCurrentUser(); assertEquals(locale, user.getLocale()); }
// Path: src/main/java/com/jeanchampemont/notedown/NoteDownApplication.java // @Configuration // @ComponentScan // @EnableAutoConfiguration // @EnableScheduling // public class NoteDownApplication { // // public static void main(String[] args) { // SpringApplication.run(NoteDownApplication.class, args); // } // // } // // Path: src/main/java/com/jeanchampemont/notedown/security/AuthenticationService.java // @Service // public class AuthenticationService { // private UserRepository userRepository; // // private AuthenticationManager authenticationManager; // // @Autowired // public AuthenticationService(UserRepository userRepository, AuthenticationManager authenticationManager) { // this.userRepository = userRepository; // this.authenticationManager = authenticationManager; // } // // public User getCurrentUser() { // String email = SecurityContextHolder.getContext().getAuthentication().getName(); // return userRepository.findByEmailIgnoreCase(email); // } // // public boolean isAuthenticated() { // return (SecurityContextHolder.getContext().getAuthentication() != null); // } // // public void newAuthentication(String email, String password) { // Authentication request = new UsernamePasswordAuthenticationToken(email, password); // Authentication result = authenticationManager.authenticate(request); // SecurityContextHolder.getContext().setAuthentication(result); // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/User.java // @Entity // @Table(name = "user_account") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.TABLE) // private long id; // // @Column(name = "email", unique = true, length = 64) // private String email; // // @Column(name = "password", length = 60) // private String password; // // @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") // private Set<Note> notes = new HashSet<>(); // // @Column(name = "locale", length = 2) // private String locale; // // @Column(name = "display_name", length = 64) // private String displayName; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public Set<Note> getNotes() { // return notes; // } // // public void setNotes(Set<Note> notes) { // this.notes = notes; // } // // public String getLocale() { // return locale; // } // // public void setLocale(String locale) { // this.locale = locale; // } // // public String getDisplayName() { // return displayName; // } // // public void setDisplayName(String displayName) { // this.displayName = displayName; // } // } // // Path: src/main/java/com/jeanchampemont/notedown/user/persistence/repository/UserRepository.java // public interface UserRepository extends CrudRepository<User, Long> { // User findByEmailIgnoreCase(String email); // } // // Path: src/main/java/com/jeanchampemont/notedown/utils/exception/OperationNotAllowedException.java // public class OperationNotAllowedException extends RuntimeException { // // } // Path: src/test/java/com/jeanchampemont/notedown/user/UserServiceTest.java import java.util.Optional; import static org.junit.Assert.*; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import com.jeanchampemont.notedown.NoteDownApplication; import com.jeanchampemont.notedown.security.AuthenticationService; import com.jeanchampemont.notedown.user.persistence.User; import com.jeanchampemont.notedown.user.persistence.repository.UserRepository; import com.jeanchampemont.notedown.utils.exception.OperationNotAllowedException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; Optional<User> result = sut.getUserByEmail(email); verify(repoMock).findByEmailIgnoreCase(email); assertFalse(result.isPresent()); } @Test public void testUpdate() { String locale = "fr"; String email = "[email protected]"; User user = new User(); user.setId(12); user.setEmail(email); user.setLocale(locale); when(repoMock.findByEmailIgnoreCase(email)).thenReturn(user); when(authenticationServiceMock.getCurrentUser()).thenReturn(user); when(repoMock.save(user)).thenReturn(user); User result = sut.update(user); verify(repoMock).findByEmailIgnoreCase(email); verify(repoMock).save(user); verify(authenticationServiceMock).getCurrentUser(); assertEquals(locale, user.getLocale()); }
@Test(expected = OperationNotAllowedException.class)
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/storage/Data.java
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Membership.java // public class Membership implements Serializable { // private final String mId; // private final int mType; // // private Membership(String id, int type){ // mId = id; // mType = type; // } // // public String getId() { // return mId; // } // // public int getType(){ // return mType; // } // // final public String getTigerType() { // if(mType==1){ // return "TigerXbox"; // } else { // return "TigerPSN"; // } // } // // public static Membership fromJson(JSONObject jsonObject) { // return new Membership(jsonObject.optString("membershipId"), jsonObject.optInt("membershipType")); // } // } // // Path: app/src/main/java/org/swistowski/vaulthelper/models/User.java // public class User implements Serializable { // private static final String LOG_TAG = "models.User"; // private final String mDisplayName; // private final String mPsnId; // private final String mGameTag; // private final boolean mIsPsn; // // private User(String displayName, String psnId, String gameTag) { // mDisplayName = displayName; // mPsnId = psnId; // mIsPsn = !psnId.equals(""); // mGameTag = gameTag; // } // // static public User fromJson(JSONObject data) throws JSONException { // return new User( // data.getJSONObject("user").getString("displayName"), // data.optString("psnId", ""), // data.optString("gamerTag", "") // ); // } // public String getAccountName(){ // return mIsPsn?mPsnId:mGameTag; // } // @Deprecated // private String getDisplayName() { // return mDisplayName; // } // // public int getAccountType() { // return mIsPsn ? 2 : 1; // } // // // }
import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import org.swistowski.vaulthelper.models.Membership; import org.swistowski.vaulthelper.models.User; import java.io.Serializable;
package org.swistowski.vaulthelper.storage; public class Data implements Serializable { private static final String LOG_TAG = "Database"; private static final Data ourInstance = new Data();
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Membership.java // public class Membership implements Serializable { // private final String mId; // private final int mType; // // private Membership(String id, int type){ // mId = id; // mType = type; // } // // public String getId() { // return mId; // } // // public int getType(){ // return mType; // } // // final public String getTigerType() { // if(mType==1){ // return "TigerXbox"; // } else { // return "TigerPSN"; // } // } // // public static Membership fromJson(JSONObject jsonObject) { // return new Membership(jsonObject.optString("membershipId"), jsonObject.optInt("membershipType")); // } // } // // Path: app/src/main/java/org/swistowski/vaulthelper/models/User.java // public class User implements Serializable { // private static final String LOG_TAG = "models.User"; // private final String mDisplayName; // private final String mPsnId; // private final String mGameTag; // private final boolean mIsPsn; // // private User(String displayName, String psnId, String gameTag) { // mDisplayName = displayName; // mPsnId = psnId; // mIsPsn = !psnId.equals(""); // mGameTag = gameTag; // } // // static public User fromJson(JSONObject data) throws JSONException { // return new User( // data.getJSONObject("user").getString("displayName"), // data.optString("psnId", ""), // data.optString("gamerTag", "") // ); // } // public String getAccountName(){ // return mIsPsn?mPsnId:mGameTag; // } // @Deprecated // private String getDisplayName() { // return mDisplayName; // } // // public int getAccountType() { // return mIsPsn ? 2 : 1; // } // // // } // Path: app/src/main/java/org/swistowski/vaulthelper/storage/Data.java import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import org.swistowski.vaulthelper.models.Membership; import org.swistowski.vaulthelper.models.User; import java.io.Serializable; package org.swistowski.vaulthelper.storage; public class Data implements Serializable { private static final String LOG_TAG = "Database"; private static final Data ourInstance = new Data();
private User mUser;
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/storage/Data.java
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Membership.java // public class Membership implements Serializable { // private final String mId; // private final int mType; // // private Membership(String id, int type){ // mId = id; // mType = type; // } // // public String getId() { // return mId; // } // // public int getType(){ // return mType; // } // // final public String getTigerType() { // if(mType==1){ // return "TigerXbox"; // } else { // return "TigerPSN"; // } // } // // public static Membership fromJson(JSONObject jsonObject) { // return new Membership(jsonObject.optString("membershipId"), jsonObject.optInt("membershipType")); // } // } // // Path: app/src/main/java/org/swistowski/vaulthelper/models/User.java // public class User implements Serializable { // private static final String LOG_TAG = "models.User"; // private final String mDisplayName; // private final String mPsnId; // private final String mGameTag; // private final boolean mIsPsn; // // private User(String displayName, String psnId, String gameTag) { // mDisplayName = displayName; // mPsnId = psnId; // mIsPsn = !psnId.equals(""); // mGameTag = gameTag; // } // // static public User fromJson(JSONObject data) throws JSONException { // return new User( // data.getJSONObject("user").getString("displayName"), // data.optString("psnId", ""), // data.optString("gamerTag", "") // ); // } // public String getAccountName(){ // return mIsPsn?mPsnId:mGameTag; // } // @Deprecated // private String getDisplayName() { // return mDisplayName; // } // // public int getAccountType() { // return mIsPsn ? 2 : 1; // } // // // }
import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import org.swistowski.vaulthelper.models.Membership; import org.swistowski.vaulthelper.models.User; import java.io.Serializable;
package org.swistowski.vaulthelper.storage; public class Data implements Serializable { private static final String LOG_TAG = "Database"; private static final Data ourInstance = new Data(); private User mUser;
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Membership.java // public class Membership implements Serializable { // private final String mId; // private final int mType; // // private Membership(String id, int type){ // mId = id; // mType = type; // } // // public String getId() { // return mId; // } // // public int getType(){ // return mType; // } // // final public String getTigerType() { // if(mType==1){ // return "TigerXbox"; // } else { // return "TigerPSN"; // } // } // // public static Membership fromJson(JSONObject jsonObject) { // return new Membership(jsonObject.optString("membershipId"), jsonObject.optInt("membershipType")); // } // } // // Path: app/src/main/java/org/swistowski/vaulthelper/models/User.java // public class User implements Serializable { // private static final String LOG_TAG = "models.User"; // private final String mDisplayName; // private final String mPsnId; // private final String mGameTag; // private final boolean mIsPsn; // // private User(String displayName, String psnId, String gameTag) { // mDisplayName = displayName; // mPsnId = psnId; // mIsPsn = !psnId.equals(""); // mGameTag = gameTag; // } // // static public User fromJson(JSONObject data) throws JSONException { // return new User( // data.getJSONObject("user").getString("displayName"), // data.optString("psnId", ""), // data.optString("gamerTag", "") // ); // } // public String getAccountName(){ // return mIsPsn?mPsnId:mGameTag; // } // @Deprecated // private String getDisplayName() { // return mDisplayName; // } // // public int getAccountType() { // return mIsPsn ? 2 : 1; // } // // // } // Path: app/src/main/java/org/swistowski/vaulthelper/storage/Data.java import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import org.swistowski.vaulthelper.models.Membership; import org.swistowski.vaulthelper.models.User; import java.io.Serializable; package org.swistowski.vaulthelper.storage; public class Data implements Serializable { private static final String LOG_TAG = "Database"; private static final Data ourInstance = new Data(); private User mUser;
private Membership mMembership;
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/views/LabelView.java
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Label.java // public class Label implements Serializable { // private String name; // private long id; // private long color; // // public Label(String name, long id, long color) { // this.name = name; // this.id = id; // this.color = color; // } // // public long getId() { // return id; // } // // @Override // public String toString() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setColor(long color){ // this.color = color; // } // public long getColor(){ // return color; // } // // public void save() { // if(id==-1){ // Labels.getInstance().add(this); // } else { // Labels.getInstance().update(this); // } // } // // public void setId(long id) { // this.id = id; // } // // public void delete() { // Labels.getInstance().delete(this); // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.FrameLayout; import android.widget.TextView; import org.swistowski.vaulthelper.R; import org.swistowski.vaulthelper.models.Label;
package org.swistowski.vaulthelper.views; /** * Created by damian on 30.10.15. */ public class LabelView extends FrameLayout { private static final String LOG_TAG = "LabelView"; public LabelView(Context context) { super(context); init(); } public LabelView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public LabelView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { LayoutInflater.from(getContext()).inflate(R.layout.label_view, this, true); }
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Label.java // public class Label implements Serializable { // private String name; // private long id; // private long color; // // public Label(String name, long id, long color) { // this.name = name; // this.id = id; // this.color = color; // } // // public long getId() { // return id; // } // // @Override // public String toString() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setColor(long color){ // this.color = color; // } // public long getColor(){ // return color; // } // // public void save() { // if(id==-1){ // Labels.getInstance().add(this); // } else { // Labels.getInstance().update(this); // } // } // // public void setId(long id) { // this.id = id; // } // // public void delete() { // Labels.getInstance().delete(this); // } // } // Path: app/src/main/java/org/swistowski/vaulthelper/views/LabelView.java import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.FrameLayout; import android.widget.TextView; import org.swistowski.vaulthelper.R; import org.swistowski.vaulthelper.models.Label; package org.swistowski.vaulthelper.views; /** * Created by damian on 30.10.15. */ public class LabelView extends FrameLayout { private static final String LOG_TAG = "LabelView"; public LabelView(Context context) { super(context); init(); } public LabelView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public LabelView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { LayoutInflater.from(getContext()).inflate(R.layout.label_view, this, true); }
public void setLabel(Label label) {
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/models/Character.java
// Path: app/src/main/java/org/swistowski/vaulthelper/storage/Preferences.java // public class Preferences implements SharedPreferences.OnSharedPreferenceChangeListener { // private static Preferences instance; // private Context context; // private String Pr; // // private Preferences(Context context) { // this.context = context; // PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this); // } // // public static Preferences getInstance() { // return instance; // } // // public static Preferences getInstance(Context context) { // if (instance == null) { // instance = new Preferences(context); // } else { // instance.context = context; // } // return instance; // } // // public int tabStyle() { // return Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString("tab_style", "0")); // } // // public boolean showAll() { // return PreferenceManager.getDefaultSharedPreferences(context).getBoolean("show_all", true); // } // // @Override // public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // if (key.equals("tab_style")) { // ItemMonitor.getInstance().notifyChanged(); // } else if (key.equals("show_all")) { // ItemMonitor.getInstance().notifyChanged(); // } else if (key.equals("ordering")) { // ItemMonitor.getInstance().notifyChanged(); // Ordering.getInstance().notifyChanged(); // } // // Log.v("Preferences", "key changed: " + key + " " + sharedPreferences.toString()); // } // // public String getOrdering() { // return PreferenceManager.getDefaultSharedPreferences(context).getString("ordering", "light_10"); // } // // public void setOrdering(String ordering) { // SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); // editor.putString("ordering", ordering); // editor.apply(); // } // }
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.swistowski.vaulthelper.storage.Preferences; import java.io.Serializable; import java.util.ArrayList;
return "Human"; } return "Unknown"; } String getRaceSymbol() { return getRaceName().substring(0, 1); } public String getBackgroundPath() { return mBackgroundPath; } public String getEmblemPath() { return mEmblemPath; } public String getLabel(int i) { switch (i) { case APPEARANCE_SHORT: return "<b>" + getClassName() + "</b> " + mLevel; case APPEARANCE_LONG: return "<b>" + mLevel + " " + getClassName() + "</b> " + getRaceName() + " " + getGenderName(); case APPEARANCE_MEDIUM: return "<b>" + mLevel + " " + getClassName() + "</b> " + getRaceSymbol() + getGenderSymbol(); } return "<b>" + getClassName() + "</b> " + mLevel; } public String getLabel() {
// Path: app/src/main/java/org/swistowski/vaulthelper/storage/Preferences.java // public class Preferences implements SharedPreferences.OnSharedPreferenceChangeListener { // private static Preferences instance; // private Context context; // private String Pr; // // private Preferences(Context context) { // this.context = context; // PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this); // } // // public static Preferences getInstance() { // return instance; // } // // public static Preferences getInstance(Context context) { // if (instance == null) { // instance = new Preferences(context); // } else { // instance.context = context; // } // return instance; // } // // public int tabStyle() { // return Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(context).getString("tab_style", "0")); // } // // public boolean showAll() { // return PreferenceManager.getDefaultSharedPreferences(context).getBoolean("show_all", true); // } // // @Override // public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // if (key.equals("tab_style")) { // ItemMonitor.getInstance().notifyChanged(); // } else if (key.equals("show_all")) { // ItemMonitor.getInstance().notifyChanged(); // } else if (key.equals("ordering")) { // ItemMonitor.getInstance().notifyChanged(); // Ordering.getInstance().notifyChanged(); // } // // Log.v("Preferences", "key changed: " + key + " " + sharedPreferences.toString()); // } // // public String getOrdering() { // return PreferenceManager.getDefaultSharedPreferences(context).getString("ordering", "light_10"); // } // // public void setOrdering(String ordering) { // SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); // editor.putString("ordering", ordering); // editor.apply(); // } // } // Path: app/src/main/java/org/swistowski/vaulthelper/models/Character.java import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.swistowski.vaulthelper.storage.Preferences; import java.io.Serializable; import java.util.ArrayList; return "Human"; } return "Unknown"; } String getRaceSymbol() { return getRaceName().substring(0, 1); } public String getBackgroundPath() { return mBackgroundPath; } public String getEmblemPath() { return mEmblemPath; } public String getLabel(int i) { switch (i) { case APPEARANCE_SHORT: return "<b>" + getClassName() + "</b> " + mLevel; case APPEARANCE_LONG: return "<b>" + mLevel + " " + getClassName() + "</b> " + getRaceName() + " " + getGenderName(); case APPEARANCE_MEDIUM: return "<b>" + mLevel + " " + getClassName() + "</b> " + getRaceSymbol() + getGenderSymbol(); } return "<b>" + getClassName() + "</b> " + mLevel; } public String getLabel() {
return getLabel(Preferences.getInstance().tabStyle());
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/storage/Characters.java
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Character.java // public class Character implements Serializable { // private static final String LOG_TAG = "ModelCharacter"; // private static final long GENDER_FEMALE = 2204441813L; // private static final long GENDER_MALE = 3111576190L; // private static final long RACE_EXO = 898834093L; // private static final long RACE_AWOKEN = 2803282938L; // private static final long RACE_HUMAN = 3887404748L; // private static final int APPEARANCE_SHORT = 0; // private static final int APPEARANCE_LONG = 1; // private static final int APPEARANCE_MEDIUM = 2; // private final int mClassType; // private final int mLevel; // private final String mEmblemPath; // private final String mBackgroundPath; // private final String mId; // private final long mGenderHash; // private final long mRaceHash; // // private Character(final String characterId, final int classType, final int level, final String emblemPath, final String backgroundPath, final long raceHash, final long genderHash) { // mId = characterId; // mLevel = level; // mClassType = classType; // mEmblemPath = emblemPath; // mBackgroundPath = backgroundPath; // mRaceHash = raceHash; // mGenderHash = genderHash; // } // // static public ArrayList<Character> collectionFromJson(JSONArray data) throws JSONException { // ArrayList<Character> collection = new ArrayList<>(); // // for (int i = 0; i < data.length(); i++) { // final Character c = Character.fromJson(data.getJSONObject(i)); // collection.add(c); // } // return collection; // } // // private static Character fromJson(JSONObject data) throws JSONException { // return new Character( // data.getJSONObject("characterBase").getString("characterId"), // data.getJSONObject("characterBase").getInt("classType"), // data.getInt("characterLevel"), // data.optString("emblemPath", ""), // data.optString("backgroundPath", ""), // data.getJSONObject("characterBase").optLong("raceHash"), // data.getJSONObject("characterBase").optLong("genderHash") // ); // } // // public String getId() { // return mId; // } // // String getClassName() { // switch (mClassType) { // case 0: // return "Titan"; // case 1: // return "Hunter"; // default: // return "Warlock"; // } // } // // String getGenderName() { // if (mGenderHash == GENDER_FEMALE) { // return "Female"; // } else if (mGenderHash == GENDER_MALE) { // return "Male"; // } // return "Unknown"; // } // // String getGenderSymbol() { // if (mGenderHash == GENDER_FEMALE) { // return "♀"; // } else if (mGenderHash == GENDER_MALE) { // return "♂"; // } // return ""; // } // // String getRaceName() { // if (mRaceHash == RACE_EXO) { // return "Exo"; // } else if (mRaceHash == RACE_AWOKEN) { // return "Awoken"; // } else if (mRaceHash == RACE_HUMAN) { // return "Human"; // } // return "Unknown"; // } // // String getRaceSymbol() { // return getRaceName().substring(0, 1); // } // // public String getBackgroundPath() { // return mBackgroundPath; // } // // public String getEmblemPath() { // return mEmblemPath; // } // // public String getLabel(int i) { // switch (i) { // case APPEARANCE_SHORT: // return "<b>" + getClassName() + "</b> " + mLevel; // case APPEARANCE_LONG: // return "<b>" + mLevel + " " + getClassName() + "</b> " + getRaceName() + " " + getGenderName(); // case APPEARANCE_MEDIUM: // return "<b>" + mLevel + " " + getClassName() + "</b> " + getRaceSymbol() + getGenderSymbol(); // } // return "<b>" + getClassName() + "</b> " + mLevel; // } // // public String getLabel() { // return getLabel(Preferences.getInstance().tabStyle()); // } // }
import org.json.JSONArray; import org.json.JSONException; import org.swistowski.vaulthelper.models.Character; import java.util.List;
package org.swistowski.vaulthelper.storage; /** * Store information about characters */ public class Characters { public static Characters mInstance = new Characters(); private Characters(){} public static Characters getInstance(){ return mInstance; }
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Character.java // public class Character implements Serializable { // private static final String LOG_TAG = "ModelCharacter"; // private static final long GENDER_FEMALE = 2204441813L; // private static final long GENDER_MALE = 3111576190L; // private static final long RACE_EXO = 898834093L; // private static final long RACE_AWOKEN = 2803282938L; // private static final long RACE_HUMAN = 3887404748L; // private static final int APPEARANCE_SHORT = 0; // private static final int APPEARANCE_LONG = 1; // private static final int APPEARANCE_MEDIUM = 2; // private final int mClassType; // private final int mLevel; // private final String mEmblemPath; // private final String mBackgroundPath; // private final String mId; // private final long mGenderHash; // private final long mRaceHash; // // private Character(final String characterId, final int classType, final int level, final String emblemPath, final String backgroundPath, final long raceHash, final long genderHash) { // mId = characterId; // mLevel = level; // mClassType = classType; // mEmblemPath = emblemPath; // mBackgroundPath = backgroundPath; // mRaceHash = raceHash; // mGenderHash = genderHash; // } // // static public ArrayList<Character> collectionFromJson(JSONArray data) throws JSONException { // ArrayList<Character> collection = new ArrayList<>(); // // for (int i = 0; i < data.length(); i++) { // final Character c = Character.fromJson(data.getJSONObject(i)); // collection.add(c); // } // return collection; // } // // private static Character fromJson(JSONObject data) throws JSONException { // return new Character( // data.getJSONObject("characterBase").getString("characterId"), // data.getJSONObject("characterBase").getInt("classType"), // data.getInt("characterLevel"), // data.optString("emblemPath", ""), // data.optString("backgroundPath", ""), // data.getJSONObject("characterBase").optLong("raceHash"), // data.getJSONObject("characterBase").optLong("genderHash") // ); // } // // public String getId() { // return mId; // } // // String getClassName() { // switch (mClassType) { // case 0: // return "Titan"; // case 1: // return "Hunter"; // default: // return "Warlock"; // } // } // // String getGenderName() { // if (mGenderHash == GENDER_FEMALE) { // return "Female"; // } else if (mGenderHash == GENDER_MALE) { // return "Male"; // } // return "Unknown"; // } // // String getGenderSymbol() { // if (mGenderHash == GENDER_FEMALE) { // return "♀"; // } else if (mGenderHash == GENDER_MALE) { // return "♂"; // } // return ""; // } // // String getRaceName() { // if (mRaceHash == RACE_EXO) { // return "Exo"; // } else if (mRaceHash == RACE_AWOKEN) { // return "Awoken"; // } else if (mRaceHash == RACE_HUMAN) { // return "Human"; // } // return "Unknown"; // } // // String getRaceSymbol() { // return getRaceName().substring(0, 1); // } // // public String getBackgroundPath() { // return mBackgroundPath; // } // // public String getEmblemPath() { // return mEmblemPath; // } // // public String getLabel(int i) { // switch (i) { // case APPEARANCE_SHORT: // return "<b>" + getClassName() + "</b> " + mLevel; // case APPEARANCE_LONG: // return "<b>" + mLevel + " " + getClassName() + "</b> " + getRaceName() + " " + getGenderName(); // case APPEARANCE_MEDIUM: // return "<b>" + mLevel + " " + getClassName() + "</b> " + getRaceSymbol() + getGenderSymbol(); // } // return "<b>" + getClassName() + "</b> " + mLevel; // } // // public String getLabel() { // return getLabel(Preferences.getInstance().tabStyle()); // } // } // Path: app/src/main/java/org/swistowski/vaulthelper/storage/Characters.java import org.json.JSONArray; import org.json.JSONException; import org.swistowski.vaulthelper.models.Character; import java.util.List; package org.swistowski.vaulthelper.storage; /** * Store information about characters */ public class Characters { public static Characters mInstance = new Characters(); private Characters(){} public static Characters getInstance(){ return mInstance; }
private List<Character> mCharacters;
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/db/DB.java
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Label.java // public class Label implements Serializable { // private String name; // private long id; // private long color; // // public Label(String name, long id, long color) { // this.name = name; // this.id = id; // this.color = color; // } // // public long getId() { // return id; // } // // @Override // public String toString() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setColor(long color){ // this.color = color; // } // public long getColor(){ // return color; // } // // public void save() { // if(id==-1){ // Labels.getInstance().add(this); // } else { // Labels.getInstance().update(this); // } // } // // public void setId(long id) { // this.id = id; // } // // public void delete() { // Labels.getInstance().delete(this); // } // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import org.swistowski.vaulthelper.models.Label; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Set;
private DBHelper helper; private SQLiteDatabase database; public DB(Context context) { helper = new DBHelper(context); database = helper.getWritableDatabase(); } public HashMap<Long, Set<Long>> getAllItems() { String[] cols = new String[]{DBHelper.TABLE_ITEMS_COL_LABEL_ID, DBHelper.TABLE_ITEMS_COL_ITEM}; Cursor cursor = database.query(true, DBHelper.TABLE_ITEMS_NAME, cols, null, null, null, null, null, null); /* if (cursor != null) { cursor.moveToFirst(); }*/ HashMap<Long, Set<Long>> allItems = new HashMap<>(); while (cursor.moveToNext()) { Long labelId = cursor.getLong(0); Long item = cursor.getLong(1); if (allItems.get(labelId) == null) { allItems.put(labelId, new HashSet<Long>()); } allItems.get(labelId).add(item); } cursor.close(); return allItems; } ;
// Path: app/src/main/java/org/swistowski/vaulthelper/models/Label.java // public class Label implements Serializable { // private String name; // private long id; // private long color; // // public Label(String name, long id, long color) { // this.name = name; // this.id = id; // this.color = color; // } // // public long getId() { // return id; // } // // @Override // public String toString() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setColor(long color){ // this.color = color; // } // public long getColor(){ // return color; // } // // public void save() { // if(id==-1){ // Labels.getInstance().add(this); // } else { // Labels.getInstance().update(this); // } // } // // public void setId(long id) { // this.id = id; // } // // public void delete() { // Labels.getInstance().delete(this); // } // } // Path: app/src/main/java/org/swistowski/vaulthelper/db/DB.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import org.swistowski.vaulthelper.models.Label; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; private DBHelper helper; private SQLiteDatabase database; public DB(Context context) { helper = new DBHelper(context); database = helper.getWritableDatabase(); } public HashMap<Long, Set<Long>> getAllItems() { String[] cols = new String[]{DBHelper.TABLE_ITEMS_COL_LABEL_ID, DBHelper.TABLE_ITEMS_COL_ITEM}; Cursor cursor = database.query(true, DBHelper.TABLE_ITEMS_NAME, cols, null, null, null, null, null, null); /* if (cursor != null) { cursor.moveToFirst(); }*/ HashMap<Long, Set<Long>> allItems = new HashMap<>(); while (cursor.moveToNext()) { Long labelId = cursor.getLong(0); Long item = cursor.getLong(1); if (allItems.get(labelId) == null) { allItems.put(labelId, new HashSet<Long>()); } allItems.get(labelId).add(item); } cursor.close(); return allItems; } ;
public Collection<Label> getLabels() {
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/models/Label.java
// Path: app/src/main/java/org/swistowski/vaulthelper/storage/Labels.java // public class Labels { // // private DB mDb; // private static Labels mInstance = new Labels(); // private Context context; // private HashMap<Long, Set<Long>> items; // private HashMap<Long, Label> labels; // private HashMap<Long, Set<Long>> itemLabels; // private List<Label> labelsList; // // private long current = -1; // // // private Labels() { // } // // public static Labels getInstance() { // return mInstance; // } // // public DB getDb() { // if (mDb == null) { // mDb = new DB(getContext()); // } // return mDb; // } // // private HashMap<Long, Set<Long>> getItems() { // if (items == null) { // items = getDb().getAllItems(); // } // return items; // } // // public List<Label> getLabelList() { // if (labelsList == null) { // Collection<Label> labelsFromDb = getDb().getLabels(); // labelsList = new ArrayList<>(labelsFromDb); // } // return labelsList; // } // // // public Map<Long, Label> getLabels() { // if (labels == null) { // labels = new HashMap<>(); // for (Label label : getLabelList()) { // labels.put(label.getId(), label); // } // } // return labels; // } // // private Set<Long> getLabelItems(Long labelId) { // if(!getItems().containsKey(labelId)){ // getItems().put(labelId, new HashSet<Long>()); // } // return getItems().get(labelId); // } // // public void addLabelToItem(long item, long labelId) { // getDb().addItem(item, labelId); // getLabelItems(labelId).add(item); // } // // public void deleteLabelFromItem(long item, long labelId) { // getDb().deleteItem(item, labelId); // getLabelItems(labelId).remove(item); // } // // public boolean hasLabel(long item, long labelId) { // return getLabelItems(labelId).contains(item); // } // // public void setContext(Context context) { // this.context = context; // } // // public Context getContext() { // return context; // } // // public int count() { // return getItems().size(); // } // // public long getCurrent() { // if(current==-1){ // current = getLabelList().get(0).getId(); // } // return current; // } // // public void setCurrent(long current){ // this.current = current; // ItemMonitor.getInstance().notifyChanged(); // //LabelMonitor.getInstance().notifyChanged(); // } // // // public Label add(Label label) { // label.setId(getDb().addLabel(label.getName(), label.getColor())); // cleanLocalCache(); // LabelMonitor.getInstance().notifyChanged(); // return label; // } // // private void cleanLocalCache() { // labelsList = null; // labels = null; // items = null; // itemLabels = null; // } // // public void update(Label label) { // getDb().updateLabel(label.getId(), label.getName(), label.getColor()); // LabelMonitor.getInstance().notifyChanged(); // } // // public void delete(Label label) { // getDb().deleteLabel(label.getId()); // cleanLocalCache(); // if(current==label.getId()){ // current = -1; // } // LabelMonitor.getInstance().notifyChanged(); // } // // private Map<Long, Set<Long>> getItemLabels(){ // if(itemLabels==null) { // itemLabels = new HashMap<>(); // for(Map.Entry<Long, Set<Long>> entry: getItems().entrySet()){ // for (Long itemId : entry.getValue()) { // if(!itemLabels.containsKey(itemId)){ // itemLabels.put(itemId, new HashSet<Long>()); // } // itemLabels.get(itemId).add(entry.getKey()); // } // } // } // return itemLabels; // } // // public List<Label> getLabelsForItem(long itemId) { // LinkedList<Label> labels = new LinkedList<>(); // if(getItemLabels().containsKey(itemId)){ // for (Long labelId : getItemLabels().get(itemId)) { // labels.add(getLabels().get(labelId)); // } // } // return labels; // } // }
import org.swistowski.vaulthelper.storage.Labels; import java.io.Serializable;
this.id = id; this.color = color; } public long getId() { return id; } @Override public String toString() { return name; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setColor(long color){ this.color = color; } public long getColor(){ return color; } public void save() { if(id==-1){
// Path: app/src/main/java/org/swistowski/vaulthelper/storage/Labels.java // public class Labels { // // private DB mDb; // private static Labels mInstance = new Labels(); // private Context context; // private HashMap<Long, Set<Long>> items; // private HashMap<Long, Label> labels; // private HashMap<Long, Set<Long>> itemLabels; // private List<Label> labelsList; // // private long current = -1; // // // private Labels() { // } // // public static Labels getInstance() { // return mInstance; // } // // public DB getDb() { // if (mDb == null) { // mDb = new DB(getContext()); // } // return mDb; // } // // private HashMap<Long, Set<Long>> getItems() { // if (items == null) { // items = getDb().getAllItems(); // } // return items; // } // // public List<Label> getLabelList() { // if (labelsList == null) { // Collection<Label> labelsFromDb = getDb().getLabels(); // labelsList = new ArrayList<>(labelsFromDb); // } // return labelsList; // } // // // public Map<Long, Label> getLabels() { // if (labels == null) { // labels = new HashMap<>(); // for (Label label : getLabelList()) { // labels.put(label.getId(), label); // } // } // return labels; // } // // private Set<Long> getLabelItems(Long labelId) { // if(!getItems().containsKey(labelId)){ // getItems().put(labelId, new HashSet<Long>()); // } // return getItems().get(labelId); // } // // public void addLabelToItem(long item, long labelId) { // getDb().addItem(item, labelId); // getLabelItems(labelId).add(item); // } // // public void deleteLabelFromItem(long item, long labelId) { // getDb().deleteItem(item, labelId); // getLabelItems(labelId).remove(item); // } // // public boolean hasLabel(long item, long labelId) { // return getLabelItems(labelId).contains(item); // } // // public void setContext(Context context) { // this.context = context; // } // // public Context getContext() { // return context; // } // // public int count() { // return getItems().size(); // } // // public long getCurrent() { // if(current==-1){ // current = getLabelList().get(0).getId(); // } // return current; // } // // public void setCurrent(long current){ // this.current = current; // ItemMonitor.getInstance().notifyChanged(); // //LabelMonitor.getInstance().notifyChanged(); // } // // // public Label add(Label label) { // label.setId(getDb().addLabel(label.getName(), label.getColor())); // cleanLocalCache(); // LabelMonitor.getInstance().notifyChanged(); // return label; // } // // private void cleanLocalCache() { // labelsList = null; // labels = null; // items = null; // itemLabels = null; // } // // public void update(Label label) { // getDb().updateLabel(label.getId(), label.getName(), label.getColor()); // LabelMonitor.getInstance().notifyChanged(); // } // // public void delete(Label label) { // getDb().deleteLabel(label.getId()); // cleanLocalCache(); // if(current==label.getId()){ // current = -1; // } // LabelMonitor.getInstance().notifyChanged(); // } // // private Map<Long, Set<Long>> getItemLabels(){ // if(itemLabels==null) { // itemLabels = new HashMap<>(); // for(Map.Entry<Long, Set<Long>> entry: getItems().entrySet()){ // for (Long itemId : entry.getValue()) { // if(!itemLabels.containsKey(itemId)){ // itemLabels.put(itemId, new HashSet<Long>()); // } // itemLabels.get(itemId).add(entry.getKey()); // } // } // } // return itemLabels; // } // // public List<Label> getLabelsForItem(long itemId) { // LinkedList<Label> labels = new LinkedList<>(); // if(getItemLabels().containsKey(itemId)){ // for (Long labelId : getItemLabels().get(itemId)) { // labels.add(getLabels().get(labelId)); // } // } // return labels; // } // } // Path: app/src/main/java/org/swistowski/vaulthelper/models/Label.java import org.swistowski.vaulthelper.storage.Labels; import java.io.Serializable; this.id = id; this.color = color; } public long getId() { return id; } @Override public String toString() { return name; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setColor(long color){ this.color = color; } public long getColor(){ return color; } public void save() { if(id==-1){
Labels.getInstance().add(this);
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/activities/LoginActivity.java
// Path: app/src/main/java/org/swistowski/vaulthelper/Application.java // public class Application extends android.app.Application { // private Tracker mTracker; // private ClientWebView mWebView; // // @Override // public void onCreate() // { // mWebView = new ClientWebView(getApplicationContext()); // ImageStorage.getInstance().setContext(getApplicationContext()); // Data.getInstance().setContext(getApplicationContext()); // super.onCreate(); // } // // public ClientWebView getWebView() { // return mWebView; // } // // // public synchronized Tracker getTracker() { // if(mTracker==null){ // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // mTracker = analytics.newTracker(R.xml.global_tracker); // } // return mTracker; // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.Html; import android.view.View; import android.widget.TextView; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import org.swistowski.vaulthelper.Application; import org.swistowski.vaulthelper.R;
intent.putExtra(XONE_URL_ID, xBoxUrl); intent.putExtra(PSN_URL_ID, psnUrl); c.startActivityForResult(intent, LoginActivity.LOGIN_REQUEST); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String url = intent.getStringExtra(XONE_URL_ID); if(url!=null){ xone_url = url; } url = intent.getStringExtra(PSN_URL_ID); if(url!=null){ psn_url = url; } setContentView(R.layout.activity_login); TextView loginInformation = (TextView)findViewById(R.id.loginDetailInformation); loginInformation.setText(Html.fromHtml(getString(R.string.login_information))); } void goToUrl(String url){ Intent i = new Intent(getApplicationContext(), WebViewActivity.class); i.putExtra(URL, url); startActivityForResult(i, LOGIN_REQUEST); } private Tracker getTracker(){
// Path: app/src/main/java/org/swistowski/vaulthelper/Application.java // public class Application extends android.app.Application { // private Tracker mTracker; // private ClientWebView mWebView; // // @Override // public void onCreate() // { // mWebView = new ClientWebView(getApplicationContext()); // ImageStorage.getInstance().setContext(getApplicationContext()); // Data.getInstance().setContext(getApplicationContext()); // super.onCreate(); // } // // public ClientWebView getWebView() { // return mWebView; // } // // // public synchronized Tracker getTracker() { // if(mTracker==null){ // GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); // mTracker = analytics.newTracker(R.xml.global_tracker); // } // return mTracker; // } // } // Path: app/src/main/java/org/swistowski/vaulthelper/activities/LoginActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.Html; import android.view.View; import android.widget.TextView; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import org.swistowski.vaulthelper.Application; import org.swistowski.vaulthelper.R; intent.putExtra(XONE_URL_ID, xBoxUrl); intent.putExtra(PSN_URL_ID, psnUrl); c.startActivityForResult(intent, LoginActivity.LOGIN_REQUEST); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String url = intent.getStringExtra(XONE_URL_ID); if(url!=null){ xone_url = url; } url = intent.getStringExtra(PSN_URL_ID); if(url!=null){ psn_url = url; } setContentView(R.layout.activity_login); TextView loginInformation = (TextView)findViewById(R.id.loginDetailInformation); loginInformation.setText(Html.fromHtml(getString(R.string.login_information))); } void goToUrl(String url){ Intent i = new Intent(getApplicationContext(), WebViewActivity.class); i.putExtra(URL, url); startActivityForResult(i, LOGIN_REQUEST); } private Tracker getTracker(){
return ((Application) getApplication()).getTracker();
DestinyVaultHelper/dvh
app/src/main/java/org/swistowski/vaulthelper/views/BackgroundDrawable.java
// Path: app/src/main/java/org/swistowski/vaulthelper/util/ImageStorage.java // public class ImageStorage { // private static final ImageStorage ourInstance = new ImageStorage(); // // private final HashMap<String, Bitmap> cachedImages = new HashMap<String, Bitmap>(); // private Context mContext; // // private ImageStorage() { // } // // public static ImageStorage getInstance() { // return ourInstance; // } // /* // private static String md5(final String s) { // final String MD5 = "MD5"; // try { // // Create MD5 Hash // MessageDigest digest = java.security.MessageDigest.getInstance(MD5); // digest.update(s.getBytes()); // byte messageDigest[] = digest.digest(); // // // Create Hex String // StringBuilder hexString = new StringBuilder(); // for (byte aMessageDigest : messageDigest) { // String h = Integer.toHexString(0xFF & aMessageDigest); // while (h.length() < 2) // h = "0" + h; // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return ""; // } // */ // // /* // public boolean hasImage(long url) { // if (!cachedImages.containsKey(url)) { // try { // FileInputStream fis = mContext.openFileInput(md5(url)); // Bitmap bitmap = BitmapFactory.decodeStream(fis); // cachedImages.put(url, bitmap); // } catch (FileNotFoundException e) { // //e.printStackTrace(); // } // } // return cachedImages.containsKey(url); // } // */ // // public Bitmap getImage(long itemHash) { // return getImage(itemHash+""); // } // // public Bitmap getImage(String itemHash){ // try{ // FileInputStream fis = mContext.openFileInput(itemHash+".png"); // return BitmapFactory.decodeStream(fis); // } catch (FileNotFoundException e){ // return null; // } // } // // private void saveImage(String itemHash, Bitmap bitmap) { // try { // FileOutputStream fos = mContext.openFileOutput(itemHash+".png", Context.MODE_PRIVATE); // bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); // fos.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public void setContext(Context context) { // this.mContext = context; // } // // public DownloadImageTask fetchImage(final String itemHash, final String url, final UrlFetchWaiter ufw) { // Bitmap bmp = getImage(itemHash); // if(bmp!=null){ // ufw.onImageFetched(bmp); // } else { // DownloadImageTask dit = new DownloadImageTask(new UrlFetchWaiter() { // @Override // public void onImageFetched(Bitmap bitmap) { // saveImage(itemHash, bitmap); // ufw.onImageFetched(bitmap); // } // }); // dit.execute(url); // return dit; // } // return null; // } // // public interface UrlFetchWaiter { // public void onImageFetched(Bitmap bitmap); // } // // public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { // private final UrlFetchWaiter ufw; // // public DownloadImageTask(UrlFetchWaiter ufw) { // this.ufw = ufw; // } // // @Override // protected Bitmap doInBackground(String... urls) { // URL url; // try { // url = new URL("http://www.bungie.net" + urls[0]); // } catch (MalformedURLException e) { // e.printStackTrace(); // return null; // } // Bitmap bmp = null; // try { // bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); // } catch (IOException e) { // e.printStackTrace(); // } // return bmp; // } // // @Override // protected void onPostExecute(Bitmap result) { // if (result != null) { // ufw.onImageFetched(result); // } // } // } // // }
import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import org.swistowski.vaulthelper.util.ImageStorage;
package org.swistowski.vaulthelper.views; /** * Created by damian on 23.06.15. */ public class BackgroundDrawable extends Drawable { private Paint mPaint; private final String mEmblemHash; private final String mBackgroupdHash; public BackgroundDrawable(String emblemPath, String backgroundPath) { mPaint = new Paint(); mEmblemHash = emblemPath.replace('/', '-'); mBackgroupdHash = backgroundPath.replace('/', '-');
// Path: app/src/main/java/org/swistowski/vaulthelper/util/ImageStorage.java // public class ImageStorage { // private static final ImageStorage ourInstance = new ImageStorage(); // // private final HashMap<String, Bitmap> cachedImages = new HashMap<String, Bitmap>(); // private Context mContext; // // private ImageStorage() { // } // // public static ImageStorage getInstance() { // return ourInstance; // } // /* // private static String md5(final String s) { // final String MD5 = "MD5"; // try { // // Create MD5 Hash // MessageDigest digest = java.security.MessageDigest.getInstance(MD5); // digest.update(s.getBytes()); // byte messageDigest[] = digest.digest(); // // // Create Hex String // StringBuilder hexString = new StringBuilder(); // for (byte aMessageDigest : messageDigest) { // String h = Integer.toHexString(0xFF & aMessageDigest); // while (h.length() < 2) // h = "0" + h; // hexString.append(h); // } // return hexString.toString(); // // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return ""; // } // */ // // /* // public boolean hasImage(long url) { // if (!cachedImages.containsKey(url)) { // try { // FileInputStream fis = mContext.openFileInput(md5(url)); // Bitmap bitmap = BitmapFactory.decodeStream(fis); // cachedImages.put(url, bitmap); // } catch (FileNotFoundException e) { // //e.printStackTrace(); // } // } // return cachedImages.containsKey(url); // } // */ // // public Bitmap getImage(long itemHash) { // return getImage(itemHash+""); // } // // public Bitmap getImage(String itemHash){ // try{ // FileInputStream fis = mContext.openFileInput(itemHash+".png"); // return BitmapFactory.decodeStream(fis); // } catch (FileNotFoundException e){ // return null; // } // } // // private void saveImage(String itemHash, Bitmap bitmap) { // try { // FileOutputStream fos = mContext.openFileOutput(itemHash+".png", Context.MODE_PRIVATE); // bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); // fos.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public void setContext(Context context) { // this.mContext = context; // } // // public DownloadImageTask fetchImage(final String itemHash, final String url, final UrlFetchWaiter ufw) { // Bitmap bmp = getImage(itemHash); // if(bmp!=null){ // ufw.onImageFetched(bmp); // } else { // DownloadImageTask dit = new DownloadImageTask(new UrlFetchWaiter() { // @Override // public void onImageFetched(Bitmap bitmap) { // saveImage(itemHash, bitmap); // ufw.onImageFetched(bitmap); // } // }); // dit.execute(url); // return dit; // } // return null; // } // // public interface UrlFetchWaiter { // public void onImageFetched(Bitmap bitmap); // } // // public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { // private final UrlFetchWaiter ufw; // // public DownloadImageTask(UrlFetchWaiter ufw) { // this.ufw = ufw; // } // // @Override // protected Bitmap doInBackground(String... urls) { // URL url; // try { // url = new URL("http://www.bungie.net" + urls[0]); // } catch (MalformedURLException e) { // e.printStackTrace(); // return null; // } // Bitmap bmp = null; // try { // bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); // } catch (IOException e) { // e.printStackTrace(); // } // return bmp; // } // // @Override // protected void onPostExecute(Bitmap result) { // if (result != null) { // ufw.onImageFetched(result); // } // } // } // // } // Path: app/src/main/java/org/swistowski/vaulthelper/views/BackgroundDrawable.java import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import org.swistowski.vaulthelper.util.ImageStorage; package org.swistowski.vaulthelper.views; /** * Created by damian on 23.06.15. */ public class BackgroundDrawable extends Drawable { private Paint mPaint; private final String mEmblemHash; private final String mBackgroupdHash; public BackgroundDrawable(String emblemPath, String backgroundPath) { mPaint = new Paint(); mEmblemHash = emblemPath.replace('/', '-'); mBackgroupdHash = backgroundPath.replace('/', '-');
if (ImageStorage.getInstance().getImage(mEmblemHash) == null) {
jgilfelt/Novocation
core/src/main/java/com/novoda/location/Locator.java
// Path: core/src/main/java/com/novoda/location/exception/NoProviderAvailable.java // public class NoProviderAvailable extends Exception { // // private static final long serialVersionUID = 1L; // // }
import com.novoda.location.exception.NoProviderAvailable; import android.content.Context; import android.location.Location;
/** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location; public interface Locator { void prepare(Context c, LocatorSettings settings); Location getLocation(); void setLocation(Location location); LocatorSettings getSettings();
// Path: core/src/main/java/com/novoda/location/exception/NoProviderAvailable.java // public class NoProviderAvailable extends Exception { // // private static final long serialVersionUID = 1L; // // } // Path: core/src/main/java/com/novoda/location/Locator.java import com.novoda.location.exception.NoProviderAvailable; import android.content.Context; import android.location.Location; /** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location; public interface Locator { void prepare(Context c, LocatorSettings settings); Location getLocation(); void setLocation(Location location); LocatorSettings getSettings();
void startLocationUpdates() throws NoProviderAvailable;
jgilfelt/Novocation
core/src/main/java/com/novoda/location/receiver/LocationChanged.java
// Path: core/src/main/java/com/novoda/location/Constants.java // public interface Constants { // // boolean USE_GPS = true; // boolean REFRESH_DATA_ON_LOCATION_CHANGED = true; // boolean ENABLE_PASSIVE_UPDATES = false; // // int UPDATES_MAX_DISTANCE = 100; // long UPDATES_MAX_TIME = 5 * 60 * 1000; // // long DEFAULT_INTERVAL_PASSIVE = 15 * 60 * 1000; // int DEFAULT_DISTANCE_PASSIVE = 300; // // String ACTIVE_LOCATION_UPDATE_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION"; // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import com.novoda.location.Constants; import com.novoda.location.LocatorFactory;
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class LocationChanged extends BroadcastReceiver { @Override public void onReceive(Context context, Intent i) { if(i == null) { return; } if(providerStatusHasChanged(i)){ broadcastProviderStatusHasChanged(context, i); } if (locationHasChanged(i)) {
// Path: core/src/main/java/com/novoda/location/Constants.java // public interface Constants { // // boolean USE_GPS = true; // boolean REFRESH_DATA_ON_LOCATION_CHANGED = true; // boolean ENABLE_PASSIVE_UPDATES = false; // // int UPDATES_MAX_DISTANCE = 100; // long UPDATES_MAX_TIME = 5 * 60 * 1000; // // long DEFAULT_INTERVAL_PASSIVE = 15 * 60 * 1000; // int DEFAULT_DISTANCE_PASSIVE = 300; // // String ACTIVE_LOCATION_UPDATE_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION"; // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // Path: core/src/main/java/com/novoda/location/receiver/LocationChanged.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import com.novoda.location.Constants; import com.novoda.location.LocatorFactory; /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class LocationChanged extends BroadcastReceiver { @Override public void onReceive(Context context, Intent i) { if(i == null) { return; } if(providerStatusHasChanged(i)){ broadcastProviderStatusHasChanged(context, i); } if (locationHasChanged(i)) {
LocatorFactory.setLocation(getLocation(i));
jgilfelt/Novocation
core/src/main/java/com/novoda/location/receiver/LocationChanged.java
// Path: core/src/main/java/com/novoda/location/Constants.java // public interface Constants { // // boolean USE_GPS = true; // boolean REFRESH_DATA_ON_LOCATION_CHANGED = true; // boolean ENABLE_PASSIVE_UPDATES = false; // // int UPDATES_MAX_DISTANCE = 100; // long UPDATES_MAX_TIME = 5 * 60 * 1000; // // long DEFAULT_INTERVAL_PASSIVE = 15 * 60 * 1000; // int DEFAULT_DISTANCE_PASSIVE = 300; // // String ACTIVE_LOCATION_UPDATE_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION"; // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import com.novoda.location.Constants; import com.novoda.location.LocatorFactory;
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class LocationChanged extends BroadcastReceiver { @Override public void onReceive(Context context, Intent i) { if(i == null) { return; } if(providerStatusHasChanged(i)){ broadcastProviderStatusHasChanged(context, i); } if (locationHasChanged(i)) { LocatorFactory.setLocation(getLocation(i)); } } private boolean providerStatusHasChanged(Intent i) { return i.hasExtra(LocationManager.KEY_PROVIDER_ENABLED); } private void broadcastProviderStatusHasChanged(Context context, Intent i) { Intent providerStatusChanged; if(providerHasBeenEnabled(i)){
// Path: core/src/main/java/com/novoda/location/Constants.java // public interface Constants { // // boolean USE_GPS = true; // boolean REFRESH_DATA_ON_LOCATION_CHANGED = true; // boolean ENABLE_PASSIVE_UPDATES = false; // // int UPDATES_MAX_DISTANCE = 100; // long UPDATES_MAX_TIME = 5 * 60 * 1000; // // long DEFAULT_INTERVAL_PASSIVE = 15 * 60 * 1000; // int DEFAULT_DISTANCE_PASSIVE = 300; // // String ACTIVE_LOCATION_UPDATE_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION"; // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // Path: core/src/main/java/com/novoda/location/receiver/LocationChanged.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import com.novoda.location.Constants; import com.novoda.location.LocatorFactory; /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class LocationChanged extends BroadcastReceiver { @Override public void onReceive(Context context, Intent i) { if(i == null) { return; } if(providerStatusHasChanged(i)){ broadcastProviderStatusHasChanged(context, i); } if (locationHasChanged(i)) { LocatorFactory.setLocation(getLocation(i)); } } private boolean providerStatusHasChanged(Intent i) { return i.hasExtra(LocationManager.KEY_PROVIDER_ENABLED); } private void broadcastProviderStatusHasChanged(Context context, Intent i) { Intent providerStatusChanged; if(providerHasBeenEnabled(i)){
providerStatusChanged = new Intent(Constants.ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION);
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/store/SharedPreferenceSettingsDao.java
// Path: core/src/main/java/com/novoda/location/Constants.java // public interface Constants { // // boolean USE_GPS = true; // boolean REFRESH_DATA_ON_LOCATION_CHANGED = true; // boolean ENABLE_PASSIVE_UPDATES = false; // // int UPDATES_MAX_DISTANCE = 100; // long UPDATES_MAX_TIME = 5 * 60 * 1000; // // long DEFAULT_INTERVAL_PASSIVE = 15 * 60 * 1000; // int DEFAULT_DISTANCE_PASSIVE = 300; // // String ACTIVE_LOCATION_UPDATE_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION"; // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // }
import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import com.novoda.location.Constants; import com.novoda.location.LocatorSettings;
/** * Copyright 2011 Novoda Ltd. * * 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. * * Sections copyright Matthias Kaeppler 2009-2011 based on Ignition-Support. */ package com.novoda.location.provider.store; public class SharedPreferenceSettingsDao implements SettingsDao { private static final String SHARED_PREFERENCE_FILE = "novocation_prefs"; private static final String SP_KEY_RUN_ONCE = "sp_key_run_once"; private static final String SP_KEY_PASSIVE_LOCATION_CHANGES = "sp_key_follow_location_changes"; private static final String SP_KEY_PASSIVE_LOCATION_UPDATES_DISTANCE_DIFF = "sp_passive_location_updates_distance_diff"; private static final String SP_KEY_PASSIVE_LOCATION_UPDATES_INTERVAL = "sp_key_passive_location_updates_interval"; @Override
// Path: core/src/main/java/com/novoda/location/Constants.java // public interface Constants { // // boolean USE_GPS = true; // boolean REFRESH_DATA_ON_LOCATION_CHANGED = true; // boolean ENABLE_PASSIVE_UPDATES = false; // // int UPDATES_MAX_DISTANCE = 100; // long UPDATES_MAX_TIME = 5 * 60 * 1000; // // long DEFAULT_INTERVAL_PASSIVE = 15 * 60 * 1000; // int DEFAULT_DISTANCE_PASSIVE = 300; // // String ACTIVE_LOCATION_UPDATE_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION"; // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // Path: core/src/main/java/com/novoda/location/provider/store/SharedPreferenceSettingsDao.java import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import com.novoda.location.Constants; import com.novoda.location.LocatorSettings; /** * Copyright 2011 Novoda Ltd. * * 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. * * Sections copyright Matthias Kaeppler 2009-2011 based on Ignition-Support. */ package com.novoda.location.provider.store; public class SharedPreferenceSettingsDao implements SettingsDao { private static final String SHARED_PREFERENCE_FILE = "novocation_prefs"; private static final String SP_KEY_RUN_ONCE = "sp_key_run_once"; private static final String SP_KEY_PASSIVE_LOCATION_CHANGES = "sp_key_follow_location_changes"; private static final String SP_KEY_PASSIVE_LOCATION_UPDATES_DISTANCE_DIFF = "sp_passive_location_updates_distance_diff"; private static final String SP_KEY_PASSIVE_LOCATION_UPDATES_INTERVAL = "sp_key_passive_location_updates_interval"; @Override
public void persistSettingsToPreferences(Context context, LocatorSettings settings) {
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/store/SharedPreferenceSettingsDao.java
// Path: core/src/main/java/com/novoda/location/Constants.java // public interface Constants { // // boolean USE_GPS = true; // boolean REFRESH_DATA_ON_LOCATION_CHANGED = true; // boolean ENABLE_PASSIVE_UPDATES = false; // // int UPDATES_MAX_DISTANCE = 100; // long UPDATES_MAX_TIME = 5 * 60 * 1000; // // long DEFAULT_INTERVAL_PASSIVE = 15 * 60 * 1000; // int DEFAULT_DISTANCE_PASSIVE = 300; // // String ACTIVE_LOCATION_UPDATE_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION"; // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // }
import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import com.novoda.location.Constants; import com.novoda.location.LocatorSettings;
/** * Copyright 2011 Novoda Ltd. * * 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. * * Sections copyright Matthias Kaeppler 2009-2011 based on Ignition-Support. */ package com.novoda.location.provider.store; public class SharedPreferenceSettingsDao implements SettingsDao { private static final String SHARED_PREFERENCE_FILE = "novocation_prefs"; private static final String SP_KEY_RUN_ONCE = "sp_key_run_once"; private static final String SP_KEY_PASSIVE_LOCATION_CHANGES = "sp_key_follow_location_changes"; private static final String SP_KEY_PASSIVE_LOCATION_UPDATES_DISTANCE_DIFF = "sp_passive_location_updates_distance_diff"; private static final String SP_KEY_PASSIVE_LOCATION_UPDATES_INTERVAL = "sp_key_passive_location_updates_interval"; @Override public void persistSettingsToPreferences(Context context, LocatorSettings settings) { Editor editor = getSharedPrefs(context).edit(); editor.putBoolean(SP_KEY_PASSIVE_LOCATION_CHANGES, settings.shouldEnablePassiveUpdates()); editor.putInt(SP_KEY_PASSIVE_LOCATION_UPDATES_DISTANCE_DIFF, settings.getPassiveUpdatesDistance()); editor.putLong(SP_KEY_PASSIVE_LOCATION_UPDATES_INTERVAL, settings.getPassiveUpdatesInterval()); editor.putBoolean(SP_KEY_RUN_ONCE, true); editor.commit(); } @Override public long getPassiveLocationInterval(Context context) {
// Path: core/src/main/java/com/novoda/location/Constants.java // public interface Constants { // // boolean USE_GPS = true; // boolean REFRESH_DATA_ON_LOCATION_CHANGED = true; // boolean ENABLE_PASSIVE_UPDATES = false; // // int UPDATES_MAX_DISTANCE = 100; // long UPDATES_MAX_TIME = 5 * 60 * 1000; // // long DEFAULT_INTERVAL_PASSIVE = 15 * 60 * 1000; // int DEFAULT_DISTANCE_PASSIVE = 300; // // String ACTIVE_LOCATION_UPDATE_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED_ACTION"; // String ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION = "com.novoda.location.ACTIVE_LOCATION_UPDATE_PROVIDER_ENABLED_ACTION"; // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // Path: core/src/main/java/com/novoda/location/provider/store/SharedPreferenceSettingsDao.java import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import com.novoda.location.Constants; import com.novoda.location.LocatorSettings; /** * Copyright 2011 Novoda Ltd. * * 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. * * Sections copyright Matthias Kaeppler 2009-2011 based on Ignition-Support. */ package com.novoda.location.provider.store; public class SharedPreferenceSettingsDao implements SettingsDao { private static final String SHARED_PREFERENCE_FILE = "novocation_prefs"; private static final String SP_KEY_RUN_ONCE = "sp_key_run_once"; private static final String SP_KEY_PASSIVE_LOCATION_CHANGES = "sp_key_follow_location_changes"; private static final String SP_KEY_PASSIVE_LOCATION_UPDATES_DISTANCE_DIFF = "sp_passive_location_updates_distance_diff"; private static final String SP_KEY_PASSIVE_LOCATION_UPDATES_INTERVAL = "sp_key_passive_location_updates_interval"; @Override public void persistSettingsToPreferences(Context context, LocatorSettings settings) { Editor editor = getSharedPrefs(context).edit(); editor.putBoolean(SP_KEY_PASSIVE_LOCATION_CHANGES, settings.shouldEnablePassiveUpdates()); editor.putInt(SP_KEY_PASSIVE_LOCATION_UPDATES_DISTANCE_DIFF, settings.getPassiveUpdatesDistance()); editor.putLong(SP_KEY_PASSIVE_LOCATION_UPDATES_INTERVAL, settings.getPassiveUpdatesInterval()); editor.putBoolean(SP_KEY_RUN_ONCE, true); editor.commit(); } @Override public long getPassiveLocationInterval(Context context) {
return getSharedPrefs(context).getLong(SP_KEY_PASSIVE_LOCATION_UPDATES_INTERVAL, Constants.UPDATES_MAX_TIME);
jgilfelt/Novocation
demo/src/com/novoda/locationdemo/LocationDemo.java
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // }
import roboguice.application.RoboApplication; import com.bugsense.trace.BugSenseHandler; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.Locator;
/* * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.locationdemo; public class LocationDemo extends RoboApplication { public static final String PACKAGE_NAME = "com.novoda.locationdemo"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.locationdemo.action.ACTION_FRESH_LOCATION"; //================================================== // TODO
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // Path: demo/src/com/novoda/locationdemo/LocationDemo.java import roboguice.application.RoboApplication; import com.bugsense.trace.BugSenseHandler; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.Locator; /* * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.locationdemo; public class LocationDemo extends RoboApplication { public static final String PACKAGE_NAME = "com.novoda.locationdemo"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.locationdemo.action.ACTION_FRESH_LOCATION"; //================================================== // TODO
private static Locator locator;
jgilfelt/Novocation
demo/src/com/novoda/locationdemo/LocationDemo.java
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // }
import roboguice.application.RoboApplication; import com.bugsense.trace.BugSenseHandler; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.Locator;
/* * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.locationdemo; public class LocationDemo extends RoboApplication { public static final String PACKAGE_NAME = "com.novoda.locationdemo"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.locationdemo.action.ACTION_FRESH_LOCATION"; //================================================== // TODO private static Locator locator; //================================================== @Override public void onCreate() { super.onCreate(); //================================================== // TODO // Connect the location finder with relevant settings.
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // Path: demo/src/com/novoda/locationdemo/LocationDemo.java import roboguice.application.RoboApplication; import com.bugsense.trace.BugSenseHandler; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.Locator; /* * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.locationdemo; public class LocationDemo extends RoboApplication { public static final String PACKAGE_NAME = "com.novoda.locationdemo"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.locationdemo.action.ACTION_FRESH_LOCATION"; //================================================== // TODO private static Locator locator; //================================================== @Override public void onCreate() { super.onCreate(); //================================================== // TODO // Connect the location finder with relevant settings.
LocatorSettings settings = new LocatorSettings(PACKAGE_NAME, LOCATION_UPDATE_ACTION);
jgilfelt/Novocation
demo/src/com/novoda/locationdemo/LocationDemo.java
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // }
import roboguice.application.RoboApplication; import com.bugsense.trace.BugSenseHandler; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.Locator;
/* * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.locationdemo; public class LocationDemo extends RoboApplication { public static final String PACKAGE_NAME = "com.novoda.locationdemo"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.locationdemo.action.ACTION_FRESH_LOCATION"; //================================================== // TODO private static Locator locator; //================================================== @Override public void onCreate() { super.onCreate(); //================================================== // TODO // Connect the location finder with relevant settings. LocatorSettings settings = new LocatorSettings(PACKAGE_NAME, LOCATION_UPDATE_ACTION); settings.setUpdatesInterval(3 * 60 * 1000); settings.setUpdatesDistance(50);
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // Path: demo/src/com/novoda/locationdemo/LocationDemo.java import roboguice.application.RoboApplication; import com.bugsense.trace.BugSenseHandler; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.Locator; /* * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.locationdemo; public class LocationDemo extends RoboApplication { public static final String PACKAGE_NAME = "com.novoda.locationdemo"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.locationdemo.action.ACTION_FRESH_LOCATION"; //================================================== // TODO private static Locator locator; //================================================== @Override public void onCreate() { super.onCreate(); //================================================== // TODO // Connect the location finder with relevant settings. LocatorSettings settings = new LocatorSettings(PACKAGE_NAME, LOCATION_UPDATE_ACTION); settings.setUpdatesInterval(3 * 60 * 1000); settings.setUpdatesDistance(50);
locator = LocatorFactory.getInstance();
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/requester/BaseLocationUpdateRequester.java
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // }
import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao; import android.app.PendingIntent; import android.content.Context; import android.location.LocationManager;
/** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.requester; public abstract class BaseLocationUpdateRequester implements LocationUpdateRequester { protected LocationManager locationManager; protected BaseLocationUpdateRequester(LocationManager locationManager) { this.locationManager = locationManager; } @Override public void requestPassiveLocationUpdates(Context context, PendingIntent pendingIntent) {
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // } // Path: core/src/main/java/com/novoda/location/provider/requester/BaseLocationUpdateRequester.java import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao; import android.app.PendingIntent; import android.content.Context; import android.location.LocationManager; /** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.requester; public abstract class BaseLocationUpdateRequester implements LocationUpdateRequester { protected LocationManager locationManager; protected BaseLocationUpdateRequester(LocationManager locationManager) { this.locationManager = locationManager; } @Override public void requestPassiveLocationUpdates(Context context, PendingIntent pendingIntent) {
SettingsDao settingsDao = new LocationProviderFactory().getSettingsDao();
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/requester/BaseLocationUpdateRequester.java
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // }
import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao; import android.app.PendingIntent; import android.content.Context; import android.location.LocationManager;
/** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.requester; public abstract class BaseLocationUpdateRequester implements LocationUpdateRequester { protected LocationManager locationManager; protected BaseLocationUpdateRequester(LocationManager locationManager) { this.locationManager = locationManager; } @Override public void requestPassiveLocationUpdates(Context context, PendingIntent pendingIntent) {
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // } // Path: core/src/main/java/com/novoda/location/provider/requester/BaseLocationUpdateRequester.java import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao; import android.app.PendingIntent; import android.content.Context; import android.location.LocationManager; /** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.requester; public abstract class BaseLocationUpdateRequester implements LocationUpdateRequester { protected LocationManager locationManager; protected BaseLocationUpdateRequester(LocationManager locationManager) { this.locationManager = locationManager; } @Override public void requestPassiveLocationUpdates(Context context, PendingIntent pendingIntent) {
SettingsDao settingsDao = new LocationProviderFactory().getSettingsDao();
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/requester/BaseLocationUpdateRequester.java
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // }
import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao; import android.app.PendingIntent; import android.content.Context; import android.location.LocationManager;
/** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.requester; public abstract class BaseLocationUpdateRequester implements LocationUpdateRequester { protected LocationManager locationManager; protected BaseLocationUpdateRequester(LocationManager locationManager) { this.locationManager = locationManager; } @Override public void requestPassiveLocationUpdates(Context context, PendingIntent pendingIntent) { SettingsDao settingsDao = new LocationProviderFactory().getSettingsDao(); long passiveLocationTime = settingsDao.getPassiveLocationInterval(context); int passiveLocationDistance = settingsDao.getPassiveLocationDistance(context); requestPassiveLocationUpdates(passiveLocationTime, passiveLocationDistance, pendingIntent); } @Override
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // } // Path: core/src/main/java/com/novoda/location/provider/requester/BaseLocationUpdateRequester.java import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao; import android.app.PendingIntent; import android.content.Context; import android.location.LocationManager; /** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.requester; public abstract class BaseLocationUpdateRequester implements LocationUpdateRequester { protected LocationManager locationManager; protected BaseLocationUpdateRequester(LocationManager locationManager) { this.locationManager = locationManager; } @Override public void requestPassiveLocationUpdates(Context context, PendingIntent pendingIntent) { SettingsDao settingsDao = new LocationProviderFactory().getSettingsDao(); long passiveLocationTime = settingsDao.getPassiveLocationInterval(context); int passiveLocationDistance = settingsDao.getPassiveLocationDistance(context); requestPassiveLocationUpdates(passiveLocationTime, passiveLocationDistance, pendingIntent); } @Override
public void requestPassiveLocationUpdates(LocatorSettings settings, PendingIntent pendingIntent) {
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/store/SettingsDao.java
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // }
import com.novoda.location.LocatorSettings; import android.content.Context;
/** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.store; public interface SettingsDao { long getPassiveLocationInterval(Context context); int getPassiveLocationDistance(Context context);
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java import com.novoda.location.LocatorSettings; import android.content.Context; /** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.store; public interface SettingsDao { long getPassiveLocationInterval(Context context); int getPassiveLocationDistance(Context context);
void persistSettingsToPreferences(Context context, LocatorSettings settings);
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/task/LastKnownLocationTask.java
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LastLocationFinder.java // public interface LastLocationFinder { // // public Location getLastBestLocation(int minDistance, long minTime); // // public void setChangedLocationListener(LocationListener l); // // public void cancel(); // // }
import android.location.Location; import android.os.AsyncTask; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LastLocationFinder;
/** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.task; public class LastKnownLocationTask extends AsyncTask<Void, Void, Location> { private LastLocationFinder lastLocationFinder; private int locationUpdateDistanceDiff; private long locationUpdateInterval;
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LastLocationFinder.java // public interface LastLocationFinder { // // public Location getLastBestLocation(int minDistance, long minTime); // // public void setChangedLocationListener(LocationListener l); // // public void cancel(); // // } // Path: core/src/main/java/com/novoda/location/provider/task/LastKnownLocationTask.java import android.location.Location; import android.os.AsyncTask; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LastLocationFinder; /** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.task; public class LastKnownLocationTask extends AsyncTask<Void, Void, Location> { private LastLocationFinder lastLocationFinder; private int locationUpdateDistanceDiff; private long locationUpdateInterval;
public LastKnownLocationTask(LastLocationFinder lastLocationFinder, LocatorSettings settings) {
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/task/LastKnownLocationTask.java
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LastLocationFinder.java // public interface LastLocationFinder { // // public Location getLastBestLocation(int minDistance, long minTime); // // public void setChangedLocationListener(LocationListener l); // // public void cancel(); // // }
import android.location.Location; import android.os.AsyncTask; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LastLocationFinder;
/** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.task; public class LastKnownLocationTask extends AsyncTask<Void, Void, Location> { private LastLocationFinder lastLocationFinder; private int locationUpdateDistanceDiff; private long locationUpdateInterval; public LastKnownLocationTask(LastLocationFinder lastLocationFinder, LocatorSettings settings) { this.lastLocationFinder = lastLocationFinder; this.locationUpdateDistanceDiff = settings.getUpdatesDistance(); this.locationUpdateInterval = settings.getUpdatesInterval(); } @Override protected Location doInBackground(Void... params) { long minimumTime = System.currentTimeMillis() - locationUpdateInterval; return lastLocationFinder.getLastBestLocation(locationUpdateDistanceDiff, minimumTime); } @Override protected void onPostExecute(Location lastKnownLocation) { if (lastKnownLocation == null) { return; }
// Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LastLocationFinder.java // public interface LastLocationFinder { // // public Location getLastBestLocation(int minDistance, long minTime); // // public void setChangedLocationListener(LocationListener l); // // public void cancel(); // // } // Path: core/src/main/java/com/novoda/location/provider/task/LastKnownLocationTask.java import android.location.Location; import android.os.AsyncTask; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; import com.novoda.location.provider.LastLocationFinder; /** * Copyright 2011 Novoda Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider.task; public class LastKnownLocationTask extends AsyncTask<Void, Void, Location> { private LastLocationFinder lastLocationFinder; private int locationUpdateDistanceDiff; private long locationUpdateInterval; public LastKnownLocationTask(LastLocationFinder lastLocationFinder, LocatorSettings settings) { this.lastLocationFinder = lastLocationFinder; this.locationUpdateDistanceDiff = settings.getUpdatesDistance(); this.locationUpdateInterval = settings.getUpdatesInterval(); } @Override protected Location doInBackground(Void... params) { long minimumTime = System.currentTimeMillis() - locationUpdateInterval; return lastLocationFinder.getLastBestLocation(locationUpdateDistanceDiff, minimumTime); } @Override protected void onPostExecute(Location lastKnownLocation) { if (lastKnownLocation == null) { return; }
LocatorFactory.setLocation(lastKnownLocation);
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/requester/LegacyLocationUpdateRequester.java
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.location.Criteria; import android.location.LocationManager; import com.novoda.location.LocatorSettings;
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.provider.requester; /** * Provides support for initiating active and passive location updates for all * Android platforms from Android 1.6. * * Uses broadcast Intents to notify the app of location changes. */ public class LegacyLocationUpdateRequester extends BaseLocationUpdateRequester { protected final AlarmManager alarmManager;
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // Path: core/src/main/java/com/novoda/location/provider/requester/LegacyLocationUpdateRequester.java import android.app.AlarmManager; import android.app.PendingIntent; import android.location.Criteria; import android.location.LocationManager; import com.novoda.location.LocatorSettings; /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.provider.requester; /** * Provides support for initiating active and passive location updates for all * Android platforms from Android 1.6. * * Uses broadcast Intents to notify the app of location changes. */ public class LegacyLocationUpdateRequester extends BaseLocationUpdateRequester { protected final AlarmManager alarmManager;
private final LocatorSettings settings;
jgilfelt/Novocation
core/src/main/java/com/novoda/location/receiver/RestorePassiveListenerBoot.java
// Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // }
import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.LocationManager; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao;
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class RestorePassiveListenerBoot extends BroadcastReceiver { @Override public void onReceive(Context c, Intent intent) {
// Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // } // Path: core/src/main/java/com/novoda/location/receiver/RestorePassiveListenerBoot.java import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.LocationManager; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao; /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class RestorePassiveListenerBoot extends BroadcastReceiver { @Override public void onReceive(Context c, Intent intent) {
SettingsDao settingsDao = new LocationProviderFactory().getSettingsDao();
jgilfelt/Novocation
core/src/main/java/com/novoda/location/receiver/RestorePassiveListenerBoot.java
// Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // }
import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.LocationManager; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao;
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class RestorePassiveListenerBoot extends BroadcastReceiver { @Override public void onReceive(Context c, Intent intent) {
// Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // } // Path: core/src/main/java/com/novoda/location/receiver/RestorePassiveListenerBoot.java import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.LocationManager; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao; /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class RestorePassiveListenerBoot extends BroadcastReceiver { @Override public void onReceive(Context c, Intent intent) {
SettingsDao settingsDao = new LocationProviderFactory().getSettingsDao();
jgilfelt/Novocation
core/src/main/java/com/novoda/location/receiver/RestorePassiveListenerBoot.java
// Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // }
import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.LocationManager; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao;
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class RestorePassiveListenerBoot extends BroadcastReceiver { @Override public void onReceive(Context c, Intent intent) { SettingsDao settingsDao = new LocationProviderFactory().getSettingsDao(); if (!settingsDao.isRunOnce(c)) { return; } if (!settingsDao.isPassiveLocationChanges(c)) { return; } requestPassiveLocationUpdates(c); } private void requestPassiveLocationUpdates(Context context) { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); LocationProviderFactory factory = new LocationProviderFactory();
// Path: core/src/main/java/com/novoda/location/provider/LocationProviderFactory.java // public class LocationProviderFactory { // // public LastLocationFinder getLastLocationFinder(LocationManager locationManager, Context context) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLastLocationFinder(locationManager, context); // } // return new LegacyLastLocationFinder(locationManager, context); // } // // public LocationUpdateRequester getLocationUpdateRequester(LocationManager locationManager) { // if(ApiLevelDetector.supportsGingerbread()) { // return new GingerbreadLocationUpdateRequester(locationManager); // } // return new FroyoLocationUpdateRequester(locationManager); // } // // public SettingsDao getSettingsDao() { // return new SharedPreferenceSettingsDao(); // } // // } // // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java // public interface LocationUpdateRequester { // // void requestActiveLocationUpdates(long minTime, long minDistance, // Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; // // void requestPassiveLocationUpdates(Context context, // PendingIntent pendingIntent); // // void requestPassiveLocationUpdates(LocatorSettings settings, // PendingIntent pendingIntent); // // void removeLocationUpdates(PendingIntent pendingIntent); // } // // Path: core/src/main/java/com/novoda/location/provider/store/SettingsDao.java // public interface SettingsDao { // // long getPassiveLocationInterval(Context context); // // int getPassiveLocationDistance(Context context); // // void persistSettingsToPreferences(Context context, LocatorSettings settings); // // boolean isRunOnce(Context context); // // boolean isPassiveLocationChanges(Context context); // // } // Path: core/src/main/java/com/novoda/location/receiver/RestorePassiveListenerBoot.java import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.location.LocationManager; import com.novoda.location.provider.LocationProviderFactory; import com.novoda.location.provider.LocationUpdateRequester; import com.novoda.location.provider.store.SettingsDao; /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Code modified by Novoda Ltd, 2011. */ package com.novoda.location.receiver; public class RestorePassiveListenerBoot extends BroadcastReceiver { @Override public void onReceive(Context c, Intent intent) { SettingsDao settingsDao = new LocationProviderFactory().getSettingsDao(); if (!settingsDao.isRunOnce(c)) { return; } if (!settingsDao.isPassiveLocationChanges(c)) { return; } requestPassiveLocationUpdates(c); } private void requestPassiveLocationUpdates(Context context) { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); LocationProviderFactory factory = new LocationProviderFactory();
LocationUpdateRequester lur = factory.getLocationUpdateRequester(lm);
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/exception/NoProviderAvailable.java // public class NoProviderAvailable extends Exception { // // private static final long serialVersionUID = 1L; // // }
import com.novoda.location.LocatorSettings; import com.novoda.location.exception.NoProviderAvailable; import android.app.PendingIntent; import android.content.Context; import android.location.Criteria;
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider; public interface LocationUpdateRequester { void requestActiveLocationUpdates(long minTime, long minDistance,
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/exception/NoProviderAvailable.java // public class NoProviderAvailable extends Exception { // // private static final long serialVersionUID = 1L; // // } // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java import com.novoda.location.LocatorSettings; import com.novoda.location.exception.NoProviderAvailable; import android.app.PendingIntent; import android.content.Context; import android.location.Criteria; /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider; public interface LocationUpdateRequester { void requestActiveLocationUpdates(long minTime, long minDistance,
Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable;
jgilfelt/Novocation
core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/exception/NoProviderAvailable.java // public class NoProviderAvailable extends Exception { // // private static final long serialVersionUID = 1L; // // }
import com.novoda.location.LocatorSettings; import com.novoda.location.exception.NoProviderAvailable; import android.app.PendingIntent; import android.content.Context; import android.location.Criteria;
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider; public interface LocationUpdateRequester { void requestActiveLocationUpdates(long minTime, long minDistance, Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; void requestPassiveLocationUpdates(Context context, PendingIntent pendingIntent);
// Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // // Path: core/src/main/java/com/novoda/location/exception/NoProviderAvailable.java // public class NoProviderAvailable extends Exception { // // private static final long serialVersionUID = 1L; // // } // Path: core/src/main/java/com/novoda/location/provider/LocationUpdateRequester.java import com.novoda.location.LocatorSettings; import com.novoda.location.exception.NoProviderAvailable; import android.app.PendingIntent; import android.content.Context; import android.location.Criteria; /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.novoda.location.provider; public interface LocationUpdateRequester { void requestActiveLocationUpdates(long minTime, long minDistance, Criteria criteria, PendingIntent pendingIntent) throws NoProviderAvailable; void requestPassiveLocationUpdates(Context context, PendingIntent pendingIntent);
void requestPassiveLocationUpdates(LocatorSettings settings,
jgilfelt/Novocation
simple/src/com/novoda/location/demo/simple/ExampleActivity.java
// Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // // Path: core/src/main/java/com/novoda/location/exception/NoProviderAvailable.java // public class NoProviderAvailable extends Exception { // // private static final long serialVersionUID = 1L; // // }
import java.util.Date; import com.novoda.location.Locator; import com.novoda.location.exception.NoProviderAvailable; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.widget.TextView; import android.widget.Toast;
package com.novoda.location.demo.simple; /* * This activity registers a broadcast receiver so that it can do * something on each location update. You could also simply call * locator.getLocation() some time after the onCreate method. */ public class ExampleActivity extends Activity { private Locator locator; TextView time; TextView accuracy; TextView provider; TextView latitude; TextView longitude; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); time = (TextView) findViewById(R.id.val_time); accuracy = (TextView) findViewById(R.id.val_acc); provider = (TextView) findViewById(R.id.val_prov); latitude = (TextView) findViewById(R.id.val_lat); longitude = (TextView) findViewById(R.id.val_lon); // Get the reference to the locator object. ExampleApplication app = (ExampleApplication) getApplication(); locator = app.getLocator(); } @Override public void onResume() { super.onResume(); // Register broadcast receiver and start location updates. IntentFilter f = new IntentFilter(); f.addAction(ExampleApplication.LOCATION_UPDATE_ACTION); registerReceiver(freshLocationReceiver, f); try { locator.startLocationUpdates();
// Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // // Path: core/src/main/java/com/novoda/location/exception/NoProviderAvailable.java // public class NoProviderAvailable extends Exception { // // private static final long serialVersionUID = 1L; // // } // Path: simple/src/com/novoda/location/demo/simple/ExampleActivity.java import java.util.Date; import com.novoda.location.Locator; import com.novoda.location.exception.NoProviderAvailable; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.widget.TextView; import android.widget.Toast; package com.novoda.location.demo.simple; /* * This activity registers a broadcast receiver so that it can do * something on each location update. You could also simply call * locator.getLocation() some time after the onCreate method. */ public class ExampleActivity extends Activity { private Locator locator; TextView time; TextView accuracy; TextView provider; TextView latitude; TextView longitude; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); time = (TextView) findViewById(R.id.val_time); accuracy = (TextView) findViewById(R.id.val_acc); provider = (TextView) findViewById(R.id.val_prov); latitude = (TextView) findViewById(R.id.val_lat); longitude = (TextView) findViewById(R.id.val_lon); // Get the reference to the locator object. ExampleApplication app = (ExampleApplication) getApplication(); locator = app.getLocator(); } @Override public void onResume() { super.onResume(); // Register broadcast receiver and start location updates. IntentFilter f = new IntentFilter(); f.addAction(ExampleApplication.LOCATION_UPDATE_ACTION); registerReceiver(freshLocationReceiver, f); try { locator.startLocationUpdates();
} catch (NoProviderAvailable npa) {
jgilfelt/Novocation
demo/src/com/novoda/locationdemo/activity/location/AccuracyCircleOverlay.java
// Path: core/src/main/java/com/novoda/location/util/Log.java // public class Log { // // public static final void v(String msg) { // android.util.Log.v("Novocation", msg); // } // // }
import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Point; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.Projection; import com.novoda.location.util.Log;
package com.novoda.locationdemo.activity.location; public class AccuracyCircleOverlay extends Overlay { private float accuracy; private GeoPoint geoPoint; public AccuracyCircleOverlay(GeoPoint geoPoint, float accuracy) { this.accuracy = accuracy; this.geoPoint = geoPoint; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { Projection projection = mapView.getProjection(); if (shadow && projection == null) {
// Path: core/src/main/java/com/novoda/location/util/Log.java // public class Log { // // public static final void v(String msg) { // android.util.Log.v("Novocation", msg); // } // // } // Path: demo/src/com/novoda/locationdemo/activity/location/AccuracyCircleOverlay.java import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Point; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.Projection; import com.novoda.location.util.Log; package com.novoda.locationdemo.activity.location; public class AccuracyCircleOverlay extends Overlay { private float accuracy; private GeoPoint geoPoint; public AccuracyCircleOverlay(GeoPoint geoPoint, float accuracy) { this.accuracy = accuracy; this.geoPoint = geoPoint; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { Projection projection = mapView.getProjection(); if (shadow && projection == null) {
Log.v("drawing not done because shadow and projection are null");
jgilfelt/Novocation
simple/src/com/novoda/location/demo/simple/ExampleApplication.java
// Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // }
import android.app.Application; import com.novoda.location.Locator; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings;
package com.novoda.location.demo.simple; public class ExampleApplication extends Application { public static final String PACKAGE_NAME = "com.novoda.location.demo.simple"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.location.demo.simple.action.ACTION_FRESH_LOCATION";
// Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // Path: simple/src/com/novoda/location/demo/simple/ExampleApplication.java import android.app.Application; import com.novoda.location.Locator; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; package com.novoda.location.demo.simple; public class ExampleApplication extends Application { public static final String PACKAGE_NAME = "com.novoda.location.demo.simple"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.location.demo.simple.action.ACTION_FRESH_LOCATION";
private static Locator locator;
jgilfelt/Novocation
simple/src/com/novoda/location/demo/simple/ExampleApplication.java
// Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // }
import android.app.Application; import com.novoda.location.Locator; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings;
package com.novoda.location.demo.simple; public class ExampleApplication extends Application { public static final String PACKAGE_NAME = "com.novoda.location.demo.simple"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.location.demo.simple.action.ACTION_FRESH_LOCATION"; private static Locator locator; @Override public void onCreate() { super.onCreate(); // Connect the location finder with relevant settings.
// Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // Path: simple/src/com/novoda/location/demo/simple/ExampleApplication.java import android.app.Application; import com.novoda.location.Locator; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; package com.novoda.location.demo.simple; public class ExampleApplication extends Application { public static final String PACKAGE_NAME = "com.novoda.location.demo.simple"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.location.demo.simple.action.ACTION_FRESH_LOCATION"; private static Locator locator; @Override public void onCreate() { super.onCreate(); // Connect the location finder with relevant settings.
LocatorSettings settings = new LocatorSettings(PACKAGE_NAME, LOCATION_UPDATE_ACTION);
jgilfelt/Novocation
simple/src/com/novoda/location/demo/simple/ExampleApplication.java
// Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // }
import android.app.Application; import com.novoda.location.Locator; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings;
package com.novoda.location.demo.simple; public class ExampleApplication extends Application { public static final String PACKAGE_NAME = "com.novoda.location.demo.simple"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.location.demo.simple.action.ACTION_FRESH_LOCATION"; private static Locator locator; @Override public void onCreate() { super.onCreate(); // Connect the location finder with relevant settings. LocatorSettings settings = new LocatorSettings(PACKAGE_NAME, LOCATION_UPDATE_ACTION); settings.setUpdatesInterval(3 * 60 * 1000); settings.setUpdatesDistance(50);
// Path: core/src/main/java/com/novoda/location/Locator.java // public interface Locator { // // void prepare(Context c, LocatorSettings settings); // // Location getLocation(); // // void setLocation(Location location); // // LocatorSettings getSettings(); // // void startLocationUpdates() throws NoProviderAvailable; // // void stopLocationUpdates(); // // boolean isNetworkProviderEnabled(); // // boolean isGpsProviderEnabled(); // // } // // Path: core/src/main/java/com/novoda/location/LocatorFactory.java // public class LocatorFactory { // // private static Locator instance; // // public static Locator getInstance() { // if(instance == null) { // instance = new DefaultLocator(); // } // return instance; // } // // public static void setLocation(Location location) { // getInstance().setLocation(location); // } // // public static Location getLocation() { // return getInstance().getLocation(); // } // // public static void reset() { // instance = null; // } // // } // // Path: core/src/main/java/com/novoda/location/LocatorSettings.java // public class LocatorSettings { // // private final String packageName; // private final String updateAction; // // private boolean useGps = Constants.USE_GPS; // private boolean updateOnLocationChange = Constants.REFRESH_DATA_ON_LOCATION_CHANGED; // private long updatesInterval = Constants.UPDATES_MAX_TIME; // private int updatesDistance = Constants.UPDATES_MAX_DISTANCE; // private long passiveUpdatesInterval = Constants.DEFAULT_INTERVAL_PASSIVE; // private int passiveUpdatesDistance = Constants.DEFAULT_DISTANCE_PASSIVE; // private boolean enablePassiveUpdates = Constants.ENABLE_PASSIVE_UPDATES; // // public LocatorSettings(String packageName, String updateAction) { // this.packageName = packageName; // this.updateAction = updateAction; // } // // public String getPackageName() { // return packageName; // } // // public String getUpdateAction() { // return updateAction; // } // // public boolean shouldUseGps() { // return useGps; // } // // public void setUseGps(boolean useGps) { // this.useGps = useGps; // } // // public boolean shouldUpdateLocation() { // return updateOnLocationChange; // } // // public void setUpdateOnLocationChange(boolean updateOnLocationChange) { // this.updateOnLocationChange = updateOnLocationChange; // } // // public boolean shouldEnablePassiveUpdates() { // return enablePassiveUpdates; // } // // public void setEnablePassiveUpdates(boolean enablePassiveUpdates) { // this.enablePassiveUpdates = enablePassiveUpdates; // } // // public long getUpdatesInterval() { // return updatesInterval; // } // // public void setUpdatesInterval(long updatesInterval) { // this.updatesInterval = updatesInterval; // } // // public int getUpdatesDistance() { // return updatesDistance; // } // // public void setUpdatesDistance(int updatesDistance) { // this.updatesDistance = updatesDistance; // } // // public long getPassiveUpdatesInterval() { // return passiveUpdatesInterval; // } // // public void setPassiveUpdatesInterval(long passiveUpdatesInterval) { // this.passiveUpdatesInterval = passiveUpdatesInterval; // } // // public int getPassiveUpdatesDistance() { // return passiveUpdatesDistance; // } // // public void setPassiveUpdatesDistance(int passiveUpdatesDistance) { // this.passiveUpdatesDistance = passiveUpdatesDistance; // } // // } // Path: simple/src/com/novoda/location/demo/simple/ExampleApplication.java import android.app.Application; import com.novoda.location.Locator; import com.novoda.location.LocatorFactory; import com.novoda.location.LocatorSettings; package com.novoda.location.demo.simple; public class ExampleApplication extends Application { public static final String PACKAGE_NAME = "com.novoda.location.demo.simple"; public static final String LOCATION_UPDATE_ACTION = "com.novoda.location.demo.simple.action.ACTION_FRESH_LOCATION"; private static Locator locator; @Override public void onCreate() { super.onCreate(); // Connect the location finder with relevant settings. LocatorSettings settings = new LocatorSettings(PACKAGE_NAME, LOCATION_UPDATE_ACTION); settings.setUpdatesInterval(3 * 60 * 1000); settings.setUpdatesDistance(50);
locator = LocatorFactory.getInstance();
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudLogic.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import com.vaadin.flow.component.UI; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.io.Serializable;
package com.github.mcollovati.vertxvaadin.flowdemo.crud; /** * This class provides an interface for the logical operations between the CRUD * view, its parts like the product editor form and the data source, including * fetching and saving products. * * Having this separate from the view makes it easier to test various parts of * the system separately, and to e.g. provide alternative views for the same * data. */ public class SampleCrudLogic implements Serializable { private SampleCrudView view; public SampleCrudLogic(SampleCrudView simpleCrudView) { view = simpleCrudView; } public void init() { editProduct(null); // Hide and disable if not admin
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudLogic.java import com.vaadin.flow.component.UI; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.io.Serializable; package com.github.mcollovati.vertxvaadin.flowdemo.crud; /** * This class provides an interface for the logical operations between the CRUD * view, its parts like the product editor form and the data source, including * fetching and saving products. * * Having this separate from the view makes it easier to test various parts of * the system separately, and to e.g. provide alternative views for the same * data. */ public class SampleCrudLogic implements Serializable { private SampleCrudView view; public SampleCrudLogic(SampleCrudView simpleCrudView) { view = simpleCrudView; } public void init() { editProduct(null); // Hide and disable if not admin
if (!AccessControlFactory.getInstance().createAccessControl()
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudLogic.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import com.vaadin.flow.component.UI; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.io.Serializable;
package com.github.mcollovati.vertxvaadin.flowdemo.crud; /** * This class provides an interface for the logical operations between the CRUD * view, its parts like the product editor form and the data source, including * fetching and saving products. * * Having this separate from the view makes it easier to test various parts of * the system separately, and to e.g. provide alternative views for the same * data. */ public class SampleCrudLogic implements Serializable { private SampleCrudView view; public SampleCrudLogic(SampleCrudView simpleCrudView) { view = simpleCrudView; } public void init() { editProduct(null); // Hide and disable if not admin if (!AccessControlFactory.getInstance().createAccessControl()
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudLogic.java import com.vaadin.flow.component.UI; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.io.Serializable; package com.github.mcollovati.vertxvaadin.flowdemo.crud; /** * This class provides an interface for the logical operations between the CRUD * view, its parts like the product editor form and the data source, including * fetching and saving products. * * Having this separate from the view makes it easier to test various parts of * the system separately, and to e.g. provide alternative views for the same * data. */ public class SampleCrudLogic implements Serializable { private SampleCrudView view; public SampleCrudLogic(SampleCrudView simpleCrudView) { view = simpleCrudView; } public void init() { editProduct(null); // Hide and disable if not admin if (!AccessControlFactory.getInstance().createAccessControl()
.isUserInRole(AccessControl.ADMIN_ROLE_NAME)) {
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudLogic.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import com.vaadin.flow.component.UI; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.io.Serializable;
} public void cancelProduct() { setFragmentParameter(""); view.clearSelection(); } /** * Update the fragment without causing navigator to change view */ private void setFragmentParameter(String productId) { String fragmentParameter; if (productId == null || productId.isEmpty()) { fragmentParameter = ""; } else { fragmentParameter = productId; } UI.getCurrent().navigate(SampleCrudView.class, fragmentParameter); } public void enter(String productId) { if (productId != null && !productId.isEmpty()) { if (productId.equals("new")) { newProduct(); } else { // Ensure this is selected even if coming directly here from // login try { int pid = Integer.parseInt(productId);
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudLogic.java import com.vaadin.flow.component.UI; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.io.Serializable; } public void cancelProduct() { setFragmentParameter(""); view.clearSelection(); } /** * Update the fragment without causing navigator to change view */ private void setFragmentParameter(String productId) { String fragmentParameter; if (productId == null || productId.isEmpty()) { fragmentParameter = ""; } else { fragmentParameter = productId; } UI.getCurrent().navigate(SampleCrudView.class, fragmentParameter); } public void enter(String productId) { if (productId != null && !productId.isEmpty()) { if (productId.equals("new")) { newProduct(); } else { // Ensure this is selected even if coming directly here from // login try { int pid = Integer.parseInt(productId);
Product product = findProduct(pid);
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudLogic.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import com.vaadin.flow.component.UI; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.io.Serializable;
String fragmentParameter; if (productId == null || productId.isEmpty()) { fragmentParameter = ""; } else { fragmentParameter = productId; } UI.getCurrent().navigate(SampleCrudView.class, fragmentParameter); } public void enter(String productId) { if (productId != null && !productId.isEmpty()) { if (productId.equals("new")) { newProduct(); } else { // Ensure this is selected even if coming directly here from // login try { int pid = Integer.parseInt(productId); Product product = findProduct(pid); view.selectRow(product); } catch (NumberFormatException e) { } } } else { view.showForm(false); } } private Product findProduct(int productId) {
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudLogic.java import com.vaadin.flow.component.UI; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.io.Serializable; String fragmentParameter; if (productId == null || productId.isEmpty()) { fragmentParameter = ""; } else { fragmentParameter = productId; } UI.getCurrent().navigate(SampleCrudView.class, fragmentParameter); } public void enter(String productId) { if (productId != null && !productId.isEmpty()) { if (productId.equals("new")) { newProduct(); } else { // Ensure this is selected even if coming directly here from // login try { int pid = Integer.parseInt(productId); Product product = findProduct(pid); view.selectRow(product); } catch (NumberFormatException e) { } } } else { view.showForm(false); } } private Product findProduct(int productId) {
return DataService.get().getProductById(productId);
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-backend/src/test/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataServiceTest.java
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // }
import org.junit.Before; import org.junit.Test; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import com.github.mcollovati.vertxvaadin.flowdemo.backend.mock.MockDataService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
package com.github.mcollovati.vertxvaadin.flowdemo.backend; /** * Simple unit test for the back-end data service. */ public class DataServiceTest { private DataService service; @Before public void setUp() throws Exception {
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // } // Path: flow-bookstore/bookstore-backend/src/test/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataServiceTest.java import org.junit.Before; import org.junit.Test; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import com.github.mcollovati.vertxvaadin.flowdemo.backend.mock.MockDataService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; package com.github.mcollovati.vertxvaadin.flowdemo.backend; /** * Simple unit test for the back-end data service. */ public class DataServiceTest { private DataService service; @Before public void setUp() throws Exception {
service = MockDataService.getInstance();
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-backend/src/test/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataServiceTest.java
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // }
import org.junit.Before; import org.junit.Test; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import com.github.mcollovati.vertxvaadin.flowdemo.backend.mock.MockDataService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
package com.github.mcollovati.vertxvaadin.flowdemo.backend; /** * Simple unit test for the back-end data service. */ public class DataServiceTest { private DataService service; @Before public void setUp() throws Exception { service = MockDataService.getInstance(); } @Test public void testDataServiceCanFetchProducts() throws Exception { assertFalse(service.getAllProducts().isEmpty()); } @Test public void testDataServiceCanFetchCategories() throws Exception { assertFalse(service.getAllCategories().isEmpty()); } @Test public void testUpdateProduct_updatesTheProduct() throws Exception {
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // } // Path: flow-bookstore/bookstore-backend/src/test/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataServiceTest.java import org.junit.Before; import org.junit.Test; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import com.github.mcollovati.vertxvaadin.flowdemo.backend.mock.MockDataService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; package com.github.mcollovati.vertxvaadin.flowdemo.backend; /** * Simple unit test for the back-end data service. */ public class DataServiceTest { private DataService service; @Before public void setUp() throws Exception { service = MockDataService.getInstance(); } @Test public void testDataServiceCanFetchProducts() throws Exception { assertFalse(service.getAllProducts().isEmpty()); } @Test public void testDataServiceCanFetchCategories() throws Exception { assertFalse(service.getAllCategories().isEmpty()); } @Test public void testUpdateProduct_updatesTheProduct() throws Exception {
Product p = service.getAllProducts().iterator().next();
mcollovati/vaadin-vertx-samples
example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // }
import java.io.Serializable; import java.util.Collection; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.github.mcollovati.vaadin.exampleapp.samples.backend.mock.MockDataService;
package com.github.mcollovati.vaadin.exampleapp.samples.backend; /** * Back-end service interface for retrieving and updating product data. */ public abstract class DataService implements Serializable { public abstract Collection<Product> getAllProducts();
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // } // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java import java.io.Serializable; import java.util.Collection; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.github.mcollovati.vaadin.exampleapp.samples.backend.mock.MockDataService; package com.github.mcollovati.vaadin.exampleapp.samples.backend; /** * Back-end service interface for retrieving and updating product data. */ public abstract class DataService implements Serializable { public abstract Collection<Product> getAllProducts();
public abstract Collection<Category> getAllCategories();
mcollovati/vaadin-vertx-samples
example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // }
import java.io.Serializable; import java.util.Collection; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.github.mcollovati.vaadin.exampleapp.samples.backend.mock.MockDataService;
package com.github.mcollovati.vaadin.exampleapp.samples.backend; /** * Back-end service interface for retrieving and updating product data. */ public abstract class DataService implements Serializable { public abstract Collection<Product> getAllProducts(); public abstract Collection<Category> getAllCategories(); public abstract void updateProduct(Product p); public abstract void deleteProduct(int productId); public abstract Product getProductById(int productId); public static DataService get() {
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // } // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java import java.io.Serializable; import java.util.Collection; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.github.mcollovati.vaadin.exampleapp.samples.backend.mock.MockDataService; package com.github.mcollovati.vaadin.exampleapp.samples.backend; /** * Back-end service interface for retrieving and updating product data. */ public abstract class DataService implements Serializable { public abstract Collection<Product> getAllProducts(); public abstract Collection<Category> getAllCategories(); public abstract void updateProduct(Product p); public abstract void deleteProduct(int productId); public abstract Product getProductById(int productId); public static DataService get() {
return MockDataService.getInstance();
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductFormDesign.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // }
import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.vaadin.annotations.AutoGenerated; import com.vaadin.annotations.DesignRoot; import com.vaadin.ui.Button; import com.vaadin.ui.CheckBoxGroup; import com.vaadin.ui.ComboBox; import com.vaadin.ui.CssLayout; import com.vaadin.ui.TextField; import com.vaadin.ui.declarative.Design;
package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * !! DO NOT EDIT THIS FILE !! * * This class is generated by Vaadin Designer and will be overwritten. * * Please make a subclass with logic and additional interfaces as needed, * e.g class LoginView extends LoginDesign implements View { … } */ @DesignRoot @AutoGenerated @SuppressWarnings("serial") public class ProductFormDesign extends CssLayout { protected TextField productName; protected TextField price; protected TextField stockCount;
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductFormDesign.java import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.vaadin.annotations.AutoGenerated; import com.vaadin.annotations.DesignRoot; import com.vaadin.ui.Button; import com.vaadin.ui.CheckBoxGroup; import com.vaadin.ui.ComboBox; import com.vaadin.ui.CssLayout; import com.vaadin.ui.TextField; import com.vaadin.ui.declarative.Design; package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * !! DO NOT EDIT THIS FILE !! * * This class is generated by Vaadin Designer and will be overwritten. * * Please make a subclass with logic and additional interfaces as needed, * e.g class LoginView extends LoginDesign implements View { … } */ @DesignRoot @AutoGenerated @SuppressWarnings("serial") public class ProductFormDesign extends CssLayout { protected TextField productName; protected TextField price; protected TextField stockCount;
protected ComboBox<Availability> availability;
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductFormDesign.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // }
import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.vaadin.annotations.AutoGenerated; import com.vaadin.annotations.DesignRoot; import com.vaadin.ui.Button; import com.vaadin.ui.CheckBoxGroup; import com.vaadin.ui.ComboBox; import com.vaadin.ui.CssLayout; import com.vaadin.ui.TextField; import com.vaadin.ui.declarative.Design;
package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * !! DO NOT EDIT THIS FILE !! * * This class is generated by Vaadin Designer and will be overwritten. * * Please make a subclass with logic and additional interfaces as needed, * e.g class LoginView extends LoginDesign implements View { … } */ @DesignRoot @AutoGenerated @SuppressWarnings("serial") public class ProductFormDesign extends CssLayout { protected TextField productName; protected TextField price; protected TextField stockCount; protected ComboBox<Availability> availability;
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductFormDesign.java import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.vaadin.annotations.AutoGenerated; import com.vaadin.annotations.DesignRoot; import com.vaadin.ui.Button; import com.vaadin.ui.CheckBoxGroup; import com.vaadin.ui.ComboBox; import com.vaadin.ui.CssLayout; import com.vaadin.ui.TextField; import com.vaadin.ui.declarative.Design; package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * !! DO NOT EDIT THIS FILE !! * * This class is generated by Vaadin Designer and will be overwritten. * * Please make a subclass with logic and additional interfaces as needed, * e.g class LoginView extends LoginDesign implements View { … } */ @DesignRoot @AutoGenerated @SuppressWarnings("serial") public class ProductFormDesign extends CssLayout { protected TextField productName; protected TextField price; protected TextField stockCount; protected ComboBox<Availability> availability;
protected CheckBoxGroup<Category> category;
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductDataProvider.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.util.Locale; import java.util.Objects; import java.util.function.Supplier; import java.util.stream.Stream; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.provider.AbstractDataProvider; import com.vaadin.data.provider.Query;
package com.github.mcollovati.vaadin.exampleapp.samples.crud; public class ProductDataProvider extends AbstractDataProvider<Product, String> { /** Text filter that can be changed separately. */ private String filterText = ""; /** * Store given product to the backing data service. * * @param product * the updated or new product */ public void save(Product product) { boolean newProduct = product.getId() == -1;
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductDataProvider.java import java.util.Locale; import java.util.Objects; import java.util.function.Supplier; import java.util.stream.Stream; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.provider.AbstractDataProvider; import com.vaadin.data.provider.Query; package com.github.mcollovati.vaadin.exampleapp.samples.crud; public class ProductDataProvider extends AbstractDataProvider<Product, String> { /** Text filter that can be changed separately. */ private String filterText = ""; /** * Store given product to the backing data service. * * @param product * the updated or new product */ public void save(Product product) { boolean newProduct = product.getId() == -1;
DataService.get().updateProduct(product);
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/ProductGrid.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/SerializableUtils.java // public interface SerializableUtils<T> extends Comparator<T>, Serializable { // // static <T, U> Function<T, U> function(SerializableFunction<T, U> fn) { // return fn; // } // // static <T> ToIntFunction<T> toIntFunction(SerializableToIntFunction<T> fn) { // return fn; // } // // interface SerializableToIntFunction<R> extends ToIntFunction<R>, Serializable {} // // interface FileReceiver extends Receiver { // FileInfo getFileInfo(); // // default String getFileName() { // return Optional.ofNullable(getFileInfo()).map(FileInfo::getFileName).orElse(""); // } // // default InputStream getInputStream() { // FileInfo file = getFileInfo(); // if (file != null) { // try { // return new FileInputStream(file.file); // } catch (IOException e) { // Logger.getLogger(getClass().getName()).log(Level.WARNING, // "Failed to create InputStream for: '" + getFileName() // + "'", e); // } // } // return new ByteArrayInputStream(new byte[0]); // } // // class FileInfo implements Serializable { // private final File file; // private final String fileName; // private final String mimeType; // // public FileInfo(File file, String fileName, String mimeType) { // this.file = file; // this.fileName = fileName; // this.mimeType = mimeType; // } // // public String getFileName() { // return fileName; // } // // OutputStream getOutputBuffer() { // try { // return new FileOutputStream(file); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // } // } // } // // static FileReceiver newFileBuffer() { // return new SerializableFileBuffer(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import com.github.mcollovati.vertxvaadin.flowdemo.SerializableUtils; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.data.renderer.TemplateRenderer; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.text.DecimalFormat; import java.util.Comparator; import java.util.stream.Collectors;
package com.github.mcollovati.vertxvaadin.flowdemo.crud; /** * Grid of products, handling the visual presentation and filtering of a set of * items. This version uses an in-memory data source that is suitable for small * data sets. */ public class ProductGrid extends Grid<Product> { public ProductGrid() { setSizeFull(); addColumn(Product::getProductName) .setHeader("Product name") .setFlexGrow(20) .setSortable(true); // Format and add " €" to price final DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); decimalFormat.setMinimumFractionDigits(2); // To change the text alignment of the column, a template is used. final String priceTemplate = "<div style='text-align: right'>[[item.price]]</div>"; addColumn(TemplateRenderer.<Product>of(priceTemplate) .withProperty("price", product -> decimalFormat.format(product.getPrice()) + " €")) .setHeader("Price")
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/SerializableUtils.java // public interface SerializableUtils<T> extends Comparator<T>, Serializable { // // static <T, U> Function<T, U> function(SerializableFunction<T, U> fn) { // return fn; // } // // static <T> ToIntFunction<T> toIntFunction(SerializableToIntFunction<T> fn) { // return fn; // } // // interface SerializableToIntFunction<R> extends ToIntFunction<R>, Serializable {} // // interface FileReceiver extends Receiver { // FileInfo getFileInfo(); // // default String getFileName() { // return Optional.ofNullable(getFileInfo()).map(FileInfo::getFileName).orElse(""); // } // // default InputStream getInputStream() { // FileInfo file = getFileInfo(); // if (file != null) { // try { // return new FileInputStream(file.file); // } catch (IOException e) { // Logger.getLogger(getClass().getName()).log(Level.WARNING, // "Failed to create InputStream for: '" + getFileName() // + "'", e); // } // } // return new ByteArrayInputStream(new byte[0]); // } // // class FileInfo implements Serializable { // private final File file; // private final String fileName; // private final String mimeType; // // public FileInfo(File file, String fileName, String mimeType) { // this.file = file; // this.fileName = fileName; // this.mimeType = mimeType; // } // // public String getFileName() { // return fileName; // } // // OutputStream getOutputBuffer() { // try { // return new FileOutputStream(file); // } catch (FileNotFoundException e) { // throw new RuntimeException(e); // } // } // } // } // // static FileReceiver newFileBuffer() { // return new SerializableFileBuffer(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/ProductGrid.java import com.github.mcollovati.vertxvaadin.flowdemo.SerializableUtils; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.data.renderer.TemplateRenderer; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import java.text.DecimalFormat; import java.util.Comparator; import java.util.stream.Collectors; package com.github.mcollovati.vertxvaadin.flowdemo.crud; /** * Grid of products, handling the visual presentation and filtering of a set of * items. This version uses an in-memory data source that is suitable for small * data sets. */ public class ProductGrid extends Grid<Product> { public ProductGrid() { setSizeFull(); addColumn(Product::getProductName) .setHeader("Product name") .setFlexGrow(20) .setSortable(true); // Format and add " €" to price final DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); decimalFormat.setMinimumFractionDigits(2); // To change the text alignment of the column, a template is used. final String priceTemplate = "<div style='text-align: right'>[[item.price]]</div>"; addColumn(TemplateRenderer.<Product>of(priceTemplate) .withProperty("price", product -> decimalFormat.format(product.getPrice()) + " €")) .setHeader("Price")
.setComparator(Comparator.comparing(SerializableUtils.function(Product::getPrice)))
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/MainLayout.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/about/AboutView.java // @Route(value = "About", layout = MainLayout.class) // @PageTitle("About") // public class AboutView extends VerticalLayout { // // public static final String VIEW_NAME = "About"; // // public AboutView() { // add(new HorizontalLayout( // VaadinIcon.INFO_CIRCLE.create(), // new Span(" This application is using Vaadin Flow " + Version.getFullVersion()) // )); // add(new Span("running on top of Vert.x " + VersionCommand.getVersion())); // add(new Span("using Vertx-Vaadin-Flow " + VertxVaadin.getVersion())); // // add(buildLink("http://vaadin.com/", "Vaadin web page")); // add(buildLink("http://vertx.io/", "Vert.x web page")); // add(buildLink("https://github.com/mcollovati/vertx-vaadin", "Vertx-Vaadin web page")); // // // setSizeFull(); // setJustifyContentMode(JustifyContentMode.CENTER); // setAlignItems(Alignment.CENTER); // } // // private Anchor buildLink(String href, String text) { // Anchor anchor = new Anchor(href, text); // anchor.setTarget("_blank"); // return anchor; // } // // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudView.java // @Route(value = "Inventory", layout = MainLayout.class) // @RouteAlias(value = "", layout = MainLayout.class) // public class SampleCrudView extends HorizontalLayout // implements HasUrlParameter<String> { // // public static final String VIEW_NAME = "Inventory"; // private ProductGrid grid; // private ProductForm form; // private TextField filter; // // private SampleCrudLogic viewLogic = new SampleCrudLogic(this); // private Button newProduct; // // private ProductDataProvider dataProvider = new ProductDataProvider(); // // public SampleCrudView() { // setSizeFull(); // HorizontalLayout topLayout = createTopBar(); // // grid = new ProductGrid(); // grid.setDataProvider(dataProvider); // grid.asSingleSelect().addValueChangeListener( // event -> viewLogic.rowSelected(event.getValue())); // // form = new ProductForm(viewLogic); // form.setCategories(DataService.get().getAllCategories()); // // VerticalLayout barAndGridLayout = new VerticalLayout(); // barAndGridLayout.add(topLayout); // barAndGridLayout.add(grid); // barAndGridLayout.setFlexGrow(1, grid); // barAndGridLayout.setFlexGrow(0, topLayout); // barAndGridLayout.setSizeFull(); // barAndGridLayout.expand(grid); // // add(barAndGridLayout); // add(form); // // viewLogic.init(); // } // // public HorizontalLayout createTopBar() { // filter = new TextField(); // filter.setPlaceholder("Filter name, availability or category"); // // Apply the filter to grid's data provider. TextField value is never null // filter.addValueChangeListener(event -> dataProvider.setFilter(event.getValue())); // // newProduct = new Button("New product"); // newProduct.getElement().getThemeList().add("primary"); // newProduct.setIcon(VaadinIcon.PLUS_CIRCLE.create()); // newProduct.addClickListener(click -> viewLogic.newProduct()); // // HorizontalLayout topLayout = new HorizontalLayout(); // topLayout.setWidth("100%"); // topLayout.add(filter); // topLayout.add(newProduct); // topLayout.setVerticalComponentAlignment(Alignment.START, filter); // topLayout.expand(filter); // return topLayout; // } // // public void showError(String msg) { // Notification.show(msg); // } // // public void showSaveNotification(String msg) { // Notification.show(msg); // } // // public void setNewProductEnabled(boolean enabled) { // newProduct.setEnabled(enabled); // } // // public void clearSelection() { // grid.getSelectionModel().deselectAll(); // } // // public void selectRow(Product row) { // grid.getSelectionModel().select(row); // } // // public Product getSelectedRow() { // return grid.getSelectedRow(); // } // // public void updateProduct(Product product) { // dataProvider.save(product); // } // // public void removeProduct(Product product) { // dataProvider.delete(product); // } // // public void editProduct(Product product) { // showForm(product != null); // form.editProduct(product); // } // // public void showForm(boolean show) { // form.setVisible(show); // form.getElement().setEnabled(show); // } // // @Override // public void setParameter(BeforeEvent event, // @OptionalParameter String parameter) { // viewLogic.enter(parameter); // } // }
import com.vaadin.flow.component.dependency.StyleSheet; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.FlexLayout; import com.vaadin.flow.router.RouterLayout; import com.vaadin.flow.theme.Theme; import com.vaadin.flow.theme.lumo.Lumo; import com.github.mcollovati.vertxvaadin.flowdemo.about.AboutView; import com.github.mcollovati.vertxvaadin.flowdemo.crud.SampleCrudView;
package com.github.mcollovati.vertxvaadin.flowdemo; //import com.vaadin.flow.server.PWA; /** * The layout of the pages e.g. About and Inventory. */ @StyleSheet("css/shared-styles.css") @Theme(value = Lumo.class, variant = Lumo.DARK) public class MainLayout extends FlexLayout implements RouterLayout { private Menu menu; public MainLayout() { setSizeFull(); setClassName("main-layout"); menu = new Menu();
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/about/AboutView.java // @Route(value = "About", layout = MainLayout.class) // @PageTitle("About") // public class AboutView extends VerticalLayout { // // public static final String VIEW_NAME = "About"; // // public AboutView() { // add(new HorizontalLayout( // VaadinIcon.INFO_CIRCLE.create(), // new Span(" This application is using Vaadin Flow " + Version.getFullVersion()) // )); // add(new Span("running on top of Vert.x " + VersionCommand.getVersion())); // add(new Span("using Vertx-Vaadin-Flow " + VertxVaadin.getVersion())); // // add(buildLink("http://vaadin.com/", "Vaadin web page")); // add(buildLink("http://vertx.io/", "Vert.x web page")); // add(buildLink("https://github.com/mcollovati/vertx-vaadin", "Vertx-Vaadin web page")); // // // setSizeFull(); // setJustifyContentMode(JustifyContentMode.CENTER); // setAlignItems(Alignment.CENTER); // } // // private Anchor buildLink(String href, String text) { // Anchor anchor = new Anchor(href, text); // anchor.setTarget("_blank"); // return anchor; // } // // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudView.java // @Route(value = "Inventory", layout = MainLayout.class) // @RouteAlias(value = "", layout = MainLayout.class) // public class SampleCrudView extends HorizontalLayout // implements HasUrlParameter<String> { // // public static final String VIEW_NAME = "Inventory"; // private ProductGrid grid; // private ProductForm form; // private TextField filter; // // private SampleCrudLogic viewLogic = new SampleCrudLogic(this); // private Button newProduct; // // private ProductDataProvider dataProvider = new ProductDataProvider(); // // public SampleCrudView() { // setSizeFull(); // HorizontalLayout topLayout = createTopBar(); // // grid = new ProductGrid(); // grid.setDataProvider(dataProvider); // grid.asSingleSelect().addValueChangeListener( // event -> viewLogic.rowSelected(event.getValue())); // // form = new ProductForm(viewLogic); // form.setCategories(DataService.get().getAllCategories()); // // VerticalLayout barAndGridLayout = new VerticalLayout(); // barAndGridLayout.add(topLayout); // barAndGridLayout.add(grid); // barAndGridLayout.setFlexGrow(1, grid); // barAndGridLayout.setFlexGrow(0, topLayout); // barAndGridLayout.setSizeFull(); // barAndGridLayout.expand(grid); // // add(barAndGridLayout); // add(form); // // viewLogic.init(); // } // // public HorizontalLayout createTopBar() { // filter = new TextField(); // filter.setPlaceholder("Filter name, availability or category"); // // Apply the filter to grid's data provider. TextField value is never null // filter.addValueChangeListener(event -> dataProvider.setFilter(event.getValue())); // // newProduct = new Button("New product"); // newProduct.getElement().getThemeList().add("primary"); // newProduct.setIcon(VaadinIcon.PLUS_CIRCLE.create()); // newProduct.addClickListener(click -> viewLogic.newProduct()); // // HorizontalLayout topLayout = new HorizontalLayout(); // topLayout.setWidth("100%"); // topLayout.add(filter); // topLayout.add(newProduct); // topLayout.setVerticalComponentAlignment(Alignment.START, filter); // topLayout.expand(filter); // return topLayout; // } // // public void showError(String msg) { // Notification.show(msg); // } // // public void showSaveNotification(String msg) { // Notification.show(msg); // } // // public void setNewProductEnabled(boolean enabled) { // newProduct.setEnabled(enabled); // } // // public void clearSelection() { // grid.getSelectionModel().deselectAll(); // } // // public void selectRow(Product row) { // grid.getSelectionModel().select(row); // } // // public Product getSelectedRow() { // return grid.getSelectedRow(); // } // // public void updateProduct(Product product) { // dataProvider.save(product); // } // // public void removeProduct(Product product) { // dataProvider.delete(product); // } // // public void editProduct(Product product) { // showForm(product != null); // form.editProduct(product); // } // // public void showForm(boolean show) { // form.setVisible(show); // form.getElement().setEnabled(show); // } // // @Override // public void setParameter(BeforeEvent event, // @OptionalParameter String parameter) { // viewLogic.enter(parameter); // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/MainLayout.java import com.vaadin.flow.component.dependency.StyleSheet; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.FlexLayout; import com.vaadin.flow.router.RouterLayout; import com.vaadin.flow.theme.Theme; import com.vaadin.flow.theme.lumo.Lumo; import com.github.mcollovati.vertxvaadin.flowdemo.about.AboutView; import com.github.mcollovati.vertxvaadin.flowdemo.crud.SampleCrudView; package com.github.mcollovati.vertxvaadin.flowdemo; //import com.vaadin.flow.server.PWA; /** * The layout of the pages e.g. About and Inventory. */ @StyleSheet("css/shared-styles.css") @Theme(value = Lumo.class, variant = Lumo.DARK) public class MainLayout extends FlexLayout implements RouterLayout { private Menu menu; public MainLayout() { setSizeFull(); setClassName("main-layout"); menu = new Menu();
menu.addView(SampleCrudView.class, SampleCrudView.VIEW_NAME,
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/MainLayout.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/about/AboutView.java // @Route(value = "About", layout = MainLayout.class) // @PageTitle("About") // public class AboutView extends VerticalLayout { // // public static final String VIEW_NAME = "About"; // // public AboutView() { // add(new HorizontalLayout( // VaadinIcon.INFO_CIRCLE.create(), // new Span(" This application is using Vaadin Flow " + Version.getFullVersion()) // )); // add(new Span("running on top of Vert.x " + VersionCommand.getVersion())); // add(new Span("using Vertx-Vaadin-Flow " + VertxVaadin.getVersion())); // // add(buildLink("http://vaadin.com/", "Vaadin web page")); // add(buildLink("http://vertx.io/", "Vert.x web page")); // add(buildLink("https://github.com/mcollovati/vertx-vaadin", "Vertx-Vaadin web page")); // // // setSizeFull(); // setJustifyContentMode(JustifyContentMode.CENTER); // setAlignItems(Alignment.CENTER); // } // // private Anchor buildLink(String href, String text) { // Anchor anchor = new Anchor(href, text); // anchor.setTarget("_blank"); // return anchor; // } // // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudView.java // @Route(value = "Inventory", layout = MainLayout.class) // @RouteAlias(value = "", layout = MainLayout.class) // public class SampleCrudView extends HorizontalLayout // implements HasUrlParameter<String> { // // public static final String VIEW_NAME = "Inventory"; // private ProductGrid grid; // private ProductForm form; // private TextField filter; // // private SampleCrudLogic viewLogic = new SampleCrudLogic(this); // private Button newProduct; // // private ProductDataProvider dataProvider = new ProductDataProvider(); // // public SampleCrudView() { // setSizeFull(); // HorizontalLayout topLayout = createTopBar(); // // grid = new ProductGrid(); // grid.setDataProvider(dataProvider); // grid.asSingleSelect().addValueChangeListener( // event -> viewLogic.rowSelected(event.getValue())); // // form = new ProductForm(viewLogic); // form.setCategories(DataService.get().getAllCategories()); // // VerticalLayout barAndGridLayout = new VerticalLayout(); // barAndGridLayout.add(topLayout); // barAndGridLayout.add(grid); // barAndGridLayout.setFlexGrow(1, grid); // barAndGridLayout.setFlexGrow(0, topLayout); // barAndGridLayout.setSizeFull(); // barAndGridLayout.expand(grid); // // add(barAndGridLayout); // add(form); // // viewLogic.init(); // } // // public HorizontalLayout createTopBar() { // filter = new TextField(); // filter.setPlaceholder("Filter name, availability or category"); // // Apply the filter to grid's data provider. TextField value is never null // filter.addValueChangeListener(event -> dataProvider.setFilter(event.getValue())); // // newProduct = new Button("New product"); // newProduct.getElement().getThemeList().add("primary"); // newProduct.setIcon(VaadinIcon.PLUS_CIRCLE.create()); // newProduct.addClickListener(click -> viewLogic.newProduct()); // // HorizontalLayout topLayout = new HorizontalLayout(); // topLayout.setWidth("100%"); // topLayout.add(filter); // topLayout.add(newProduct); // topLayout.setVerticalComponentAlignment(Alignment.START, filter); // topLayout.expand(filter); // return topLayout; // } // // public void showError(String msg) { // Notification.show(msg); // } // // public void showSaveNotification(String msg) { // Notification.show(msg); // } // // public void setNewProductEnabled(boolean enabled) { // newProduct.setEnabled(enabled); // } // // public void clearSelection() { // grid.getSelectionModel().deselectAll(); // } // // public void selectRow(Product row) { // grid.getSelectionModel().select(row); // } // // public Product getSelectedRow() { // return grid.getSelectedRow(); // } // // public void updateProduct(Product product) { // dataProvider.save(product); // } // // public void removeProduct(Product product) { // dataProvider.delete(product); // } // // public void editProduct(Product product) { // showForm(product != null); // form.editProduct(product); // } // // public void showForm(boolean show) { // form.setVisible(show); // form.getElement().setEnabled(show); // } // // @Override // public void setParameter(BeforeEvent event, // @OptionalParameter String parameter) { // viewLogic.enter(parameter); // } // }
import com.vaadin.flow.component.dependency.StyleSheet; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.FlexLayout; import com.vaadin.flow.router.RouterLayout; import com.vaadin.flow.theme.Theme; import com.vaadin.flow.theme.lumo.Lumo; import com.github.mcollovati.vertxvaadin.flowdemo.about.AboutView; import com.github.mcollovati.vertxvaadin.flowdemo.crud.SampleCrudView;
package com.github.mcollovati.vertxvaadin.flowdemo; //import com.vaadin.flow.server.PWA; /** * The layout of the pages e.g. About and Inventory. */ @StyleSheet("css/shared-styles.css") @Theme(value = Lumo.class, variant = Lumo.DARK) public class MainLayout extends FlexLayout implements RouterLayout { private Menu menu; public MainLayout() { setSizeFull(); setClassName("main-layout"); menu = new Menu(); menu.addView(SampleCrudView.class, SampleCrudView.VIEW_NAME, VaadinIcon.EDIT.create());
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/about/AboutView.java // @Route(value = "About", layout = MainLayout.class) // @PageTitle("About") // public class AboutView extends VerticalLayout { // // public static final String VIEW_NAME = "About"; // // public AboutView() { // add(new HorizontalLayout( // VaadinIcon.INFO_CIRCLE.create(), // new Span(" This application is using Vaadin Flow " + Version.getFullVersion()) // )); // add(new Span("running on top of Vert.x " + VersionCommand.getVersion())); // add(new Span("using Vertx-Vaadin-Flow " + VertxVaadin.getVersion())); // // add(buildLink("http://vaadin.com/", "Vaadin web page")); // add(buildLink("http://vertx.io/", "Vert.x web page")); // add(buildLink("https://github.com/mcollovati/vertx-vaadin", "Vertx-Vaadin web page")); // // // setSizeFull(); // setJustifyContentMode(JustifyContentMode.CENTER); // setAlignItems(Alignment.CENTER); // } // // private Anchor buildLink(String href, String text) { // Anchor anchor = new Anchor(href, text); // anchor.setTarget("_blank"); // return anchor; // } // // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudView.java // @Route(value = "Inventory", layout = MainLayout.class) // @RouteAlias(value = "", layout = MainLayout.class) // public class SampleCrudView extends HorizontalLayout // implements HasUrlParameter<String> { // // public static final String VIEW_NAME = "Inventory"; // private ProductGrid grid; // private ProductForm form; // private TextField filter; // // private SampleCrudLogic viewLogic = new SampleCrudLogic(this); // private Button newProduct; // // private ProductDataProvider dataProvider = new ProductDataProvider(); // // public SampleCrudView() { // setSizeFull(); // HorizontalLayout topLayout = createTopBar(); // // grid = new ProductGrid(); // grid.setDataProvider(dataProvider); // grid.asSingleSelect().addValueChangeListener( // event -> viewLogic.rowSelected(event.getValue())); // // form = new ProductForm(viewLogic); // form.setCategories(DataService.get().getAllCategories()); // // VerticalLayout barAndGridLayout = new VerticalLayout(); // barAndGridLayout.add(topLayout); // barAndGridLayout.add(grid); // barAndGridLayout.setFlexGrow(1, grid); // barAndGridLayout.setFlexGrow(0, topLayout); // barAndGridLayout.setSizeFull(); // barAndGridLayout.expand(grid); // // add(barAndGridLayout); // add(form); // // viewLogic.init(); // } // // public HorizontalLayout createTopBar() { // filter = new TextField(); // filter.setPlaceholder("Filter name, availability or category"); // // Apply the filter to grid's data provider. TextField value is never null // filter.addValueChangeListener(event -> dataProvider.setFilter(event.getValue())); // // newProduct = new Button("New product"); // newProduct.getElement().getThemeList().add("primary"); // newProduct.setIcon(VaadinIcon.PLUS_CIRCLE.create()); // newProduct.addClickListener(click -> viewLogic.newProduct()); // // HorizontalLayout topLayout = new HorizontalLayout(); // topLayout.setWidth("100%"); // topLayout.add(filter); // topLayout.add(newProduct); // topLayout.setVerticalComponentAlignment(Alignment.START, filter); // topLayout.expand(filter); // return topLayout; // } // // public void showError(String msg) { // Notification.show(msg); // } // // public void showSaveNotification(String msg) { // Notification.show(msg); // } // // public void setNewProductEnabled(boolean enabled) { // newProduct.setEnabled(enabled); // } // // public void clearSelection() { // grid.getSelectionModel().deselectAll(); // } // // public void selectRow(Product row) { // grid.getSelectionModel().select(row); // } // // public Product getSelectedRow() { // return grid.getSelectedRow(); // } // // public void updateProduct(Product product) { // dataProvider.save(product); // } // // public void removeProduct(Product product) { // dataProvider.delete(product); // } // // public void editProduct(Product product) { // showForm(product != null); // form.editProduct(product); // } // // public void showForm(boolean show) { // form.setVisible(show); // form.getElement().setEnabled(show); // } // // @Override // public void setParameter(BeforeEvent event, // @OptionalParameter String parameter) { // viewLogic.enter(parameter); // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/MainLayout.java import com.vaadin.flow.component.dependency.StyleSheet; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.FlexLayout; import com.vaadin.flow.router.RouterLayout; import com.vaadin.flow.theme.Theme; import com.vaadin.flow.theme.lumo.Lumo; import com.github.mcollovati.vertxvaadin.flowdemo.about.AboutView; import com.github.mcollovati.vertxvaadin.flowdemo.crud.SampleCrudView; package com.github.mcollovati.vertxvaadin.flowdemo; //import com.vaadin.flow.server.PWA; /** * The layout of the pages e.g. About and Inventory. */ @StyleSheet("css/shared-styles.css") @Theme(value = Lumo.class, variant = Lumo.DARK) public class MainLayout extends FlexLayout implements RouterLayout { private Menu menu; public MainLayout() { setSizeFull(); setClassName("main-layout"); menu = new Menu(); menu.addView(SampleCrudView.class, SampleCrudView.VIEW_NAME, VaadinIcon.EDIT.create());
menu.addView(AboutView.class, AboutView.VIEW_NAME,
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // }
import java.io.Serializable; import java.util.Collection; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import com.github.mcollovati.vertxvaadin.flowdemo.backend.mock.MockDataService;
package com.github.mcollovati.vertxvaadin.flowdemo.backend; /** * Back-end service interface for retrieving and updating product data. */ public abstract class DataService implements Serializable { public abstract Collection<Product> getAllProducts();
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // } // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java import java.io.Serializable; import java.util.Collection; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import com.github.mcollovati.vertxvaadin.flowdemo.backend.mock.MockDataService; package com.github.mcollovati.vertxvaadin.flowdemo.backend; /** * Back-end service interface for retrieving and updating product data. */ public abstract class DataService implements Serializable { public abstract Collection<Product> getAllProducts();
public abstract Collection<Category> getAllCategories();
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // }
import java.io.Serializable; import java.util.Collection; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import com.github.mcollovati.vertxvaadin.flowdemo.backend.mock.MockDataService;
package com.github.mcollovati.vertxvaadin.flowdemo.backend; /** * Back-end service interface for retrieving and updating product data. */ public abstract class DataService implements Serializable { public abstract Collection<Product> getAllProducts(); public abstract Collection<Category> getAllCategories(); public abstract void updateProduct(Product p); public abstract void deleteProduct(int productId); public abstract Product getProductById(int productId); public static DataService get() {
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // } // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java import java.io.Serializable; import java.util.Collection; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; import com.github.mcollovati.vertxvaadin.flowdemo.backend.mock.MockDataService; package com.github.mcollovati.vertxvaadin.flowdemo.backend; /** * Back-end service interface for retrieving and updating product data. */ public abstract class DataService implements Serializable { public abstract Collection<Product> getAllProducts(); public abstract Collection<Category> getAllCategories(); public abstract void updateProduct(Product p); public abstract void deleteProduct(int productId); public abstract Product getProductById(int productId); public static DataService get() {
return MockDataService.getInstance();
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudLogic.java
// Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/MyUI.java // @Viewport("user-scalable=no,initial-scale=1.0") // @Theme("mytheme") // @Widgetset("com.github.mcollovati.vaadin.exampleapp.MyAppWidgetset") // @Push // public class MyUI extends UI { // // private AccessControl accessControl = new BasicAccessControl(); // // @Override // protected void init(VaadinRequest vaadinRequest) { // setPushConnection(new SockJSPushConnection(this)); // Responsive.makeResponsive(this); // setLocale(vaadinRequest.getLocale()); // getPage().setTitle("My"); // if (!accessControl.isUserSignedIn()) { // setContent(new LoginScreen(accessControl, new LoginListener() { // @Override // public void loginSuccessful() { // showMainView(); // } // })); // } else { // showMainView(); // } // } // // // /* Only for serialization debug purpose // private void readObject(ObjectInputStream in) // throws IOException, ClassNotFoundException { // in.defaultReadObject(); // System.out.println("============= MyUI::readObject syncid " + getConnectorTracker().getCurrentSyncId()); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // System.out.println("============= MyUI::writeObject syncid " + getConnectorTracker().getCurrentSyncId()); // out.defaultWriteObject(); // } // */ // // @Override // public void attach() { // super.attach(); // /* // UIProxy proxy = new UIProxy(this); // // proxy.runLater(() -> { // UI safe = UI.getCurrent(); // safe.getPage().setTitle("Changed with safeUI"); // }, 15, TimeUnit.SECONDS); // */ // // } // // protected void showMainView() { // addStyleName(ValoTheme.UI_WITH_MENU); // setContent(new MainScreen(MyUI.this)); // getNavigator().navigateTo(getNavigator().getState()); // } // // public AccessControl getAccessControl() { // return accessControl; // } // // public static MyUI get() { // return (MyUI) UI.getCurrent(); // } // // @VaadinServletConfiguration(ui = MyUI.class, productionMode = false) // public static class ExampleUIVerticle extends VaadinVerticle { // } // // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import com.github.mcollovati.vaadin.exampleapp.MyUI; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import java.io.Serializable; import com.vaadin.server.Page;
package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * This class provides an interface for the logical operations between the CRUD * view, its parts like the product editor form and the data source, including * fetching and saving products. * * Having this separate from the view makes it easier to test various parts of * the system separately, and to e.g. provide alternative views for the same * data. */ public class SampleCrudLogic implements Serializable { private SampleCrudView view; public SampleCrudLogic(SampleCrudView simpleCrudView) { view = simpleCrudView; } public void init() { editProduct(null); // Hide and disable if not admin
// Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/MyUI.java // @Viewport("user-scalable=no,initial-scale=1.0") // @Theme("mytheme") // @Widgetset("com.github.mcollovati.vaadin.exampleapp.MyAppWidgetset") // @Push // public class MyUI extends UI { // // private AccessControl accessControl = new BasicAccessControl(); // // @Override // protected void init(VaadinRequest vaadinRequest) { // setPushConnection(new SockJSPushConnection(this)); // Responsive.makeResponsive(this); // setLocale(vaadinRequest.getLocale()); // getPage().setTitle("My"); // if (!accessControl.isUserSignedIn()) { // setContent(new LoginScreen(accessControl, new LoginListener() { // @Override // public void loginSuccessful() { // showMainView(); // } // })); // } else { // showMainView(); // } // } // // // /* Only for serialization debug purpose // private void readObject(ObjectInputStream in) // throws IOException, ClassNotFoundException { // in.defaultReadObject(); // System.out.println("============= MyUI::readObject syncid " + getConnectorTracker().getCurrentSyncId()); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // System.out.println("============= MyUI::writeObject syncid " + getConnectorTracker().getCurrentSyncId()); // out.defaultWriteObject(); // } // */ // // @Override // public void attach() { // super.attach(); // /* // UIProxy proxy = new UIProxy(this); // // proxy.runLater(() -> { // UI safe = UI.getCurrent(); // safe.getPage().setTitle("Changed with safeUI"); // }, 15, TimeUnit.SECONDS); // */ // // } // // protected void showMainView() { // addStyleName(ValoTheme.UI_WITH_MENU); // setContent(new MainScreen(MyUI.this)); // getNavigator().navigateTo(getNavigator().getState()); // } // // public AccessControl getAccessControl() { // return accessControl; // } // // public static MyUI get() { // return (MyUI) UI.getCurrent(); // } // // @VaadinServletConfiguration(ui = MyUI.class, productionMode = false) // public static class ExampleUIVerticle extends VaadinVerticle { // } // // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudLogic.java import com.github.mcollovati.vaadin.exampleapp.MyUI; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import java.io.Serializable; import com.vaadin.server.Page; package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * This class provides an interface for the logical operations between the CRUD * view, its parts like the product editor form and the data source, including * fetching and saving products. * * Having this separate from the view makes it easier to test various parts of * the system separately, and to e.g. provide alternative views for the same * data. */ public class SampleCrudLogic implements Serializable { private SampleCrudView view; public SampleCrudLogic(SampleCrudView simpleCrudView) { view = simpleCrudView; } public void init() { editProduct(null); // Hide and disable if not admin
if (!MyUI.get().getAccessControl().isUserInRole("admin")) {
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudLogic.java
// Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/MyUI.java // @Viewport("user-scalable=no,initial-scale=1.0") // @Theme("mytheme") // @Widgetset("com.github.mcollovati.vaadin.exampleapp.MyAppWidgetset") // @Push // public class MyUI extends UI { // // private AccessControl accessControl = new BasicAccessControl(); // // @Override // protected void init(VaadinRequest vaadinRequest) { // setPushConnection(new SockJSPushConnection(this)); // Responsive.makeResponsive(this); // setLocale(vaadinRequest.getLocale()); // getPage().setTitle("My"); // if (!accessControl.isUserSignedIn()) { // setContent(new LoginScreen(accessControl, new LoginListener() { // @Override // public void loginSuccessful() { // showMainView(); // } // })); // } else { // showMainView(); // } // } // // // /* Only for serialization debug purpose // private void readObject(ObjectInputStream in) // throws IOException, ClassNotFoundException { // in.defaultReadObject(); // System.out.println("============= MyUI::readObject syncid " + getConnectorTracker().getCurrentSyncId()); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // System.out.println("============= MyUI::writeObject syncid " + getConnectorTracker().getCurrentSyncId()); // out.defaultWriteObject(); // } // */ // // @Override // public void attach() { // super.attach(); // /* // UIProxy proxy = new UIProxy(this); // // proxy.runLater(() -> { // UI safe = UI.getCurrent(); // safe.getPage().setTitle("Changed with safeUI"); // }, 15, TimeUnit.SECONDS); // */ // // } // // protected void showMainView() { // addStyleName(ValoTheme.UI_WITH_MENU); // setContent(new MainScreen(MyUI.this)); // getNavigator().navigateTo(getNavigator().getState()); // } // // public AccessControl getAccessControl() { // return accessControl; // } // // public static MyUI get() { // return (MyUI) UI.getCurrent(); // } // // @VaadinServletConfiguration(ui = MyUI.class, productionMode = false) // public static class ExampleUIVerticle extends VaadinVerticle { // } // // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import com.github.mcollovati.vaadin.exampleapp.MyUI; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import java.io.Serializable; import com.vaadin.server.Page;
setFragmentParameter(""); view.clearSelection(); } /** * Update the fragment without causing navigator to change view */ private void setFragmentParameter(String productId) { String fragmentParameter; if (productId == null || productId.isEmpty()) { fragmentParameter = ""; } else { fragmentParameter = productId; } Page page = MyUI.get().getPage(); page.setUriFragment( "!" + SampleCrudView.VIEW_NAME + "/" + fragmentParameter, false); } public void enter(String productId) { if (productId != null && !productId.isEmpty()) { if (productId.equals("new")) { newProduct(); } else { // Ensure this is selected even if coming directly here from // login try { int pid = Integer.parseInt(productId);
// Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/MyUI.java // @Viewport("user-scalable=no,initial-scale=1.0") // @Theme("mytheme") // @Widgetset("com.github.mcollovati.vaadin.exampleapp.MyAppWidgetset") // @Push // public class MyUI extends UI { // // private AccessControl accessControl = new BasicAccessControl(); // // @Override // protected void init(VaadinRequest vaadinRequest) { // setPushConnection(new SockJSPushConnection(this)); // Responsive.makeResponsive(this); // setLocale(vaadinRequest.getLocale()); // getPage().setTitle("My"); // if (!accessControl.isUserSignedIn()) { // setContent(new LoginScreen(accessControl, new LoginListener() { // @Override // public void loginSuccessful() { // showMainView(); // } // })); // } else { // showMainView(); // } // } // // // /* Only for serialization debug purpose // private void readObject(ObjectInputStream in) // throws IOException, ClassNotFoundException { // in.defaultReadObject(); // System.out.println("============= MyUI::readObject syncid " + getConnectorTracker().getCurrentSyncId()); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // System.out.println("============= MyUI::writeObject syncid " + getConnectorTracker().getCurrentSyncId()); // out.defaultWriteObject(); // } // */ // // @Override // public void attach() { // super.attach(); // /* // UIProxy proxy = new UIProxy(this); // // proxy.runLater(() -> { // UI safe = UI.getCurrent(); // safe.getPage().setTitle("Changed with safeUI"); // }, 15, TimeUnit.SECONDS); // */ // // } // // protected void showMainView() { // addStyleName(ValoTheme.UI_WITH_MENU); // setContent(new MainScreen(MyUI.this)); // getNavigator().navigateTo(getNavigator().getState()); // } // // public AccessControl getAccessControl() { // return accessControl; // } // // public static MyUI get() { // return (MyUI) UI.getCurrent(); // } // // @VaadinServletConfiguration(ui = MyUI.class, productionMode = false) // public static class ExampleUIVerticle extends VaadinVerticle { // } // // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudLogic.java import com.github.mcollovati.vaadin.exampleapp.MyUI; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import java.io.Serializable; import com.vaadin.server.Page; setFragmentParameter(""); view.clearSelection(); } /** * Update the fragment without causing navigator to change view */ private void setFragmentParameter(String productId) { String fragmentParameter; if (productId == null || productId.isEmpty()) { fragmentParameter = ""; } else { fragmentParameter = productId; } Page page = MyUI.get().getPage(); page.setUriFragment( "!" + SampleCrudView.VIEW_NAME + "/" + fragmentParameter, false); } public void enter(String productId) { if (productId != null && !productId.isEmpty()) { if (productId.equals("new")) { newProduct(); } else { // Ensure this is selected even if coming directly here from // login try { int pid = Integer.parseInt(productId);
Product product = findProduct(pid);
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudLogic.java
// Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/MyUI.java // @Viewport("user-scalable=no,initial-scale=1.0") // @Theme("mytheme") // @Widgetset("com.github.mcollovati.vaadin.exampleapp.MyAppWidgetset") // @Push // public class MyUI extends UI { // // private AccessControl accessControl = new BasicAccessControl(); // // @Override // protected void init(VaadinRequest vaadinRequest) { // setPushConnection(new SockJSPushConnection(this)); // Responsive.makeResponsive(this); // setLocale(vaadinRequest.getLocale()); // getPage().setTitle("My"); // if (!accessControl.isUserSignedIn()) { // setContent(new LoginScreen(accessControl, new LoginListener() { // @Override // public void loginSuccessful() { // showMainView(); // } // })); // } else { // showMainView(); // } // } // // // /* Only for serialization debug purpose // private void readObject(ObjectInputStream in) // throws IOException, ClassNotFoundException { // in.defaultReadObject(); // System.out.println("============= MyUI::readObject syncid " + getConnectorTracker().getCurrentSyncId()); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // System.out.println("============= MyUI::writeObject syncid " + getConnectorTracker().getCurrentSyncId()); // out.defaultWriteObject(); // } // */ // // @Override // public void attach() { // super.attach(); // /* // UIProxy proxy = new UIProxy(this); // // proxy.runLater(() -> { // UI safe = UI.getCurrent(); // safe.getPage().setTitle("Changed with safeUI"); // }, 15, TimeUnit.SECONDS); // */ // // } // // protected void showMainView() { // addStyleName(ValoTheme.UI_WITH_MENU); // setContent(new MainScreen(MyUI.this)); // getNavigator().navigateTo(getNavigator().getState()); // } // // public AccessControl getAccessControl() { // return accessControl; // } // // public static MyUI get() { // return (MyUI) UI.getCurrent(); // } // // @VaadinServletConfiguration(ui = MyUI.class, productionMode = false) // public static class ExampleUIVerticle extends VaadinVerticle { // } // // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import com.github.mcollovati.vaadin.exampleapp.MyUI; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import java.io.Serializable; import com.vaadin.server.Page;
if (productId == null || productId.isEmpty()) { fragmentParameter = ""; } else { fragmentParameter = productId; } Page page = MyUI.get().getPage(); page.setUriFragment( "!" + SampleCrudView.VIEW_NAME + "/" + fragmentParameter, false); } public void enter(String productId) { if (productId != null && !productId.isEmpty()) { if (productId.equals("new")) { newProduct(); } else { // Ensure this is selected even if coming directly here from // login try { int pid = Integer.parseInt(productId); Product product = findProduct(pid); view.selectRow(product); } catch (NumberFormatException e) { } } } } private Product findProduct(int productId) {
// Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/MyUI.java // @Viewport("user-scalable=no,initial-scale=1.0") // @Theme("mytheme") // @Widgetset("com.github.mcollovati.vaadin.exampleapp.MyAppWidgetset") // @Push // public class MyUI extends UI { // // private AccessControl accessControl = new BasicAccessControl(); // // @Override // protected void init(VaadinRequest vaadinRequest) { // setPushConnection(new SockJSPushConnection(this)); // Responsive.makeResponsive(this); // setLocale(vaadinRequest.getLocale()); // getPage().setTitle("My"); // if (!accessControl.isUserSignedIn()) { // setContent(new LoginScreen(accessControl, new LoginListener() { // @Override // public void loginSuccessful() { // showMainView(); // } // })); // } else { // showMainView(); // } // } // // // /* Only for serialization debug purpose // private void readObject(ObjectInputStream in) // throws IOException, ClassNotFoundException { // in.defaultReadObject(); // System.out.println("============= MyUI::readObject syncid " + getConnectorTracker().getCurrentSyncId()); // } // // private void writeObject(ObjectOutputStream out) throws IOException { // System.out.println("============= MyUI::writeObject syncid " + getConnectorTracker().getCurrentSyncId()); // out.defaultWriteObject(); // } // */ // // @Override // public void attach() { // super.attach(); // /* // UIProxy proxy = new UIProxy(this); // // proxy.runLater(() -> { // UI safe = UI.getCurrent(); // safe.getPage().setTitle("Changed with safeUI"); // }, 15, TimeUnit.SECONDS); // */ // // } // // protected void showMainView() { // addStyleName(ValoTheme.UI_WITH_MENU); // setContent(new MainScreen(MyUI.this)); // getNavigator().navigateTo(getNavigator().getState()); // } // // public AccessControl getAccessControl() { // return accessControl; // } // // public static MyUI get() { // return (MyUI) UI.getCurrent(); // } // // @VaadinServletConfiguration(ui = MyUI.class, productionMode = false) // public static class ExampleUIVerticle extends VaadinVerticle { // } // // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudLogic.java import com.github.mcollovati.vaadin.exampleapp.MyUI; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import java.io.Serializable; import com.vaadin.server.Page; if (productId == null || productId.isEmpty()) { fragmentParameter = ""; } else { fragmentParameter = productId; } Page page = MyUI.get().getPage(); page.setUriFragment( "!" + SampleCrudView.VIEW_NAME + "/" + fragmentParameter, false); } public void enter(String productId) { if (productId != null && !productId.isEmpty()) { if (productId.equals("new")) { newProduct(); } else { // Ensure this is selected even if coming directly here from // login try { int pid = Integer.parseInt(productId); Product product = findProduct(pid); view.selectRow(product); } catch (NumberFormatException e) { } } } } private Product findProduct(int productId) {
return DataService.get().getProductById(productId);
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import java.util.List; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product;
package com.github.mcollovati.vertxvaadin.flowdemo.backend.mock; /** * Mock data model. This implementation has very simplistic locking and does not * notify users of modifications. */ public class MockDataService extends DataService { private static MockDataService INSTANCE;
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java import java.util.List; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; package com.github.mcollovati.vertxvaadin.flowdemo.backend.mock; /** * Mock data model. This implementation has very simplistic locking and does not * notify users of modifications. */ public class MockDataService extends DataService { private static MockDataService INSTANCE;
private List<Product> products;
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import java.util.List; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product;
package com.github.mcollovati.vertxvaadin.flowdemo.backend.mock; /** * Mock data model. This implementation has very simplistic locking and does not * notify users of modifications. */ public class MockDataService extends DataService { private static MockDataService INSTANCE; private List<Product> products;
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataService.java import java.util.List; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; package com.github.mcollovati.vertxvaadin.flowdemo.backend.mock; /** * Mock data model. This implementation has very simplistic locking and does not * notify users of modifications. */ public class MockDataService extends DataService { private static MockDataService INSTANCE; private List<Product> products;
private List<Category> categories;
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductForm.java
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/AttributeExtension.java // @JavaScript("attribute_extension_connector.js") // public class AttributeExtension extends AbstractJavaScriptExtension { // // public void extend(TextField target) { // super.extend(target); // } // // @Override // protected AttributeExtensionState getState() { // return (AttributeExtensionState) super.getState(); // } // // public void setAttribute(String attribute, String value) { // getState().attributes.put(attribute, value); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.Locale; import com.github.mcollovati.vaadin.exampleapp.samples.AttributeExtension; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Result; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.ValueContext; import com.vaadin.server.Page;
package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * A form for editing a single product. * * Using responsive layouts, the form can be displayed either sliding out on the * side of the view or filling the whole screen - see the theme for the related * CSS rules. */ public class ProductForm extends ProductFormDesign { private SampleCrudLogic viewLogic;
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/AttributeExtension.java // @JavaScript("attribute_extension_connector.js") // public class AttributeExtension extends AbstractJavaScriptExtension { // // public void extend(TextField target) { // super.extend(target); // } // // @Override // protected AttributeExtensionState getState() { // return (AttributeExtensionState) super.getState(); // } // // public void setAttribute(String attribute, String value) { // getState().attributes.put(attribute, value); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductForm.java import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.Locale; import com.github.mcollovati.vaadin.exampleapp.samples.AttributeExtension; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Result; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.ValueContext; import com.vaadin.server.Page; package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * A form for editing a single product. * * Using responsive layouts, the form can be displayed either sliding out on the * side of the view or filling the whole screen - see the theme for the related * CSS rules. */ public class ProductForm extends ProductFormDesign { private SampleCrudLogic viewLogic;
private Binder<Product> binder;
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductForm.java
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/AttributeExtension.java // @JavaScript("attribute_extension_connector.js") // public class AttributeExtension extends AbstractJavaScriptExtension { // // public void extend(TextField target) { // super.extend(target); // } // // @Override // protected AttributeExtensionState getState() { // return (AttributeExtensionState) super.getState(); // } // // public void setAttribute(String attribute, String value) { // getState().attributes.put(attribute, value); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.Locale; import com.github.mcollovati.vaadin.exampleapp.samples.AttributeExtension; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Result; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.ValueContext; import com.vaadin.server.Page;
package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * A form for editing a single product. * * Using responsive layouts, the form can be displayed either sliding out on the * side of the view or filling the whole screen - see the theme for the related * CSS rules. */ public class ProductForm extends ProductFormDesign { private SampleCrudLogic viewLogic; private Binder<Product> binder; private Product currentProduct; private static class StockPriceConverter extends StringToIntegerConverter { public StockPriceConverter() { super("Could not convert value to " + Integer.class.getName()); } @Override protected NumberFormat getFormat(Locale locale) { // do not use a thousands separator, as HTML5 input type // number expects a fixed wire/DOM number format regardless // of how the browser presents it to the user (which could // depend on the browser locale) DecimalFormat format = new DecimalFormat(); format.setMaximumFractionDigits(0); format.setDecimalSeparatorAlwaysShown(false); format.setParseIntegerOnly(true); format.setGroupingUsed(false); return format; } @Override public Result<Integer> convertToModel(String value, ValueContext context) { Result<Integer> result = super.convertToModel(value, context); return result.map(stock -> stock == null ? 0 : stock); } } public ProductForm(SampleCrudLogic sampleCrudLogic) { super(); addStyleName("product-form"); viewLogic = sampleCrudLogic; // Mark the stock count field as numeric. // This affects the virtual keyboard shown on mobile devices.
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/AttributeExtension.java // @JavaScript("attribute_extension_connector.js") // public class AttributeExtension extends AbstractJavaScriptExtension { // // public void extend(TextField target) { // super.extend(target); // } // // @Override // protected AttributeExtensionState getState() { // return (AttributeExtensionState) super.getState(); // } // // public void setAttribute(String attribute, String value) { // getState().attributes.put(attribute, value); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductForm.java import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.Locale; import com.github.mcollovati.vaadin.exampleapp.samples.AttributeExtension; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Result; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.ValueContext; import com.vaadin.server.Page; package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * A form for editing a single product. * * Using responsive layouts, the form can be displayed either sliding out on the * side of the view or filling the whole screen - see the theme for the related * CSS rules. */ public class ProductForm extends ProductFormDesign { private SampleCrudLogic viewLogic; private Binder<Product> binder; private Product currentProduct; private static class StockPriceConverter extends StringToIntegerConverter { public StockPriceConverter() { super("Could not convert value to " + Integer.class.getName()); } @Override protected NumberFormat getFormat(Locale locale) { // do not use a thousands separator, as HTML5 input type // number expects a fixed wire/DOM number format regardless // of how the browser presents it to the user (which could // depend on the browser locale) DecimalFormat format = new DecimalFormat(); format.setMaximumFractionDigits(0); format.setDecimalSeparatorAlwaysShown(false); format.setParseIntegerOnly(true); format.setGroupingUsed(false); return format; } @Override public Result<Integer> convertToModel(String value, ValueContext context) { Result<Integer> result = super.convertToModel(value, context); return result.map(stock -> stock == null ? 0 : stock); } } public ProductForm(SampleCrudLogic sampleCrudLogic) { super(); addStyleName("product-form"); viewLogic = sampleCrudLogic; // Mark the stock count field as numeric. // This affects the virtual keyboard shown on mobile devices.
AttributeExtension stockFieldExtension = new AttributeExtension();
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductForm.java
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/AttributeExtension.java // @JavaScript("attribute_extension_connector.js") // public class AttributeExtension extends AbstractJavaScriptExtension { // // public void extend(TextField target) { // super.extend(target); // } // // @Override // protected AttributeExtensionState getState() { // return (AttributeExtensionState) super.getState(); // } // // public void setAttribute(String attribute, String value) { // getState().attributes.put(attribute, value); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.Locale; import com.github.mcollovati.vaadin.exampleapp.samples.AttributeExtension; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Result; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.ValueContext; import com.vaadin.server.Page;
// of how the browser presents it to the user (which could // depend on the browser locale) DecimalFormat format = new DecimalFormat(); format.setMaximumFractionDigits(0); format.setDecimalSeparatorAlwaysShown(false); format.setParseIntegerOnly(true); format.setGroupingUsed(false); return format; } @Override public Result<Integer> convertToModel(String value, ValueContext context) { Result<Integer> result = super.convertToModel(value, context); return result.map(stock -> stock == null ? 0 : stock); } } public ProductForm(SampleCrudLogic sampleCrudLogic) { super(); addStyleName("product-form"); viewLogic = sampleCrudLogic; // Mark the stock count field as numeric. // This affects the virtual keyboard shown on mobile devices. AttributeExtension stockFieldExtension = new AttributeExtension(); stockFieldExtension.extend(stockCount); stockFieldExtension.setAttribute("type", "number");
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/AttributeExtension.java // @JavaScript("attribute_extension_connector.js") // public class AttributeExtension extends AbstractJavaScriptExtension { // // public void extend(TextField target) { // super.extend(target); // } // // @Override // protected AttributeExtensionState getState() { // return (AttributeExtensionState) super.getState(); // } // // public void setAttribute(String attribute, String value) { // getState().attributes.put(attribute, value); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductForm.java import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.Locale; import com.github.mcollovati.vaadin.exampleapp.samples.AttributeExtension; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Result; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.ValueContext; import com.vaadin.server.Page; // of how the browser presents it to the user (which could // depend on the browser locale) DecimalFormat format = new DecimalFormat(); format.setMaximumFractionDigits(0); format.setDecimalSeparatorAlwaysShown(false); format.setParseIntegerOnly(true); format.setGroupingUsed(false); return format; } @Override public Result<Integer> convertToModel(String value, ValueContext context) { Result<Integer> result = super.convertToModel(value, context); return result.map(stock -> stock == null ? 0 : stock); } } public ProductForm(SampleCrudLogic sampleCrudLogic) { super(); addStyleName("product-form"); viewLogic = sampleCrudLogic; // Mark the stock count field as numeric. // This affects the virtual keyboard shown on mobile devices. AttributeExtension stockFieldExtension = new AttributeExtension(); stockFieldExtension.extend(stockCount); stockFieldExtension.setAttribute("type", "number");
availability.setItems(Availability.values());
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductForm.java
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/AttributeExtension.java // @JavaScript("attribute_extension_connector.js") // public class AttributeExtension extends AbstractJavaScriptExtension { // // public void extend(TextField target) { // super.extend(target); // } // // @Override // protected AttributeExtensionState getState() { // return (AttributeExtensionState) super.getState(); // } // // public void setAttribute(String attribute, String value) { // getState().attributes.put(attribute, value); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.Locale; import com.github.mcollovati.vaadin.exampleapp.samples.AttributeExtension; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Result; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.ValueContext; import com.vaadin.server.Page;
@Override public Result<Integer> convertToModel(String value, ValueContext context) { Result<Integer> result = super.convertToModel(value, context); return result.map(stock -> stock == null ? 0 : stock); } } public ProductForm(SampleCrudLogic sampleCrudLogic) { super(); addStyleName("product-form"); viewLogic = sampleCrudLogic; // Mark the stock count field as numeric. // This affects the virtual keyboard shown on mobile devices. AttributeExtension stockFieldExtension = new AttributeExtension(); stockFieldExtension.extend(stockCount); stockFieldExtension.setAttribute("type", "number"); availability.setItems(Availability.values()); availability.setEmptySelectionAllowed(false); binder = new BeanValidationBinder<>(Product.class); binder.forField(price).withConverter(new EuroConverter()) .bind("price"); binder.forField(stockCount).withConverter(new StockPriceConverter()) .bind("stockCount");
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/AttributeExtension.java // @JavaScript("attribute_extension_connector.js") // public class AttributeExtension extends AbstractJavaScriptExtension { // // public void extend(TextField target) { // super.extend(target); // } // // @Override // protected AttributeExtensionState getState() { // return (AttributeExtensionState) super.getState(); // } // // public void setAttribute(String attribute, String value) { // getState().attributes.put(attribute, value); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductForm.java import java.lang.reflect.InvocationTargetException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.Locale; import com.github.mcollovati.vaadin.exampleapp.samples.AttributeExtension; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Result; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.ValueContext; import com.vaadin.server.Page; @Override public Result<Integer> convertToModel(String value, ValueContext context) { Result<Integer> result = super.convertToModel(value, context); return result.map(stock -> stock == null ? 0 : stock); } } public ProductForm(SampleCrudLogic sampleCrudLogic) { super(); addStyleName("product-form"); viewLogic = sampleCrudLogic; // Mark the stock count field as numeric. // This affects the virtual keyboard shown on mobile devices. AttributeExtension stockFieldExtension = new AttributeExtension(); stockFieldExtension.extend(stockCount); stockFieldExtension.setAttribute("type", "number"); availability.setItems(Availability.values()); availability.setEmptySelectionAllowed(false); binder = new BeanValidationBinder<>(Product.class); binder.forField(price).withConverter(new EuroConverter()) .bind("price"); binder.forField(stockCount).withConverter(new StockPriceConverter()) .bind("stockCount");
category.setItemCaptionGenerator(Category::getName);
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/BookstoreInitListener.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/LoginScreen.java // @Route("Login") // @PageTitle("Login") // @StyleSheet("css/shared-styles.css") // public class LoginScreen extends FlexLayout { // // private TextField username; // private PasswordField password; // private Button login; // private Button forgotPassword; // private AccessControl accessControl; // // public LoginScreen() { // accessControl = AccessControlFactory.getInstance().createAccessControl(); // buildUI(); // username.focus(); // } // // private void buildUI() { // setSizeFull(); // setClassName("login-screen"); // // // login form, centered in the available part of the screen // Component loginForm = buildLoginForm(); // // // layout to center login form when there is sufficient screen space // FlexLayout centeringLayout = new FlexLayout(); // centeringLayout.setSizeFull(); // centeringLayout.setJustifyContentMode(JustifyContentMode.CENTER); // centeringLayout.setAlignItems(Alignment.CENTER); // centeringLayout.add(loginForm); // // // information text about logging in // Component loginInformation = buildLoginInformation(); // // add(loginInformation); // add(centeringLayout); // } // // private Component buildLoginForm() { // FormLayout loginForm = new FormLayout(); // // loginForm.setWidth("310px"); // // loginForm.addFormItem(username = new TextField(), "Username"); // username.setWidth("15em"); // username.setValue("admin"); // loginForm.add(new Html("<br/>")); // loginForm.addFormItem(password = new PasswordField(), "Password"); // password.setWidth("15em"); // // HorizontalLayout buttons = new HorizontalLayout(); // loginForm.add(new Html("<br/>")); // loginForm.add(buttons); // // buttons.add(login = new Button("Login")); // login.addClickListener(event -> login()); // loginForm.getElement().addEventListener("keypress", event -> login()).setFilter("event.key == 'Enter'"); // login.getElement().getThemeList().add("success primary"); // // buttons.add(forgotPassword = new Button("Forgot password?")); // forgotPassword.addClickListener(event -> showNotification(new Notification("Hint: try anything"))); // forgotPassword.getElement().getThemeList().add("tertiary"); // // return loginForm; // } // // private Component buildLoginInformation() { // VerticalLayout loginInformation = new VerticalLayout(); // loginInformation.setClassName("login-information"); // // H1 loginInfoHeader = new H1("Login Information"); // Span loginInfoText = new Span( // "Log in as \"admin\" to have full access. Log in with any other username to have read-only access. For all users, any password is fine."); // loginInformation.add(loginInfoHeader); // loginInformation.add(loginInfoText); // // return loginInformation; // } // // private void login() { // login.setEnabled(false); // try { // if (accessControl.signIn(username.getValue(), password.getValue())) { // getUI().get().navigate(""); // } else { // showNotification(new Notification("Login failed. " + // "Please check your username and password and try again.")); // username.focus(); // } // } finally { // login.setEnabled(true); // } // } // // private void showNotification(Notification notification) { // // keep the notification visible a little while after moving the // // mouse, or until clicked // notification.setDuration(2000); // notification.open(); // } // }
import com.vaadin.flow.server.ServiceInitEvent; import com.vaadin.flow.server.VaadinServiceInitListener; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.LoginScreen;
package com.github.mcollovati.vertxvaadin.flowdemo; /** * This class is used to listen to BeforeEnter event of all UIs in order to * check whether a user is signed in or not before allowing entering any page. * It is registered in a file named * com.vaadin.flow.server.VaadinServiceInitListener in META-INF/services. */ public class BookstoreInitListener implements VaadinServiceInitListener { @Override public void serviceInit(ServiceInitEvent initEvent) {
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/LoginScreen.java // @Route("Login") // @PageTitle("Login") // @StyleSheet("css/shared-styles.css") // public class LoginScreen extends FlexLayout { // // private TextField username; // private PasswordField password; // private Button login; // private Button forgotPassword; // private AccessControl accessControl; // // public LoginScreen() { // accessControl = AccessControlFactory.getInstance().createAccessControl(); // buildUI(); // username.focus(); // } // // private void buildUI() { // setSizeFull(); // setClassName("login-screen"); // // // login form, centered in the available part of the screen // Component loginForm = buildLoginForm(); // // // layout to center login form when there is sufficient screen space // FlexLayout centeringLayout = new FlexLayout(); // centeringLayout.setSizeFull(); // centeringLayout.setJustifyContentMode(JustifyContentMode.CENTER); // centeringLayout.setAlignItems(Alignment.CENTER); // centeringLayout.add(loginForm); // // // information text about logging in // Component loginInformation = buildLoginInformation(); // // add(loginInformation); // add(centeringLayout); // } // // private Component buildLoginForm() { // FormLayout loginForm = new FormLayout(); // // loginForm.setWidth("310px"); // // loginForm.addFormItem(username = new TextField(), "Username"); // username.setWidth("15em"); // username.setValue("admin"); // loginForm.add(new Html("<br/>")); // loginForm.addFormItem(password = new PasswordField(), "Password"); // password.setWidth("15em"); // // HorizontalLayout buttons = new HorizontalLayout(); // loginForm.add(new Html("<br/>")); // loginForm.add(buttons); // // buttons.add(login = new Button("Login")); // login.addClickListener(event -> login()); // loginForm.getElement().addEventListener("keypress", event -> login()).setFilter("event.key == 'Enter'"); // login.getElement().getThemeList().add("success primary"); // // buttons.add(forgotPassword = new Button("Forgot password?")); // forgotPassword.addClickListener(event -> showNotification(new Notification("Hint: try anything"))); // forgotPassword.getElement().getThemeList().add("tertiary"); // // return loginForm; // } // // private Component buildLoginInformation() { // VerticalLayout loginInformation = new VerticalLayout(); // loginInformation.setClassName("login-information"); // // H1 loginInfoHeader = new H1("Login Information"); // Span loginInfoText = new Span( // "Log in as \"admin\" to have full access. Log in with any other username to have read-only access. For all users, any password is fine."); // loginInformation.add(loginInfoHeader); // loginInformation.add(loginInfoText); // // return loginInformation; // } // // private void login() { // login.setEnabled(false); // try { // if (accessControl.signIn(username.getValue(), password.getValue())) { // getUI().get().navigate(""); // } else { // showNotification(new Notification("Login failed. " + // "Please check your username and password and try again.")); // username.focus(); // } // } finally { // login.setEnabled(true); // } // } // // private void showNotification(Notification notification) { // // keep the notification visible a little while after moving the // // mouse, or until clicked // notification.setDuration(2000); // notification.open(); // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/BookstoreInitListener.java import com.vaadin.flow.server.ServiceInitEvent; import com.vaadin.flow.server.VaadinServiceInitListener; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.LoginScreen; package com.github.mcollovati.vertxvaadin.flowdemo; /** * This class is used to listen to BeforeEnter event of all UIs in order to * check whether a user is signed in or not before allowing entering any page. * It is registered in a file named * com.vaadin.flow.server.VaadinServiceInitListener in META-INF/services. */ public class BookstoreInitListener implements VaadinServiceInitListener { @Override public void serviceInit(ServiceInitEvent initEvent) {
final AccessControl accessControl = AccessControlFactory.getInstance()
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/BookstoreInitListener.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/LoginScreen.java // @Route("Login") // @PageTitle("Login") // @StyleSheet("css/shared-styles.css") // public class LoginScreen extends FlexLayout { // // private TextField username; // private PasswordField password; // private Button login; // private Button forgotPassword; // private AccessControl accessControl; // // public LoginScreen() { // accessControl = AccessControlFactory.getInstance().createAccessControl(); // buildUI(); // username.focus(); // } // // private void buildUI() { // setSizeFull(); // setClassName("login-screen"); // // // login form, centered in the available part of the screen // Component loginForm = buildLoginForm(); // // // layout to center login form when there is sufficient screen space // FlexLayout centeringLayout = new FlexLayout(); // centeringLayout.setSizeFull(); // centeringLayout.setJustifyContentMode(JustifyContentMode.CENTER); // centeringLayout.setAlignItems(Alignment.CENTER); // centeringLayout.add(loginForm); // // // information text about logging in // Component loginInformation = buildLoginInformation(); // // add(loginInformation); // add(centeringLayout); // } // // private Component buildLoginForm() { // FormLayout loginForm = new FormLayout(); // // loginForm.setWidth("310px"); // // loginForm.addFormItem(username = new TextField(), "Username"); // username.setWidth("15em"); // username.setValue("admin"); // loginForm.add(new Html("<br/>")); // loginForm.addFormItem(password = new PasswordField(), "Password"); // password.setWidth("15em"); // // HorizontalLayout buttons = new HorizontalLayout(); // loginForm.add(new Html("<br/>")); // loginForm.add(buttons); // // buttons.add(login = new Button("Login")); // login.addClickListener(event -> login()); // loginForm.getElement().addEventListener("keypress", event -> login()).setFilter("event.key == 'Enter'"); // login.getElement().getThemeList().add("success primary"); // // buttons.add(forgotPassword = new Button("Forgot password?")); // forgotPassword.addClickListener(event -> showNotification(new Notification("Hint: try anything"))); // forgotPassword.getElement().getThemeList().add("tertiary"); // // return loginForm; // } // // private Component buildLoginInformation() { // VerticalLayout loginInformation = new VerticalLayout(); // loginInformation.setClassName("login-information"); // // H1 loginInfoHeader = new H1("Login Information"); // Span loginInfoText = new Span( // "Log in as \"admin\" to have full access. Log in with any other username to have read-only access. For all users, any password is fine."); // loginInformation.add(loginInfoHeader); // loginInformation.add(loginInfoText); // // return loginInformation; // } // // private void login() { // login.setEnabled(false); // try { // if (accessControl.signIn(username.getValue(), password.getValue())) { // getUI().get().navigate(""); // } else { // showNotification(new Notification("Login failed. " + // "Please check your username and password and try again.")); // username.focus(); // } // } finally { // login.setEnabled(true); // } // } // // private void showNotification(Notification notification) { // // keep the notification visible a little while after moving the // // mouse, or until clicked // notification.setDuration(2000); // notification.open(); // } // }
import com.vaadin.flow.server.ServiceInitEvent; import com.vaadin.flow.server.VaadinServiceInitListener; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.LoginScreen;
package com.github.mcollovati.vertxvaadin.flowdemo; /** * This class is used to listen to BeforeEnter event of all UIs in order to * check whether a user is signed in or not before allowing entering any page. * It is registered in a file named * com.vaadin.flow.server.VaadinServiceInitListener in META-INF/services. */ public class BookstoreInitListener implements VaadinServiceInitListener { @Override public void serviceInit(ServiceInitEvent initEvent) {
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/LoginScreen.java // @Route("Login") // @PageTitle("Login") // @StyleSheet("css/shared-styles.css") // public class LoginScreen extends FlexLayout { // // private TextField username; // private PasswordField password; // private Button login; // private Button forgotPassword; // private AccessControl accessControl; // // public LoginScreen() { // accessControl = AccessControlFactory.getInstance().createAccessControl(); // buildUI(); // username.focus(); // } // // private void buildUI() { // setSizeFull(); // setClassName("login-screen"); // // // login form, centered in the available part of the screen // Component loginForm = buildLoginForm(); // // // layout to center login form when there is sufficient screen space // FlexLayout centeringLayout = new FlexLayout(); // centeringLayout.setSizeFull(); // centeringLayout.setJustifyContentMode(JustifyContentMode.CENTER); // centeringLayout.setAlignItems(Alignment.CENTER); // centeringLayout.add(loginForm); // // // information text about logging in // Component loginInformation = buildLoginInformation(); // // add(loginInformation); // add(centeringLayout); // } // // private Component buildLoginForm() { // FormLayout loginForm = new FormLayout(); // // loginForm.setWidth("310px"); // // loginForm.addFormItem(username = new TextField(), "Username"); // username.setWidth("15em"); // username.setValue("admin"); // loginForm.add(new Html("<br/>")); // loginForm.addFormItem(password = new PasswordField(), "Password"); // password.setWidth("15em"); // // HorizontalLayout buttons = new HorizontalLayout(); // loginForm.add(new Html("<br/>")); // loginForm.add(buttons); // // buttons.add(login = new Button("Login")); // login.addClickListener(event -> login()); // loginForm.getElement().addEventListener("keypress", event -> login()).setFilter("event.key == 'Enter'"); // login.getElement().getThemeList().add("success primary"); // // buttons.add(forgotPassword = new Button("Forgot password?")); // forgotPassword.addClickListener(event -> showNotification(new Notification("Hint: try anything"))); // forgotPassword.getElement().getThemeList().add("tertiary"); // // return loginForm; // } // // private Component buildLoginInformation() { // VerticalLayout loginInformation = new VerticalLayout(); // loginInformation.setClassName("login-information"); // // H1 loginInfoHeader = new H1("Login Information"); // Span loginInfoText = new Span( // "Log in as \"admin\" to have full access. Log in with any other username to have read-only access. For all users, any password is fine."); // loginInformation.add(loginInfoHeader); // loginInformation.add(loginInfoText); // // return loginInformation; // } // // private void login() { // login.setEnabled(false); // try { // if (accessControl.signIn(username.getValue(), password.getValue())) { // getUI().get().navigate(""); // } else { // showNotification(new Notification("Login failed. " + // "Please check your username and password and try again.")); // username.focus(); // } // } finally { // login.setEnabled(true); // } // } // // private void showNotification(Notification notification) { // // keep the notification visible a little while after moving the // // mouse, or until clicked // notification.setDuration(2000); // notification.open(); // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/BookstoreInitListener.java import com.vaadin.flow.server.ServiceInitEvent; import com.vaadin.flow.server.VaadinServiceInitListener; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.LoginScreen; package com.github.mcollovati.vertxvaadin.flowdemo; /** * This class is used to listen to BeforeEnter event of all UIs in order to * check whether a user is signed in or not before allowing entering any page. * It is registered in a file named * com.vaadin.flow.server.VaadinServiceInitListener in META-INF/services. */ public class BookstoreInitListener implements VaadinServiceInitListener { @Override public void serviceInit(ServiceInitEvent initEvent) {
final AccessControl accessControl = AccessControlFactory.getInstance()
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/BookstoreInitListener.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/LoginScreen.java // @Route("Login") // @PageTitle("Login") // @StyleSheet("css/shared-styles.css") // public class LoginScreen extends FlexLayout { // // private TextField username; // private PasswordField password; // private Button login; // private Button forgotPassword; // private AccessControl accessControl; // // public LoginScreen() { // accessControl = AccessControlFactory.getInstance().createAccessControl(); // buildUI(); // username.focus(); // } // // private void buildUI() { // setSizeFull(); // setClassName("login-screen"); // // // login form, centered in the available part of the screen // Component loginForm = buildLoginForm(); // // // layout to center login form when there is sufficient screen space // FlexLayout centeringLayout = new FlexLayout(); // centeringLayout.setSizeFull(); // centeringLayout.setJustifyContentMode(JustifyContentMode.CENTER); // centeringLayout.setAlignItems(Alignment.CENTER); // centeringLayout.add(loginForm); // // // information text about logging in // Component loginInformation = buildLoginInformation(); // // add(loginInformation); // add(centeringLayout); // } // // private Component buildLoginForm() { // FormLayout loginForm = new FormLayout(); // // loginForm.setWidth("310px"); // // loginForm.addFormItem(username = new TextField(), "Username"); // username.setWidth("15em"); // username.setValue("admin"); // loginForm.add(new Html("<br/>")); // loginForm.addFormItem(password = new PasswordField(), "Password"); // password.setWidth("15em"); // // HorizontalLayout buttons = new HorizontalLayout(); // loginForm.add(new Html("<br/>")); // loginForm.add(buttons); // // buttons.add(login = new Button("Login")); // login.addClickListener(event -> login()); // loginForm.getElement().addEventListener("keypress", event -> login()).setFilter("event.key == 'Enter'"); // login.getElement().getThemeList().add("success primary"); // // buttons.add(forgotPassword = new Button("Forgot password?")); // forgotPassword.addClickListener(event -> showNotification(new Notification("Hint: try anything"))); // forgotPassword.getElement().getThemeList().add("tertiary"); // // return loginForm; // } // // private Component buildLoginInformation() { // VerticalLayout loginInformation = new VerticalLayout(); // loginInformation.setClassName("login-information"); // // H1 loginInfoHeader = new H1("Login Information"); // Span loginInfoText = new Span( // "Log in as \"admin\" to have full access. Log in with any other username to have read-only access. For all users, any password is fine."); // loginInformation.add(loginInfoHeader); // loginInformation.add(loginInfoText); // // return loginInformation; // } // // private void login() { // login.setEnabled(false); // try { // if (accessControl.signIn(username.getValue(), password.getValue())) { // getUI().get().navigate(""); // } else { // showNotification(new Notification("Login failed. " + // "Please check your username and password and try again.")); // username.focus(); // } // } finally { // login.setEnabled(true); // } // } // // private void showNotification(Notification notification) { // // keep the notification visible a little while after moving the // // mouse, or until clicked // notification.setDuration(2000); // notification.open(); // } // }
import com.vaadin.flow.server.ServiceInitEvent; import com.vaadin.flow.server.VaadinServiceInitListener; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.LoginScreen;
package com.github.mcollovati.vertxvaadin.flowdemo; /** * This class is used to listen to BeforeEnter event of all UIs in order to * check whether a user is signed in or not before allowing entering any page. * It is registered in a file named * com.vaadin.flow.server.VaadinServiceInitListener in META-INF/services. */ public class BookstoreInitListener implements VaadinServiceInitListener { @Override public void serviceInit(ServiceInitEvent initEvent) { final AccessControl accessControl = AccessControlFactory.getInstance() .createAccessControl(); initEvent.getSource().addUIInitListener(uiInitEvent -> { uiInitEvent.getUI().addBeforeEnterListener(enterEvent -> {
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControl.java // public interface AccessControl extends Serializable { // // String ADMIN_ROLE_NAME = "admin"; // String ADMIN_USERNAME = "admin"; // // public boolean signIn(String username, String password); // // public boolean isUserSignedIn(); // // public boolean isUserInRole(String role); // // public String getPrincipalName(); // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/AccessControlFactory.java // public class AccessControlFactory { // private static final AccessControlFactory INSTANCE = new AccessControlFactory(); // private final AccessControl accessControl = new BasicAccessControl(); // // private AccessControlFactory() { // } // // public static AccessControlFactory getInstance() { // return INSTANCE; // } // // public AccessControl createAccessControl() { // return accessControl; // } // } // // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/authentication/LoginScreen.java // @Route("Login") // @PageTitle("Login") // @StyleSheet("css/shared-styles.css") // public class LoginScreen extends FlexLayout { // // private TextField username; // private PasswordField password; // private Button login; // private Button forgotPassword; // private AccessControl accessControl; // // public LoginScreen() { // accessControl = AccessControlFactory.getInstance().createAccessControl(); // buildUI(); // username.focus(); // } // // private void buildUI() { // setSizeFull(); // setClassName("login-screen"); // // // login form, centered in the available part of the screen // Component loginForm = buildLoginForm(); // // // layout to center login form when there is sufficient screen space // FlexLayout centeringLayout = new FlexLayout(); // centeringLayout.setSizeFull(); // centeringLayout.setJustifyContentMode(JustifyContentMode.CENTER); // centeringLayout.setAlignItems(Alignment.CENTER); // centeringLayout.add(loginForm); // // // information text about logging in // Component loginInformation = buildLoginInformation(); // // add(loginInformation); // add(centeringLayout); // } // // private Component buildLoginForm() { // FormLayout loginForm = new FormLayout(); // // loginForm.setWidth("310px"); // // loginForm.addFormItem(username = new TextField(), "Username"); // username.setWidth("15em"); // username.setValue("admin"); // loginForm.add(new Html("<br/>")); // loginForm.addFormItem(password = new PasswordField(), "Password"); // password.setWidth("15em"); // // HorizontalLayout buttons = new HorizontalLayout(); // loginForm.add(new Html("<br/>")); // loginForm.add(buttons); // // buttons.add(login = new Button("Login")); // login.addClickListener(event -> login()); // loginForm.getElement().addEventListener("keypress", event -> login()).setFilter("event.key == 'Enter'"); // login.getElement().getThemeList().add("success primary"); // // buttons.add(forgotPassword = new Button("Forgot password?")); // forgotPassword.addClickListener(event -> showNotification(new Notification("Hint: try anything"))); // forgotPassword.getElement().getThemeList().add("tertiary"); // // return loginForm; // } // // private Component buildLoginInformation() { // VerticalLayout loginInformation = new VerticalLayout(); // loginInformation.setClassName("login-information"); // // H1 loginInfoHeader = new H1("Login Information"); // Span loginInfoText = new Span( // "Log in as \"admin\" to have full access. Log in with any other username to have read-only access. For all users, any password is fine."); // loginInformation.add(loginInfoHeader); // loginInformation.add(loginInfoText); // // return loginInformation; // } // // private void login() { // login.setEnabled(false); // try { // if (accessControl.signIn(username.getValue(), password.getValue())) { // getUI().get().navigate(""); // } else { // showNotification(new Notification("Login failed. " + // "Please check your username and password and try again.")); // username.focus(); // } // } finally { // login.setEnabled(true); // } // } // // private void showNotification(Notification notification) { // // keep the notification visible a little while after moving the // // mouse, or until clicked // notification.setDuration(2000); // notification.open(); // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/BookstoreInitListener.java import com.vaadin.flow.server.ServiceInitEvent; import com.vaadin.flow.server.VaadinServiceInitListener; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControl; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.AccessControlFactory; import com.github.mcollovati.vertxvaadin.flowdemo.authentication.LoginScreen; package com.github.mcollovati.vertxvaadin.flowdemo; /** * This class is used to listen to BeforeEnter event of all UIs in order to * check whether a user is signed in or not before allowing entering any page. * It is registered in a file named * com.vaadin.flow.server.VaadinServiceInitListener in META-INF/services. */ public class BookstoreInitListener implements VaadinServiceInitListener { @Override public void serviceInit(ServiceInitEvent initEvent) { final AccessControl accessControl = AccessControlFactory.getInstance() .createAccessControl(); initEvent.getSource().addUIInitListener(uiInitEvent -> { uiInitEvent.getUI().addBeforeEnterListener(enterEvent -> {
if (!accessControl.isUserSignedIn() && !LoginScreen.class
mcollovati/vaadin-vertx-samples
example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataGenerator.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product;
package com.github.mcollovati.vaadin.exampleapp.samples.backend.mock; public class MockDataGenerator { private static int nextCategoryId = 1; private static int nextProductId = 1; private static final Random random = new Random(1); private static final String categoryNames[] = new String[] { "Children's books", "Best sellers", "Romance", "Mystery", "Thriller", "Sci-fi", "Non-fiction", "Cookbooks" }; private static String[] word1 = new String[] { "The art of", "Mastering", "The secrets of", "Avoiding", "For fun and profit: ", "How to fail at", "10 important facts about", "The ultimate guide to", "Book of", "Surviving", "Encyclopedia of", "Very much", "Learning the basics of", "The cheap way to", "Being awesome at", "The life changer:", "The Vaadin way:", "Becoming one with", "Beginners guide to", "The complete visual guide to", "The mother of all references:" }; private static String[] word2 = new String[] { "gardening", "living a healthy life", "designing tree houses", "home security", "intergalaxy travel", "meditation", "ice hockey", "children's education", "computer programming", "Vaadin TreeTable", "winter bathing", "playing the cello", "dummies", "rubber bands", "feeling down", "debugging", "running barefoot", "speaking to a big audience", "creating software", "giant needles", "elephants", "keeping your wife happy" };
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataGenerator.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; package com.github.mcollovati.vaadin.exampleapp.samples.backend.mock; public class MockDataGenerator { private static int nextCategoryId = 1; private static int nextProductId = 1; private static final Random random = new Random(1); private static final String categoryNames[] = new String[] { "Children's books", "Best sellers", "Romance", "Mystery", "Thriller", "Sci-fi", "Non-fiction", "Cookbooks" }; private static String[] word1 = new String[] { "The art of", "Mastering", "The secrets of", "Avoiding", "For fun and profit: ", "How to fail at", "10 important facts about", "The ultimate guide to", "Book of", "Surviving", "Encyclopedia of", "Very much", "Learning the basics of", "The cheap way to", "Being awesome at", "The life changer:", "The Vaadin way:", "Becoming one with", "Beginners guide to", "The complete visual guide to", "The mother of all references:" }; private static String[] word2 = new String[] { "gardening", "living a healthy life", "designing tree houses", "home security", "intergalaxy travel", "meditation", "ice hockey", "children's education", "computer programming", "Vaadin TreeTable", "winter bathing", "playing the cello", "dummies", "rubber bands", "feeling down", "debugging", "running barefoot", "speaking to a big audience", "creating software", "giant needles", "elephants", "keeping your wife happy" };
static List<Category> createCategories() {
mcollovati/vaadin-vertx-samples
example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataGenerator.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product;
"Thriller", "Sci-fi", "Non-fiction", "Cookbooks" }; private static String[] word1 = new String[] { "The art of", "Mastering", "The secrets of", "Avoiding", "For fun and profit: ", "How to fail at", "10 important facts about", "The ultimate guide to", "Book of", "Surviving", "Encyclopedia of", "Very much", "Learning the basics of", "The cheap way to", "Being awesome at", "The life changer:", "The Vaadin way:", "Becoming one with", "Beginners guide to", "The complete visual guide to", "The mother of all references:" }; private static String[] word2 = new String[] { "gardening", "living a healthy life", "designing tree houses", "home security", "intergalaxy travel", "meditation", "ice hockey", "children's education", "computer programming", "Vaadin TreeTable", "winter bathing", "playing the cello", "dummies", "rubber bands", "feeling down", "debugging", "running barefoot", "speaking to a big audience", "creating software", "giant needles", "elephants", "keeping your wife happy" }; static List<Category> createCategories() { List<Category> categories = new ArrayList<Category>(); for (String name : categoryNames) { Category c = createCategory(name); categories.add(c); } return categories; }
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataGenerator.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; "Thriller", "Sci-fi", "Non-fiction", "Cookbooks" }; private static String[] word1 = new String[] { "The art of", "Mastering", "The secrets of", "Avoiding", "For fun and profit: ", "How to fail at", "10 important facts about", "The ultimate guide to", "Book of", "Surviving", "Encyclopedia of", "Very much", "Learning the basics of", "The cheap way to", "Being awesome at", "The life changer:", "The Vaadin way:", "Becoming one with", "Beginners guide to", "The complete visual guide to", "The mother of all references:" }; private static String[] word2 = new String[] { "gardening", "living a healthy life", "designing tree houses", "home security", "intergalaxy travel", "meditation", "ice hockey", "children's education", "computer programming", "Vaadin TreeTable", "winter bathing", "playing the cello", "dummies", "rubber bands", "feeling down", "debugging", "running barefoot", "speaking to a big audience", "creating software", "giant needles", "elephants", "keeping your wife happy" }; static List<Category> createCategories() { List<Category> categories = new ArrayList<Category>(); for (String name : categoryNames) { Category c = createCategory(name); categories.add(c); } return categories; }
static List<Product> createProducts(List<Category> categories) {
mcollovati/vaadin-vertx-samples
example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataGenerator.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product;
Category c = createCategory(name); categories.add(c); } return categories; } static List<Product> createProducts(List<Category> categories) { List<Product> products = new ArrayList<Product>(); for (int i = 0; i < 100; i++) { Product p = createProduct(categories); products.add(p); } return products; } private static Category createCategory(String name) { Category c = new Category(); c.setId(nextCategoryId++); c.setName(name); return c; } private static Product createProduct(List<Category> categories) { Product p = new Product(); p.setId(nextProductId++); p.setProductName(generateName()); p.setPrice(new BigDecimal((random.nextInt(250) + 50) / 10.0));
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataGenerator.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; Category c = createCategory(name); categories.add(c); } return categories; } static List<Product> createProducts(List<Category> categories) { List<Product> products = new ArrayList<Product>(); for (int i = 0; i < 100; i++) { Product p = createProduct(categories); products.add(p); } return products; } private static Category createCategory(String name) { Category c = new Category(); c.setId(nextCategoryId++); c.setName(name); return c; } private static Product createProduct(List<Category> categories) { Product p = new Product(); p.setId(nextProductId++); p.setProductName(generateName()); p.setPrice(new BigDecimal((random.nextInt(250) + 50) / 10.0));
p.setAvailability(Availability.values()[random.nextInt(Availability
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductGrid.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.text.DecimalFormat; import java.util.Comparator; import java.util.stream.Collectors; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.ui.Grid; import com.vaadin.ui.renderers.HtmlRenderer; import com.vaadin.ui.renderers.NumberRenderer;
package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * Grid of products, handling the visual presentation and filtering of a set of * items. This version uses an in-memory data source that is suitable for small * data sets. */ public class ProductGrid extends Grid<Product> { public ProductGrid() { setSizeFull(); addColumn(Product::getId, new NumberRenderer()).setCaption("Id"); addColumn(Product::getProductName).setCaption("Product Name"); // Format and add " €" to price final DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); decimalFormat.setMinimumFractionDigits(2); addColumn(product -> decimalFormat.format(product.getPrice()) + " €") .setCaption("Price").setComparator((p1, p2) -> { return p1.getPrice().compareTo(p2.getPrice()); }).setStyleGenerator(product -> "align-right"); // Add an traffic light icon in front of availability addColumn(this::htmlFormatAvailability, new HtmlRenderer())
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductGrid.java import java.text.DecimalFormat; import java.util.Comparator; import java.util.stream.Collectors; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.ui.Grid; import com.vaadin.ui.renderers.HtmlRenderer; import com.vaadin.ui.renderers.NumberRenderer; package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * Grid of products, handling the visual presentation and filtering of a set of * items. This version uses an in-memory data source that is suitable for small * data sets. */ public class ProductGrid extends Grid<Product> { public ProductGrid() { setSizeFull(); addColumn(Product::getId, new NumberRenderer()).setCaption("Id"); addColumn(Product::getProductName).setCaption("Product Name"); // Format and add " €" to price final DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); decimalFormat.setMinimumFractionDigits(2); addColumn(product -> decimalFormat.format(product.getPrice()) + " €") .setCaption("Price").setComparator((p1, p2) -> { return p1.getPrice().compareTo(p2.getPrice()); }).setStyleGenerator(product -> "align-right"); // Add an traffic light icon in front of availability addColumn(this::htmlFormatAvailability, new HtmlRenderer())
.setCaption("Availability").setComparator((p1, p2) -> {
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductGrid.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.text.DecimalFormat; import java.util.Comparator; import java.util.stream.Collectors; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.ui.Grid; import com.vaadin.ui.renderers.HtmlRenderer; import com.vaadin.ui.renderers.NumberRenderer;
package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * Grid of products, handling the visual presentation and filtering of a set of * items. This version uses an in-memory data source that is suitable for small * data sets. */ public class ProductGrid extends Grid<Product> { public ProductGrid() { setSizeFull(); addColumn(Product::getId, new NumberRenderer()).setCaption("Id"); addColumn(Product::getProductName).setCaption("Product Name"); // Format and add " €" to price final DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); decimalFormat.setMinimumFractionDigits(2); addColumn(product -> decimalFormat.format(product.getPrice()) + " €") .setCaption("Price").setComparator((p1, p2) -> { return p1.getPrice().compareTo(p2.getPrice()); }).setStyleGenerator(product -> "align-right"); // Add an traffic light icon in front of availability addColumn(this::htmlFormatAvailability, new HtmlRenderer()) .setCaption("Availability").setComparator((p1, p2) -> { return p1.getAvailability().toString() .compareTo(p2.getAvailability().toString()); }); // Show empty stock as "-" addColumn(product -> { if (product.getStockCount() == 0) { return "-"; } return Integer.toString(product.getStockCount()); }).setCaption("Stock Count").setComparator((p1, p2) -> { return Integer.compare(p1.getStockCount(), p2.getStockCount()); }).setStyleGenerator(product -> "align-right"); // Show all categories the product is in, separated by commas
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/ProductGrid.java import java.text.DecimalFormat; import java.util.Comparator; import java.util.stream.Collectors; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Availability; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.ui.Grid; import com.vaadin.ui.renderers.HtmlRenderer; import com.vaadin.ui.renderers.NumberRenderer; package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * Grid of products, handling the visual presentation and filtering of a set of * items. This version uses an in-memory data source that is suitable for small * data sets. */ public class ProductGrid extends Grid<Product> { public ProductGrid() { setSizeFull(); addColumn(Product::getId, new NumberRenderer()).setCaption("Id"); addColumn(Product::getProductName).setCaption("Product Name"); // Format and add " €" to price final DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumFractionDigits(2); decimalFormat.setMinimumFractionDigits(2); addColumn(product -> decimalFormat.format(product.getPrice()) + " €") .setCaption("Price").setComparator((p1, p2) -> { return p1.getPrice().compareTo(p2.getPrice()); }).setStyleGenerator(product -> "align-right"); // Add an traffic light icon in front of availability addColumn(this::htmlFormatAvailability, new HtmlRenderer()) .setCaption("Availability").setComparator((p1, p2) -> { return p1.getAvailability().toString() .compareTo(p2.getAvailability().toString()); }); // Show empty stock as "-" addColumn(product -> { if (product.getStockCount() == 0) { return "-"; } return Integer.toString(product.getStockCount()); }).setCaption("Stock Count").setComparator((p1, p2) -> { return Integer.compare(p1.getStockCount(), p2.getStockCount()); }).setStyleGenerator(product -> "align-right"); // Show all categories the product is in, separated by commas
addColumn(this::formatCategories).setCaption("Category").setSortable(false);
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudView.java
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/ResetButtonForTextField.java // public class ResetButtonForTextField extends AbstractExtension { // // public static void extend(TextField field) { // new ResetButtonForTextField().extend((AbstractClientConnector) field); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import com.github.mcollovati.vaadin.exampleapp.samples.ResetButtonForTextField; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.CssLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme;
package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * A view for performing create-read-update-delete operations on products. * * See also {@link SampleCrudLogic} for fetching the data, the actual CRUD * operations and controlling the view based on events from outside. */ public class SampleCrudView extends CssLayout implements View { public static final String VIEW_NAME = "Inventory"; private ProductGrid grid; private ProductForm form; private TextField filter; private SampleCrudLogic viewLogic = new SampleCrudLogic(this); private Button newProduct; private ProductDataProvider dataProvider = new ProductDataProvider(); public SampleCrudView() { setSizeFull(); addStyleName("crud-view"); HorizontalLayout topLayout = createTopBar(); grid = new ProductGrid(); grid.setDataProvider(dataProvider); grid.asSingleSelect().addValueChangeListener( event -> viewLogic.rowSelected(event.getValue())); form = new ProductForm(viewLogic);
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/ResetButtonForTextField.java // public class ResetButtonForTextField extends AbstractExtension { // // public static void extend(TextField field) { // new ResetButtonForTextField().extend((AbstractClientConnector) field); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudView.java import com.github.mcollovati.vaadin.exampleapp.samples.ResetButtonForTextField; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.CssLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; package com.github.mcollovati.vaadin.exampleapp.samples.crud; /** * A view for performing create-read-update-delete operations on products. * * See also {@link SampleCrudLogic} for fetching the data, the actual CRUD * operations and controlling the view based on events from outside. */ public class SampleCrudView extends CssLayout implements View { public static final String VIEW_NAME = "Inventory"; private ProductGrid grid; private ProductForm form; private TextField filter; private SampleCrudLogic viewLogic = new SampleCrudLogic(this); private Button newProduct; private ProductDataProvider dataProvider = new ProductDataProvider(); public SampleCrudView() { setSizeFull(); addStyleName("crud-view"); HorizontalLayout topLayout = createTopBar(); grid = new ProductGrid(); grid.setDataProvider(dataProvider); grid.asSingleSelect().addValueChangeListener( event -> viewLogic.rowSelected(event.getValue())); form = new ProductForm(viewLogic);
form.setCategories(DataService.get().getAllCategories());
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudView.java
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/ResetButtonForTextField.java // public class ResetButtonForTextField extends AbstractExtension { // // public static void extend(TextField field) { // new ResetButtonForTextField().extend((AbstractClientConnector) field); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import com.github.mcollovati.vaadin.exampleapp.samples.ResetButtonForTextField; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.CssLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme;
public SampleCrudView() { setSizeFull(); addStyleName("crud-view"); HorizontalLayout topLayout = createTopBar(); grid = new ProductGrid(); grid.setDataProvider(dataProvider); grid.asSingleSelect().addValueChangeListener( event -> viewLogic.rowSelected(event.getValue())); form = new ProductForm(viewLogic); form.setCategories(DataService.get().getAllCategories()); VerticalLayout barAndGridLayout = new VerticalLayout(); barAndGridLayout.addComponent(topLayout); barAndGridLayout.addComponent(grid); barAndGridLayout.setSizeFull(); barAndGridLayout.setExpandRatio(grid, 1); barAndGridLayout.setStyleName("crud-main-layout"); addComponent(barAndGridLayout); addComponent(form); viewLogic.init(); } public HorizontalLayout createTopBar() { filter = new TextField(); filter.setStyleName("filter-textfield"); filter.setPlaceholder("Filter name, availability or category");
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/ResetButtonForTextField.java // public class ResetButtonForTextField extends AbstractExtension { // // public static void extend(TextField field) { // new ResetButtonForTextField().extend((AbstractClientConnector) field); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudView.java import com.github.mcollovati.vaadin.exampleapp.samples.ResetButtonForTextField; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.CssLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; public SampleCrudView() { setSizeFull(); addStyleName("crud-view"); HorizontalLayout topLayout = createTopBar(); grid = new ProductGrid(); grid.setDataProvider(dataProvider); grid.asSingleSelect().addValueChangeListener( event -> viewLogic.rowSelected(event.getValue())); form = new ProductForm(viewLogic); form.setCategories(DataService.get().getAllCategories()); VerticalLayout barAndGridLayout = new VerticalLayout(); barAndGridLayout.addComponent(topLayout); barAndGridLayout.addComponent(grid); barAndGridLayout.setSizeFull(); barAndGridLayout.setExpandRatio(grid, 1); barAndGridLayout.setStyleName("crud-main-layout"); addComponent(barAndGridLayout); addComponent(form); viewLogic.init(); } public HorizontalLayout createTopBar() { filter = new TextField(); filter.setStyleName("filter-textfield"); filter.setPlaceholder("Filter name, availability or category");
ResetButtonForTextField.extend(filter);
mcollovati/vaadin-vertx-samples
example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudView.java
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/ResetButtonForTextField.java // public class ResetButtonForTextField extends AbstractExtension { // // public static void extend(TextField field) { // new ResetButtonForTextField().extend((AbstractClientConnector) field); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import com.github.mcollovati.vaadin.exampleapp.samples.ResetButtonForTextField; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.CssLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme;
topLayout.setWidth("100%"); topLayout.addComponent(filter); topLayout.addComponent(newProduct); topLayout.setComponentAlignment(filter, Alignment.MIDDLE_LEFT); topLayout.setExpandRatio(filter, 1); topLayout.setStyleName("top-bar"); return topLayout; } @Override public void enter(ViewChangeEvent event) { viewLogic.enter(event.getParameters()); } public void showError(String msg) { Notification.show(msg, Type.ERROR_MESSAGE); } public void showSaveNotification(String msg) { Notification.show(msg, Type.TRAY_NOTIFICATION); } public void setNewProductEnabled(boolean enabled) { newProduct.setEnabled(enabled); } public void clearSelection() { grid.getSelectionModel().deselectAll(); }
// Path: example-app/example-app-widgetset/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/ResetButtonForTextField.java // public class ResetButtonForTextField extends AbstractExtension { // // public static void extend(TextField field) { // new ResetButtonForTextField().extend((AbstractClientConnector) field); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-ui/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/crud/SampleCrudView.java import com.github.mcollovati.vaadin.exampleapp.samples.ResetButtonForTextField; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.vaadin.icons.VaadinIcons; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.CssLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; topLayout.setWidth("100%"); topLayout.addComponent(filter); topLayout.addComponent(newProduct); topLayout.setComponentAlignment(filter, Alignment.MIDDLE_LEFT); topLayout.setExpandRatio(filter, 1); topLayout.setStyleName("top-bar"); return topLayout; } @Override public void enter(ViewChangeEvent event) { viewLogic.enter(event.getParameters()); } public void showError(String msg) { Notification.show(msg, Type.ERROR_MESSAGE); } public void showSaveNotification(String msg) { Notification.show(msg, Type.TRAY_NOTIFICATION); } public void setNewProductEnabled(boolean enabled) { newProduct.setEnabled(enabled); } public void clearSelection() { grid.getSelectionModel().deselectAll(); }
public void selectRow(Product row) {
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataGenerator.java
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Availability; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product;
package com.github.mcollovati.vertxvaadin.flowdemo.backend.mock; public class MockDataGenerator { private static int nextCategoryId = 1; private static int nextProductId = 1; private static final Random random = new Random(1); private static final String categoryNames[] = new String[] { "Children's books", "Best sellers", "Romance", "Mystery", "Thriller", "Sci-fi", "Non-fiction", "Cookbooks" }; private static String[] word1 = new String[] { "The art of", "Mastering", "The secrets of", "Avoiding", "For fun and profit: ", "How to fail at", "10 important facts about", "The ultimate guide to", "Book of", "Surviving", "Encyclopedia of", "Very much", "Learning the basics of", "The cheap way to", "Being awesome at", "The life changer:", "The Vaadin way:", "Becoming one with", "Beginners guide to", "The complete visual guide to", "The mother of all references:" }; private static String[] word2 = new String[] { "gardening", "living a healthy life", "designing tree houses", "home security", "intergalaxy travel", "meditation", "ice hockey", "children's education", "computer programming", "Vaadin TreeTable", "winter bathing", "playing the cello", "dummies", "rubber bands", "feeling down", "debugging", "running barefoot", "speaking to a big audience", "creating software", "giant needles", "elephants", "keeping your wife happy" };
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataGenerator.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Availability; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; package com.github.mcollovati.vertxvaadin.flowdemo.backend.mock; public class MockDataGenerator { private static int nextCategoryId = 1; private static int nextProductId = 1; private static final Random random = new Random(1); private static final String categoryNames[] = new String[] { "Children's books", "Best sellers", "Romance", "Mystery", "Thriller", "Sci-fi", "Non-fiction", "Cookbooks" }; private static String[] word1 = new String[] { "The art of", "Mastering", "The secrets of", "Avoiding", "For fun and profit: ", "How to fail at", "10 important facts about", "The ultimate guide to", "Book of", "Surviving", "Encyclopedia of", "Very much", "Learning the basics of", "The cheap way to", "Being awesome at", "The life changer:", "The Vaadin way:", "Becoming one with", "Beginners guide to", "The complete visual guide to", "The mother of all references:" }; private static String[] word2 = new String[] { "gardening", "living a healthy life", "designing tree houses", "home security", "intergalaxy travel", "meditation", "ice hockey", "children's education", "computer programming", "Vaadin TreeTable", "winter bathing", "playing the cello", "dummies", "rubber bands", "feeling down", "debugging", "running barefoot", "speaking to a big audience", "creating software", "giant needles", "elephants", "keeping your wife happy" };
static List<Category> createCategories() {
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataGenerator.java
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Availability; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product;
"Thriller", "Sci-fi", "Non-fiction", "Cookbooks" }; private static String[] word1 = new String[] { "The art of", "Mastering", "The secrets of", "Avoiding", "For fun and profit: ", "How to fail at", "10 important facts about", "The ultimate guide to", "Book of", "Surviving", "Encyclopedia of", "Very much", "Learning the basics of", "The cheap way to", "Being awesome at", "The life changer:", "The Vaadin way:", "Becoming one with", "Beginners guide to", "The complete visual guide to", "The mother of all references:" }; private static String[] word2 = new String[] { "gardening", "living a healthy life", "designing tree houses", "home security", "intergalaxy travel", "meditation", "ice hockey", "children's education", "computer programming", "Vaadin TreeTable", "winter bathing", "playing the cello", "dummies", "rubber bands", "feeling down", "debugging", "running barefoot", "speaking to a big audience", "creating software", "giant needles", "elephants", "keeping your wife happy" }; static List<Category> createCategories() { List<Category> categories = new ArrayList<Category>(); for (String name : categoryNames) { Category c = createCategory(name); categories.add(c); } return categories; }
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataGenerator.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Availability; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; "Thriller", "Sci-fi", "Non-fiction", "Cookbooks" }; private static String[] word1 = new String[] { "The art of", "Mastering", "The secrets of", "Avoiding", "For fun and profit: ", "How to fail at", "10 important facts about", "The ultimate guide to", "Book of", "Surviving", "Encyclopedia of", "Very much", "Learning the basics of", "The cheap way to", "Being awesome at", "The life changer:", "The Vaadin way:", "Becoming one with", "Beginners guide to", "The complete visual guide to", "The mother of all references:" }; private static String[] word2 = new String[] { "gardening", "living a healthy life", "designing tree houses", "home security", "intergalaxy travel", "meditation", "ice hockey", "children's education", "computer programming", "Vaadin TreeTable", "winter bathing", "playing the cello", "dummies", "rubber bands", "feeling down", "debugging", "running barefoot", "speaking to a big audience", "creating software", "giant needles", "elephants", "keeping your wife happy" }; static List<Category> createCategories() { List<Category> categories = new ArrayList<Category>(); for (String name : categoryNames) { Category c = createCategory(name); categories.add(c); } return categories; }
static List<Product> createProducts(List<Category> categories) {
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataGenerator.java
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Availability; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product;
Category c = createCategory(name); categories.add(c); } return categories; } static List<Product> createProducts(List<Category> categories) { List<Product> products = new ArrayList<Product>(); for (int i = 0; i < 100; i++) { Product p = createProduct(categories); products.add(p); } return products; } private static Category createCategory(String name) { Category c = new Category(); c.setId(nextCategoryId++); c.setName(name); return c; } private static Product createProduct(List<Category> categories) { Product p = new Product(); p.setId(nextProductId++); p.setProductName(generateName()); p.setPrice(new BigDecimal((random.nextInt(250) + 50) / 10.0));
// Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Availability.java // public enum Availability { // COMING("Coming"), AVAILABLE("Available"), DISCONTINUED("Discontinued"); // // private final String name; // // private Availability(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/mock/MockDataGenerator.java import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Availability; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Category; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; Category c = createCategory(name); categories.add(c); } return categories; } static List<Product> createProducts(List<Category> categories) { List<Product> products = new ArrayList<Product>(); for (int i = 0; i < 100; i++) { Product p = createProduct(categories); products.add(p); } return products; } private static Category createCategory(String name) { Category c = new Category(); c.setId(nextCategoryId++); c.setName(name); return c; } private static Product createProduct(List<Category> categories) { Product p = new Product(); p.setId(nextProductId++); p.setProductName(generateName()); p.setPrice(new BigDecimal((random.nextInt(250) + 50) / 10.0));
p.setAvailability(Availability.values()[random.nextInt(Availability
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudView.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/MainLayout.java // @StyleSheet("css/shared-styles.css") // @Theme(value = Lumo.class, variant = Lumo.DARK) // public class MainLayout extends FlexLayout implements RouterLayout { // private Menu menu; // // public MainLayout() { // setSizeFull(); // setClassName("main-layout"); // // menu = new Menu(); // menu.addView(SampleCrudView.class, SampleCrudView.VIEW_NAME, // VaadinIcon.EDIT.create()); // menu.addView(AboutView.class, AboutView.VIEW_NAME, // VaadinIcon.INFO_CIRCLE.create()); // // add(menu); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.router.BeforeEvent; import com.vaadin.flow.router.HasUrlParameter; import com.vaadin.flow.router.OptionalParameter; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteAlias; import com.github.mcollovati.vertxvaadin.flowdemo.MainLayout; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product;
package com.github.mcollovati.vertxvaadin.flowdemo.crud; /** * A view for performing create-read-update-delete operations on products. * * See also {@link SampleCrudLogic} for fetching the data, the actual CRUD * operations and controlling the view based on events from outside. */ @Route(value = "Inventory", layout = MainLayout.class) @RouteAlias(value = "", layout = MainLayout.class) public class SampleCrudView extends HorizontalLayout implements HasUrlParameter<String> { public static final String VIEW_NAME = "Inventory"; private ProductGrid grid; private ProductForm form; private TextField filter; private SampleCrudLogic viewLogic = new SampleCrudLogic(this); private Button newProduct; private ProductDataProvider dataProvider = new ProductDataProvider(); public SampleCrudView() { setSizeFull(); HorizontalLayout topLayout = createTopBar(); grid = new ProductGrid(); grid.setDataProvider(dataProvider); grid.asSingleSelect().addValueChangeListener( event -> viewLogic.rowSelected(event.getValue())); form = new ProductForm(viewLogic);
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/MainLayout.java // @StyleSheet("css/shared-styles.css") // @Theme(value = Lumo.class, variant = Lumo.DARK) // public class MainLayout extends FlexLayout implements RouterLayout { // private Menu menu; // // public MainLayout() { // setSizeFull(); // setClassName("main-layout"); // // menu = new Menu(); // menu.addView(SampleCrudView.class, SampleCrudView.VIEW_NAME, // VaadinIcon.EDIT.create()); // menu.addView(AboutView.class, AboutView.VIEW_NAME, // VaadinIcon.INFO_CIRCLE.create()); // // add(menu); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudView.java import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.router.BeforeEvent; import com.vaadin.flow.router.HasUrlParameter; import com.vaadin.flow.router.OptionalParameter; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteAlias; import com.github.mcollovati.vertxvaadin.flowdemo.MainLayout; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; package com.github.mcollovati.vertxvaadin.flowdemo.crud; /** * A view for performing create-read-update-delete operations on products. * * See also {@link SampleCrudLogic} for fetching the data, the actual CRUD * operations and controlling the view based on events from outside. */ @Route(value = "Inventory", layout = MainLayout.class) @RouteAlias(value = "", layout = MainLayout.class) public class SampleCrudView extends HorizontalLayout implements HasUrlParameter<String> { public static final String VIEW_NAME = "Inventory"; private ProductGrid grid; private ProductForm form; private TextField filter; private SampleCrudLogic viewLogic = new SampleCrudLogic(this); private Button newProduct; private ProductDataProvider dataProvider = new ProductDataProvider(); public SampleCrudView() { setSizeFull(); HorizontalLayout topLayout = createTopBar(); grid = new ProductGrid(); grid.setDataProvider(dataProvider); grid.asSingleSelect().addValueChangeListener( event -> viewLogic.rowSelected(event.getValue())); form = new ProductForm(viewLogic);
form.setCategories(DataService.get().getAllCategories());
mcollovati/vaadin-vertx-samples
flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudView.java
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/MainLayout.java // @StyleSheet("css/shared-styles.css") // @Theme(value = Lumo.class, variant = Lumo.DARK) // public class MainLayout extends FlexLayout implements RouterLayout { // private Menu menu; // // public MainLayout() { // setSizeFull(); // setClassName("main-layout"); // // menu = new Menu(); // menu.addView(SampleCrudView.class, SampleCrudView.VIEW_NAME, // VaadinIcon.EDIT.create()); // menu.addView(AboutView.class, AboutView.VIEW_NAME, // VaadinIcon.INFO_CIRCLE.create()); // // add(menu); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // }
import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.router.BeforeEvent; import com.vaadin.flow.router.HasUrlParameter; import com.vaadin.flow.router.OptionalParameter; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteAlias; import com.github.mcollovati.vertxvaadin.flowdemo.MainLayout; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product;
newProduct = new Button("New product"); newProduct.getElement().getThemeList().add("primary"); newProduct.setIcon(VaadinIcon.PLUS_CIRCLE.create()); newProduct.addClickListener(click -> viewLogic.newProduct()); HorizontalLayout topLayout = new HorizontalLayout(); topLayout.setWidth("100%"); topLayout.add(filter); topLayout.add(newProduct); topLayout.setVerticalComponentAlignment(Alignment.START, filter); topLayout.expand(filter); return topLayout; } public void showError(String msg) { Notification.show(msg); } public void showSaveNotification(String msg) { Notification.show(msg); } public void setNewProductEnabled(boolean enabled) { newProduct.setEnabled(enabled); } public void clearSelection() { grid.getSelectionModel().deselectAll(); }
// Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/MainLayout.java // @StyleSheet("css/shared-styles.css") // @Theme(value = Lumo.class, variant = Lumo.DARK) // public class MainLayout extends FlexLayout implements RouterLayout { // private Menu menu; // // public MainLayout() { // setSizeFull(); // setClassName("main-layout"); // // menu = new Menu(); // menu.addView(SampleCrudView.class, SampleCrudView.VIEW_NAME, // VaadinIcon.EDIT.create()); // menu.addView(AboutView.class, AboutView.VIEW_NAME, // VaadinIcon.INFO_CIRCLE.create()); // // add(menu); // } // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: flow-bookstore/bookstore-backend/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // private String image; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // public boolean isNewProduct() { // return getId() == -1; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // Path: flow-bookstore/bookstore-ui/src/main/java/com/github/mcollovati/vertxvaadin/flowdemo/crud/SampleCrudView.java import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.router.BeforeEvent; import com.vaadin.flow.router.HasUrlParameter; import com.vaadin.flow.router.OptionalParameter; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteAlias; import com.github.mcollovati.vertxvaadin.flowdemo.MainLayout; import com.github.mcollovati.vertxvaadin.flowdemo.backend.DataService; import com.github.mcollovati.vertxvaadin.flowdemo.backend.data.Product; newProduct = new Button("New product"); newProduct.getElement().getThemeList().add("primary"); newProduct.setIcon(VaadinIcon.PLUS_CIRCLE.create()); newProduct.addClickListener(click -> viewLogic.newProduct()); HorizontalLayout topLayout = new HorizontalLayout(); topLayout.setWidth("100%"); topLayout.add(filter); topLayout.add(newProduct); topLayout.setVerticalComponentAlignment(Alignment.START, filter); topLayout.expand(filter); return topLayout; } public void showError(String msg) { Notification.show(msg); } public void showSaveNotification(String msg) { Notification.show(msg); } public void setNewProductEnabled(boolean enabled) { newProduct.setEnabled(enabled); } public void clearSelection() { grid.getSelectionModel().deselectAll(); }
public void selectRow(Product row) {
mcollovati/vaadin-vertx-samples
example-app/example-app-backend/src/test/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataServiceTest.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // }
import org.junit.Before; import org.junit.Test; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.github.mcollovati.vaadin.exampleapp.samples.backend.mock.MockDataService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
package com.github.mcollovati.vaadin.exampleapp.samples.backend; /** * Simple unit test for the back-end data service. */ public class DataServiceTest { private DataService service; @Before public void setUp() throws Exception {
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // } // Path: example-app/example-app-backend/src/test/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataServiceTest.java import org.junit.Before; import org.junit.Test; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.github.mcollovati.vaadin.exampleapp.samples.backend.mock.MockDataService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; package com.github.mcollovati.vaadin.exampleapp.samples.backend; /** * Simple unit test for the back-end data service. */ public class DataServiceTest { private DataService service; @Before public void setUp() throws Exception {
service = MockDataService.getInstance();
mcollovati/vaadin-vertx-samples
example-app/example-app-backend/src/test/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataServiceTest.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // }
import org.junit.Before; import org.junit.Test; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.github.mcollovati.vaadin.exampleapp.samples.backend.mock.MockDataService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
package com.github.mcollovati.vaadin.exampleapp.samples.backend; /** * Simple unit test for the back-end data service. */ public class DataServiceTest { private DataService service; @Before public void setUp() throws Exception { service = MockDataService.getInstance(); } @Test public void testDataServiceCanFetchProducts() throws Exception { assertFalse(service.getAllProducts().isEmpty()); } @Test public void testDataServiceCanFetchCategories() throws Exception { assertFalse(service.getAllCategories().isEmpty()); } @Test public void testUpdateProduct_updatesTheProduct() throws Exception {
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java // public class MockDataService extends DataService { // // private static MockDataService INSTANCE; // // private List<Product> products; // private List<Category> categories; // private int nextProductId = 0; // // private MockDataService() { // categories = MockDataGenerator.createCategories(); // products = MockDataGenerator.createProducts(categories); // nextProductId = products.size() + 1; // } // // public synchronized static DataService getInstance() { // if (INSTANCE == null) { // INSTANCE = new MockDataService(); // } // return INSTANCE; // } // // @Override // public synchronized List<Product> getAllProducts() { // return products; // } // // @Override // public synchronized List<Category> getAllCategories() { // return categories; // } // // @Override // public synchronized void updateProduct(Product p) { // if (p.getId() < 0) { // // New product // p.setId(nextProductId++); // products.add(p); // return; // } // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == p.getId()) { // products.set(i, p); // return; // } // } // // throw new IllegalArgumentException("No product with id " + p.getId() // + " found"); // } // // @Override // public synchronized Product getProductById(int productId) { // for (int i = 0; i < products.size(); i++) { // if (products.get(i).getId() == productId) { // return products.get(i); // } // } // return null; // } // // @Override // public synchronized void deleteProduct(int productId) { // Product p = getProductById(productId); // if (p == null) { // throw new IllegalArgumentException("Product with id " + productId // + " not found"); // } // products.remove(p); // } // } // Path: example-app/example-app-backend/src/test/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataServiceTest.java import org.junit.Before; import org.junit.Test; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; import com.github.mcollovati.vaadin.exampleapp.samples.backend.mock.MockDataService; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; package com.github.mcollovati.vaadin.exampleapp.samples.backend; /** * Simple unit test for the back-end data service. */ public class DataServiceTest { private DataService service; @Before public void setUp() throws Exception { service = MockDataService.getInstance(); } @Test public void testDataServiceCanFetchProducts() throws Exception { assertFalse(service.getAllProducts().isEmpty()); } @Test public void testDataServiceCanFetchCategories() throws Exception { assertFalse(service.getAllCategories().isEmpty()); } @Test public void testUpdateProduct_updatesTheProduct() throws Exception {
Product p = service.getAllProducts().iterator().next();
mcollovati/vaadin-vertx-samples
example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.util.List; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product;
package com.github.mcollovati.vaadin.exampleapp.samples.backend.mock; /** * Mock data model. This implementation has very simplistic locking and does not * notify users of modifications. */ public class MockDataService extends DataService { private static MockDataService INSTANCE;
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java import java.util.List; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; package com.github.mcollovati.vaadin.exampleapp.samples.backend.mock; /** * Mock data model. This implementation has very simplistic locking and does not * notify users of modifications. */ public class MockDataService extends DataService { private static MockDataService INSTANCE;
private List<Product> products;
mcollovati/vaadin-vertx-samples
example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // }
import java.util.List; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product;
package com.github.mcollovati.vaadin.exampleapp.samples.backend.mock; /** * Mock data model. This implementation has very simplistic locking and does not * notify users of modifications. */ public class MockDataService extends DataService { private static MockDataService INSTANCE; private List<Product> products;
// Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/DataService.java // public abstract class DataService implements Serializable { // // public abstract Collection<Product> getAllProducts(); // // public abstract Collection<Category> getAllCategories(); // // public abstract void updateProduct(Product p); // // public abstract void deleteProduct(int productId); // // public abstract Product getProductById(int productId); // // public static DataService get() { // return MockDataService.getInstance(); // } // // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Category.java // public class Category implements Serializable { // // @NotNull // private int id; // @NotNull // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return getName(); // } // } // // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/data/Product.java // public class Product implements Serializable { // // @NotNull // private int id = -1; // @NotNull // @Size(min = 2, message = "Product name must have at least two characters") // private String productName = ""; // @Min(0) // private BigDecimal price = BigDecimal.ZERO; // private Set<Category> category; // @Min(value = 0, message = "Can't have negative amount in stock") // private int stockCount = 0; // @NotNull // private Availability availability = Availability.COMING; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getProductName() { // return productName; // } // // public void setProductName(String productName) { // this.productName = productName; // } // // public BigDecimal getPrice() { // return price; // } // // public void setPrice(BigDecimal price) { // this.price = price; // } // // public Set<Category> getCategory() { // return category; // } // // public void setCategory(Set<Category> category) { // this.category = category; // } // // public int getStockCount() { // return stockCount; // } // // public void setStockCount(int stockCount) { // this.stockCount = stockCount; // } // // public Availability getAvailability() { // return availability; // } // // public void setAvailability(Availability availability) { // this.availability = availability; // } // // } // Path: example-app/example-app-backend/src/main/java/com/github/mcollovati/vaadin/exampleapp/samples/backend/mock/MockDataService.java import java.util.List; import com.github.mcollovati.vaadin.exampleapp.samples.backend.DataService; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Category; import com.github.mcollovati.vaadin.exampleapp.samples.backend.data.Product; package com.github.mcollovati.vaadin.exampleapp.samples.backend.mock; /** * Mock data model. This implementation has very simplistic locking and does not * notify users of modifications. */ public class MockDataService extends DataService { private static MockDataService INSTANCE; private List<Product> products;
private List<Category> categories;
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java // public class MarsWeatherClient { // // private static MarsWeatherInterface marsWeatherInterface; // // public static MarsWeatherInterface getMarsWeatherInterface() { // // if(marsWeatherInterface == null) { // // // Log level depending on build type. No logging in case of production APK // HttpLoggingInterceptor.Level logLevel; // // if(BuildConfig.DEBUG) // logLevel = HttpLoggingInterceptor.Level.BODY; // else // logLevel = HttpLoggingInterceptor.Level.NONE; // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // // Enable response caching // .addNetworkInterceptor(new ResponseCacheInterceptor()) // // Set the cache location and size (5 MB) // .cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() // .getCacheDir(), RestClientConstants.apiResponsesCache), // 5 * 1024 * 1024)) // // Enable logging // .addInterceptor(new HttpLoggingInterceptor() // .setLevel(logLevel)) // .build(); // // GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( // new GsonBuilder() // .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) // .create() // ); // // Retrofit retrofitClient = new Retrofit.Builder() // .baseUrl(RestClientConstants.marsWeatherBaseUrl) // .client(okHttpClient) // .addConverterFactory(gsonConverterFactory) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // // marsWeatherInterface = retrofitClient.create(MarsWeatherInterface.class); // } // // return marsWeatherInterface; // } // // public interface MarsWeatherInterface { // // @GET("api.php") // Observable<MarsWeatherResultDM> getLatestMarsWeather( // @Header(RestClientConstants.responseCachingFlagHeader) boolean responseCacheFlag // ); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/NASARestApiClient.java // public class NASARestApiClient { // // private static NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // public static NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // // if(nasaMarsPhotosApiInterface == null) { // // // Log level depending on build type. No logging in case of production APK // HttpLoggingInterceptor.Level logLevel; // // if(BuildConfig.DEBUG) // logLevel = HttpLoggingInterceptor.Level.BODY; // else // logLevel = HttpLoggingInterceptor.Level.NONE; // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // // Enable response caching // .addNetworkInterceptor(new ResponseCacheInterceptor()) // .addInterceptor(new OfflineResponseCacheInterceptor()) // // Set the cache location and size (5 MB) // .cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() // .getCacheDir(), RestClientConstants.apiResponsesCache), // 5 * 1024 * 1024)) // // Add the api key by default // .addInterceptor(new DefaultValuesInterceptor // (MarsExplorerApplication.getApplicationInstance() // .getString(R.string.NASA_API_KEY))) // // Enable logging // .addInterceptor(new HttpLoggingInterceptor() // .setLevel(logLevel)) // // Set the timeout periods // .readTimeout(60, TimeUnit.SECONDS) // .connectTimeout(60, TimeUnit.SECONDS) // .build(); // // GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( // new GsonBuilder() // .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) // .create() // ); // // Retrofit retrofitClient = new Retrofit.Builder() // .baseUrl(RestClientConstants.nasaApiBaseUrl) // .client(okHttpClient) // .addConverterFactory(gsonConverterFactory) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // // nasaMarsPhotosApiInterface = retrofitClient.create(NASAMarsPhotosApiInterface.class); // } // // return nasaMarsPhotosApiInterface; // } // // public interface NASAMarsPhotosApiInterface { // // @GET("{roverName}/photos") // Observable<PhotosResultDM> getPhotosBySol( // @Header(RestClientConstants.offlineCachingFlagHeader) boolean offlineCacheFlag, // @Header(RestClientConstants.responseCachingFlagHeader) boolean responseCacheFlag, // @Path("roverName") String roverName, // @Query("sol") String SOL); // } // // /** // * Interceptor that, by default, adds required query parameter(s) in every API request. // */ // private static class DefaultValuesInterceptor implements Interceptor { // // private String apiKey; // // public DefaultValuesInterceptor(String apiKey) { // this.apiKey = apiKey; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // HttpUrl url = request.url().newBuilder() // .addQueryParameter("api_key", this.apiKey) // .build(); // request = request.newBuilder().url(url).build(); // return chain.proceed(request); // } // } // }
import android.app.Application; import com.squareup.leakcanary.LeakCanary; import com.squareup.picasso.Picasso; import io.github.krtkush.marsexplorer.RESTClients.MarsWeatherClient; import io.github.krtkush.marsexplorer.RESTClients.NASARestApiClient; import timber.log.Timber; import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
package io.github.krtkush.marsexplorer; /** * Created by kartikeykushwaha on 21/05/16. */ public class MarsExplorerApplication extends Application { // Variable that holds instance of the application class private static MarsExplorerApplication marsExplorerApplicationInstance; // Variable that holds instance of the photos API interface
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java // public class MarsWeatherClient { // // private static MarsWeatherInterface marsWeatherInterface; // // public static MarsWeatherInterface getMarsWeatherInterface() { // // if(marsWeatherInterface == null) { // // // Log level depending on build type. No logging in case of production APK // HttpLoggingInterceptor.Level logLevel; // // if(BuildConfig.DEBUG) // logLevel = HttpLoggingInterceptor.Level.BODY; // else // logLevel = HttpLoggingInterceptor.Level.NONE; // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // // Enable response caching // .addNetworkInterceptor(new ResponseCacheInterceptor()) // // Set the cache location and size (5 MB) // .cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() // .getCacheDir(), RestClientConstants.apiResponsesCache), // 5 * 1024 * 1024)) // // Enable logging // .addInterceptor(new HttpLoggingInterceptor() // .setLevel(logLevel)) // .build(); // // GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( // new GsonBuilder() // .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) // .create() // ); // // Retrofit retrofitClient = new Retrofit.Builder() // .baseUrl(RestClientConstants.marsWeatherBaseUrl) // .client(okHttpClient) // .addConverterFactory(gsonConverterFactory) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // // marsWeatherInterface = retrofitClient.create(MarsWeatherInterface.class); // } // // return marsWeatherInterface; // } // // public interface MarsWeatherInterface { // // @GET("api.php") // Observable<MarsWeatherResultDM> getLatestMarsWeather( // @Header(RestClientConstants.responseCachingFlagHeader) boolean responseCacheFlag // ); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/NASARestApiClient.java // public class NASARestApiClient { // // private static NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // public static NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // // if(nasaMarsPhotosApiInterface == null) { // // // Log level depending on build type. No logging in case of production APK // HttpLoggingInterceptor.Level logLevel; // // if(BuildConfig.DEBUG) // logLevel = HttpLoggingInterceptor.Level.BODY; // else // logLevel = HttpLoggingInterceptor.Level.NONE; // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // // Enable response caching // .addNetworkInterceptor(new ResponseCacheInterceptor()) // .addInterceptor(new OfflineResponseCacheInterceptor()) // // Set the cache location and size (5 MB) // .cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() // .getCacheDir(), RestClientConstants.apiResponsesCache), // 5 * 1024 * 1024)) // // Add the api key by default // .addInterceptor(new DefaultValuesInterceptor // (MarsExplorerApplication.getApplicationInstance() // .getString(R.string.NASA_API_KEY))) // // Enable logging // .addInterceptor(new HttpLoggingInterceptor() // .setLevel(logLevel)) // // Set the timeout periods // .readTimeout(60, TimeUnit.SECONDS) // .connectTimeout(60, TimeUnit.SECONDS) // .build(); // // GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( // new GsonBuilder() // .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) // .create() // ); // // Retrofit retrofitClient = new Retrofit.Builder() // .baseUrl(RestClientConstants.nasaApiBaseUrl) // .client(okHttpClient) // .addConverterFactory(gsonConverterFactory) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // // nasaMarsPhotosApiInterface = retrofitClient.create(NASAMarsPhotosApiInterface.class); // } // // return nasaMarsPhotosApiInterface; // } // // public interface NASAMarsPhotosApiInterface { // // @GET("{roverName}/photos") // Observable<PhotosResultDM> getPhotosBySol( // @Header(RestClientConstants.offlineCachingFlagHeader) boolean offlineCacheFlag, // @Header(RestClientConstants.responseCachingFlagHeader) boolean responseCacheFlag, // @Path("roverName") String roverName, // @Query("sol") String SOL); // } // // /** // * Interceptor that, by default, adds required query parameter(s) in every API request. // */ // private static class DefaultValuesInterceptor implements Interceptor { // // private String apiKey; // // public DefaultValuesInterceptor(String apiKey) { // this.apiKey = apiKey; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // HttpUrl url = request.url().newBuilder() // .addQueryParameter("api_key", this.apiKey) // .build(); // request = request.newBuilder().url(url).build(); // return chain.proceed(request); // } // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java import android.app.Application; import com.squareup.leakcanary.LeakCanary; import com.squareup.picasso.Picasso; import io.github.krtkush.marsexplorer.RESTClients.MarsWeatherClient; import io.github.krtkush.marsexplorer.RESTClients.NASARestApiClient; import timber.log.Timber; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; package io.github.krtkush.marsexplorer; /** * Created by kartikeykushwaha on 21/05/16. */ public class MarsExplorerApplication extends Application { // Variable that holds instance of the application class private static MarsExplorerApplication marsExplorerApplicationInstance; // Variable that holds instance of the photos API interface
private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface;
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java // public class MarsWeatherClient { // // private static MarsWeatherInterface marsWeatherInterface; // // public static MarsWeatherInterface getMarsWeatherInterface() { // // if(marsWeatherInterface == null) { // // // Log level depending on build type. No logging in case of production APK // HttpLoggingInterceptor.Level logLevel; // // if(BuildConfig.DEBUG) // logLevel = HttpLoggingInterceptor.Level.BODY; // else // logLevel = HttpLoggingInterceptor.Level.NONE; // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // // Enable response caching // .addNetworkInterceptor(new ResponseCacheInterceptor()) // // Set the cache location and size (5 MB) // .cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() // .getCacheDir(), RestClientConstants.apiResponsesCache), // 5 * 1024 * 1024)) // // Enable logging // .addInterceptor(new HttpLoggingInterceptor() // .setLevel(logLevel)) // .build(); // // GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( // new GsonBuilder() // .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) // .create() // ); // // Retrofit retrofitClient = new Retrofit.Builder() // .baseUrl(RestClientConstants.marsWeatherBaseUrl) // .client(okHttpClient) // .addConverterFactory(gsonConverterFactory) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // // marsWeatherInterface = retrofitClient.create(MarsWeatherInterface.class); // } // // return marsWeatherInterface; // } // // public interface MarsWeatherInterface { // // @GET("api.php") // Observable<MarsWeatherResultDM> getLatestMarsWeather( // @Header(RestClientConstants.responseCachingFlagHeader) boolean responseCacheFlag // ); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/NASARestApiClient.java // public class NASARestApiClient { // // private static NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // public static NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // // if(nasaMarsPhotosApiInterface == null) { // // // Log level depending on build type. No logging in case of production APK // HttpLoggingInterceptor.Level logLevel; // // if(BuildConfig.DEBUG) // logLevel = HttpLoggingInterceptor.Level.BODY; // else // logLevel = HttpLoggingInterceptor.Level.NONE; // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // // Enable response caching // .addNetworkInterceptor(new ResponseCacheInterceptor()) // .addInterceptor(new OfflineResponseCacheInterceptor()) // // Set the cache location and size (5 MB) // .cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() // .getCacheDir(), RestClientConstants.apiResponsesCache), // 5 * 1024 * 1024)) // // Add the api key by default // .addInterceptor(new DefaultValuesInterceptor // (MarsExplorerApplication.getApplicationInstance() // .getString(R.string.NASA_API_KEY))) // // Enable logging // .addInterceptor(new HttpLoggingInterceptor() // .setLevel(logLevel)) // // Set the timeout periods // .readTimeout(60, TimeUnit.SECONDS) // .connectTimeout(60, TimeUnit.SECONDS) // .build(); // // GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( // new GsonBuilder() // .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) // .create() // ); // // Retrofit retrofitClient = new Retrofit.Builder() // .baseUrl(RestClientConstants.nasaApiBaseUrl) // .client(okHttpClient) // .addConverterFactory(gsonConverterFactory) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // // nasaMarsPhotosApiInterface = retrofitClient.create(NASAMarsPhotosApiInterface.class); // } // // return nasaMarsPhotosApiInterface; // } // // public interface NASAMarsPhotosApiInterface { // // @GET("{roverName}/photos") // Observable<PhotosResultDM> getPhotosBySol( // @Header(RestClientConstants.offlineCachingFlagHeader) boolean offlineCacheFlag, // @Header(RestClientConstants.responseCachingFlagHeader) boolean responseCacheFlag, // @Path("roverName") String roverName, // @Query("sol") String SOL); // } // // /** // * Interceptor that, by default, adds required query parameter(s) in every API request. // */ // private static class DefaultValuesInterceptor implements Interceptor { // // private String apiKey; // // public DefaultValuesInterceptor(String apiKey) { // this.apiKey = apiKey; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // HttpUrl url = request.url().newBuilder() // .addQueryParameter("api_key", this.apiKey) // .build(); // request = request.newBuilder().url(url).build(); // return chain.proceed(request); // } // } // }
import android.app.Application; import com.squareup.leakcanary.LeakCanary; import com.squareup.picasso.Picasso; import io.github.krtkush.marsexplorer.RESTClients.MarsWeatherClient; import io.github.krtkush.marsexplorer.RESTClients.NASARestApiClient; import timber.log.Timber; import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
package io.github.krtkush.marsexplorer; /** * Created by kartikeykushwaha on 21/05/16. */ public class MarsExplorerApplication extends Application { // Variable that holds instance of the application class private static MarsExplorerApplication marsExplorerApplicationInstance; // Variable that holds instance of the photos API interface private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // Variable to hold instance of the weather API interface
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java // public class MarsWeatherClient { // // private static MarsWeatherInterface marsWeatherInterface; // // public static MarsWeatherInterface getMarsWeatherInterface() { // // if(marsWeatherInterface == null) { // // // Log level depending on build type. No logging in case of production APK // HttpLoggingInterceptor.Level logLevel; // // if(BuildConfig.DEBUG) // logLevel = HttpLoggingInterceptor.Level.BODY; // else // logLevel = HttpLoggingInterceptor.Level.NONE; // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // // Enable response caching // .addNetworkInterceptor(new ResponseCacheInterceptor()) // // Set the cache location and size (5 MB) // .cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() // .getCacheDir(), RestClientConstants.apiResponsesCache), // 5 * 1024 * 1024)) // // Enable logging // .addInterceptor(new HttpLoggingInterceptor() // .setLevel(logLevel)) // .build(); // // GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( // new GsonBuilder() // .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) // .create() // ); // // Retrofit retrofitClient = new Retrofit.Builder() // .baseUrl(RestClientConstants.marsWeatherBaseUrl) // .client(okHttpClient) // .addConverterFactory(gsonConverterFactory) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // // marsWeatherInterface = retrofitClient.create(MarsWeatherInterface.class); // } // // return marsWeatherInterface; // } // // public interface MarsWeatherInterface { // // @GET("api.php") // Observable<MarsWeatherResultDM> getLatestMarsWeather( // @Header(RestClientConstants.responseCachingFlagHeader) boolean responseCacheFlag // ); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/NASARestApiClient.java // public class NASARestApiClient { // // private static NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // public static NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // // if(nasaMarsPhotosApiInterface == null) { // // // Log level depending on build type. No logging in case of production APK // HttpLoggingInterceptor.Level logLevel; // // if(BuildConfig.DEBUG) // logLevel = HttpLoggingInterceptor.Level.BODY; // else // logLevel = HttpLoggingInterceptor.Level.NONE; // // OkHttpClient okHttpClient = new OkHttpClient.Builder() // // Enable response caching // .addNetworkInterceptor(new ResponseCacheInterceptor()) // .addInterceptor(new OfflineResponseCacheInterceptor()) // // Set the cache location and size (5 MB) // .cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() // .getCacheDir(), RestClientConstants.apiResponsesCache), // 5 * 1024 * 1024)) // // Add the api key by default // .addInterceptor(new DefaultValuesInterceptor // (MarsExplorerApplication.getApplicationInstance() // .getString(R.string.NASA_API_KEY))) // // Enable logging // .addInterceptor(new HttpLoggingInterceptor() // .setLevel(logLevel)) // // Set the timeout periods // .readTimeout(60, TimeUnit.SECONDS) // .connectTimeout(60, TimeUnit.SECONDS) // .build(); // // GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( // new GsonBuilder() // .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) // .create() // ); // // Retrofit retrofitClient = new Retrofit.Builder() // .baseUrl(RestClientConstants.nasaApiBaseUrl) // .client(okHttpClient) // .addConverterFactory(gsonConverterFactory) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build(); // // nasaMarsPhotosApiInterface = retrofitClient.create(NASAMarsPhotosApiInterface.class); // } // // return nasaMarsPhotosApiInterface; // } // // public interface NASAMarsPhotosApiInterface { // // @GET("{roverName}/photos") // Observable<PhotosResultDM> getPhotosBySol( // @Header(RestClientConstants.offlineCachingFlagHeader) boolean offlineCacheFlag, // @Header(RestClientConstants.responseCachingFlagHeader) boolean responseCacheFlag, // @Path("roverName") String roverName, // @Query("sol") String SOL); // } // // /** // * Interceptor that, by default, adds required query parameter(s) in every API request. // */ // private static class DefaultValuesInterceptor implements Interceptor { // // private String apiKey; // // public DefaultValuesInterceptor(String apiKey) { // this.apiKey = apiKey; // } // // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // HttpUrl url = request.url().newBuilder() // .addQueryParameter("api_key", this.apiKey) // .build(); // request = request.newBuilder().url(url).build(); // return chain.proceed(request); // } // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java import android.app.Application; import com.squareup.leakcanary.LeakCanary; import com.squareup.picasso.Picasso; import io.github.krtkush.marsexplorer.RESTClients.MarsWeatherClient; import io.github.krtkush.marsexplorer.RESTClients.NASARestApiClient; import timber.log.Timber; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; package io.github.krtkush.marsexplorer; /** * Created by kartikeykushwaha on 21/05/16. */ public class MarsExplorerApplication extends Application { // Variable that holds instance of the application class private static MarsExplorerApplication marsExplorerApplicationInstance; // Variable that holds instance of the photos API interface private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // Variable to hold instance of the weather API interface
private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface;
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/OfflineResponseCacheInterceptor.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/RestClientConstants.java // public class RestClientConstants { // // // Strings related to NASA's API // private static final String nasaApiEndPoint = "https://api.nasa.gov/"; // private static final String nasaApiServiceName = "mars-photos/"; // private static final String nasaApiVersion = "api/v1/rovers/"; // public static final String nasaApiBaseUrl = nasaApiEndPoint + nasaApiServiceName // + nasaApiVersion; // // // Strings related to Mars Weather's API // private static final String marsWeatherEndPoint = "http://cab.inta-csic.es/"; // private static final String marsWeatherAddress = "rems/wp-content/plugins/marsweather-widget/"; // public static final String marsWeatherBaseUrl = marsWeatherEndPoint + marsWeatherAddress; // // // Custom headers // public static final String responseCachingFlagHeader = "ApplyResponseCache"; // public static final String offlineCachingFlagHeader = "ApplyOfflineCache"; // // // Cache directory name // public static final String apiResponsesCache = "apiResponses"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java // public class UtilityMethods { // // /** // * Method to detect network connection on the device // * @return // */ // public static boolean isNetworkAvailable() { // // ConnectivityManager connectivityManager = // (ConnectivityManager) MarsExplorerApplication.getApplicationInstance() // .getSystemService(MarsExplorerApplication.getApplicationInstance() // .CONNECTIVITY_SERVICE); // // return connectivityManager.getActiveNetworkInfo() != null // && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting(); // } // // /** // * It's usually very important for websites to track where their traffic is coming from. // * We make sure to let them know that we are sending them users by setting the referrer when // * launching our Custom Tab. // * @return The value of the Referrer Intent. // */ // public static String customTabReferrerString() { // // int URI_ANDROID_APP_SCHEME; // // // Prepare for SDK version compatibility problems. // if(Build.VERSION.SDK_INT < 22) // URI_ANDROID_APP_SCHEME = 1<<1; // else // URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME; // // return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance() // .getPackageName(); // } // // /** // * @return The Referrer intent key. // */ // public static String customTabReferrerKey() { // // String EXTRA_REFERRER; // // // Prepare for SDK version compatibility problems. // if(Build.VERSION.SDK_INT < 17) // EXTRA_REFERRER = "android.intent.extra.REFERRER"; // else // EXTRA_REFERRER = Intent.EXTRA_REFERRER; // // return EXTRA_REFERRER; // } // }
import java.io.IOException; import io.github.krtkush.marsexplorer.RESTClients.RestClientConstants; import io.github.krtkush.marsexplorer.UtilityMethods; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; import timber.log.Timber;
package io.github.krtkush.marsexplorer.RESTClients.Interceptors; /** * Created by kartikeykushwaha on 08/06/16. */ /** * Interceptor to cache data and maintain it for four weeks. * * If the device is offline, stale (at most four weeks old) response is fetched from the cache. */ public class OfflineResponseCacheInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request();
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/RestClientConstants.java // public class RestClientConstants { // // // Strings related to NASA's API // private static final String nasaApiEndPoint = "https://api.nasa.gov/"; // private static final String nasaApiServiceName = "mars-photos/"; // private static final String nasaApiVersion = "api/v1/rovers/"; // public static final String nasaApiBaseUrl = nasaApiEndPoint + nasaApiServiceName // + nasaApiVersion; // // // Strings related to Mars Weather's API // private static final String marsWeatherEndPoint = "http://cab.inta-csic.es/"; // private static final String marsWeatherAddress = "rems/wp-content/plugins/marsweather-widget/"; // public static final String marsWeatherBaseUrl = marsWeatherEndPoint + marsWeatherAddress; // // // Custom headers // public static final String responseCachingFlagHeader = "ApplyResponseCache"; // public static final String offlineCachingFlagHeader = "ApplyOfflineCache"; // // // Cache directory name // public static final String apiResponsesCache = "apiResponses"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java // public class UtilityMethods { // // /** // * Method to detect network connection on the device // * @return // */ // public static boolean isNetworkAvailable() { // // ConnectivityManager connectivityManager = // (ConnectivityManager) MarsExplorerApplication.getApplicationInstance() // .getSystemService(MarsExplorerApplication.getApplicationInstance() // .CONNECTIVITY_SERVICE); // // return connectivityManager.getActiveNetworkInfo() != null // && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting(); // } // // /** // * It's usually very important for websites to track where their traffic is coming from. // * We make sure to let them know that we are sending them users by setting the referrer when // * launching our Custom Tab. // * @return The value of the Referrer Intent. // */ // public static String customTabReferrerString() { // // int URI_ANDROID_APP_SCHEME; // // // Prepare for SDK version compatibility problems. // if(Build.VERSION.SDK_INT < 22) // URI_ANDROID_APP_SCHEME = 1<<1; // else // URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME; // // return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance() // .getPackageName(); // } // // /** // * @return The Referrer intent key. // */ // public static String customTabReferrerKey() { // // String EXTRA_REFERRER; // // // Prepare for SDK version compatibility problems. // if(Build.VERSION.SDK_INT < 17) // EXTRA_REFERRER = "android.intent.extra.REFERRER"; // else // EXTRA_REFERRER = Intent.EXTRA_REFERRER; // // return EXTRA_REFERRER; // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/OfflineResponseCacheInterceptor.java import java.io.IOException; import io.github.krtkush.marsexplorer.RESTClients.RestClientConstants; import io.github.krtkush.marsexplorer.UtilityMethods; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; import timber.log.Timber; package io.github.krtkush.marsexplorer.RESTClients.Interceptors; /** * Created by kartikeykushwaha on 08/06/16. */ /** * Interceptor to cache data and maintain it for four weeks. * * If the device is offline, stale (at most four weeks old) response is fetched from the cache. */ public class OfflineResponseCacheInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request();
if(Boolean.valueOf(request.header(RestClientConstants.offlineCachingFlagHeader))) {
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/OfflineResponseCacheInterceptor.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/RestClientConstants.java // public class RestClientConstants { // // // Strings related to NASA's API // private static final String nasaApiEndPoint = "https://api.nasa.gov/"; // private static final String nasaApiServiceName = "mars-photos/"; // private static final String nasaApiVersion = "api/v1/rovers/"; // public static final String nasaApiBaseUrl = nasaApiEndPoint + nasaApiServiceName // + nasaApiVersion; // // // Strings related to Mars Weather's API // private static final String marsWeatherEndPoint = "http://cab.inta-csic.es/"; // private static final String marsWeatherAddress = "rems/wp-content/plugins/marsweather-widget/"; // public static final String marsWeatherBaseUrl = marsWeatherEndPoint + marsWeatherAddress; // // // Custom headers // public static final String responseCachingFlagHeader = "ApplyResponseCache"; // public static final String offlineCachingFlagHeader = "ApplyOfflineCache"; // // // Cache directory name // public static final String apiResponsesCache = "apiResponses"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java // public class UtilityMethods { // // /** // * Method to detect network connection on the device // * @return // */ // public static boolean isNetworkAvailable() { // // ConnectivityManager connectivityManager = // (ConnectivityManager) MarsExplorerApplication.getApplicationInstance() // .getSystemService(MarsExplorerApplication.getApplicationInstance() // .CONNECTIVITY_SERVICE); // // return connectivityManager.getActiveNetworkInfo() != null // && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting(); // } // // /** // * It's usually very important for websites to track where their traffic is coming from. // * We make sure to let them know that we are sending them users by setting the referrer when // * launching our Custom Tab. // * @return The value of the Referrer Intent. // */ // public static String customTabReferrerString() { // // int URI_ANDROID_APP_SCHEME; // // // Prepare for SDK version compatibility problems. // if(Build.VERSION.SDK_INT < 22) // URI_ANDROID_APP_SCHEME = 1<<1; // else // URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME; // // return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance() // .getPackageName(); // } // // /** // * @return The Referrer intent key. // */ // public static String customTabReferrerKey() { // // String EXTRA_REFERRER; // // // Prepare for SDK version compatibility problems. // if(Build.VERSION.SDK_INT < 17) // EXTRA_REFERRER = "android.intent.extra.REFERRER"; // else // EXTRA_REFERRER = Intent.EXTRA_REFERRER; // // return EXTRA_REFERRER; // } // }
import java.io.IOException; import io.github.krtkush.marsexplorer.RESTClients.RestClientConstants; import io.github.krtkush.marsexplorer.UtilityMethods; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; import timber.log.Timber;
package io.github.krtkush.marsexplorer.RESTClients.Interceptors; /** * Created by kartikeykushwaha on 08/06/16. */ /** * Interceptor to cache data and maintain it for four weeks. * * If the device is offline, stale (at most four weeks old) response is fetched from the cache. */ public class OfflineResponseCacheInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if(Boolean.valueOf(request.header(RestClientConstants.offlineCachingFlagHeader))) { Timber.i("Offline cache applied");
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/RestClientConstants.java // public class RestClientConstants { // // // Strings related to NASA's API // private static final String nasaApiEndPoint = "https://api.nasa.gov/"; // private static final String nasaApiServiceName = "mars-photos/"; // private static final String nasaApiVersion = "api/v1/rovers/"; // public static final String nasaApiBaseUrl = nasaApiEndPoint + nasaApiServiceName // + nasaApiVersion; // // // Strings related to Mars Weather's API // private static final String marsWeatherEndPoint = "http://cab.inta-csic.es/"; // private static final String marsWeatherAddress = "rems/wp-content/plugins/marsweather-widget/"; // public static final String marsWeatherBaseUrl = marsWeatherEndPoint + marsWeatherAddress; // // // Custom headers // public static final String responseCachingFlagHeader = "ApplyResponseCache"; // public static final String offlineCachingFlagHeader = "ApplyOfflineCache"; // // // Cache directory name // public static final String apiResponsesCache = "apiResponses"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/UtilityMethods.java // public class UtilityMethods { // // /** // * Method to detect network connection on the device // * @return // */ // public static boolean isNetworkAvailable() { // // ConnectivityManager connectivityManager = // (ConnectivityManager) MarsExplorerApplication.getApplicationInstance() // .getSystemService(MarsExplorerApplication.getApplicationInstance() // .CONNECTIVITY_SERVICE); // // return connectivityManager.getActiveNetworkInfo() != null // && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting(); // } // // /** // * It's usually very important for websites to track where their traffic is coming from. // * We make sure to let them know that we are sending them users by setting the referrer when // * launching our Custom Tab. // * @return The value of the Referrer Intent. // */ // public static String customTabReferrerString() { // // int URI_ANDROID_APP_SCHEME; // // // Prepare for SDK version compatibility problems. // if(Build.VERSION.SDK_INT < 22) // URI_ANDROID_APP_SCHEME = 1<<1; // else // URI_ANDROID_APP_SCHEME = Intent.URI_ANDROID_APP_SCHEME; // // return URI_ANDROID_APP_SCHEME + "//" + MarsExplorerApplication.getApplicationInstance() // .getPackageName(); // } // // /** // * @return The Referrer intent key. // */ // public static String customTabReferrerKey() { // // String EXTRA_REFERRER; // // // Prepare for SDK version compatibility problems. // if(Build.VERSION.SDK_INT < 17) // EXTRA_REFERRER = "android.intent.extra.REFERRER"; // else // EXTRA_REFERRER = Intent.EXTRA_REFERRER; // // return EXTRA_REFERRER; // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/OfflineResponseCacheInterceptor.java import java.io.IOException; import io.github.krtkush.marsexplorer.RESTClients.RestClientConstants; import io.github.krtkush.marsexplorer.UtilityMethods; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; import timber.log.Timber; package io.github.krtkush.marsexplorer.RESTClients.Interceptors; /** * Created by kartikeykushwaha on 08/06/16. */ /** * Interceptor to cache data and maintain it for four weeks. * * If the device is offline, stale (at most four weeks old) response is fetched from the cache. */ public class OfflineResponseCacheInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if(Boolean.valueOf(request.header(RestClientConstants.offlineCachingFlagHeader))) { Timber.i("Offline cache applied");
if(!UtilityMethods.isNetworkAvailable()) {
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/PhotosRecyclerViewAdapter.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/ExpandedPhotosConstants.java // public class ExpandedPhotosConstants { // // // Constants for identifying data being passed via intents // public static final String imageUrl = "ImageUrl"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/PhotoExpandedViewActivity.java // public class PhotoExpandedViewActivity extends AppCompatActivity { // // @BindView(R.id.expandedPhotoHolder) ImageView expandedPhotoHolder; // // private PhotoExpandedViewInteractor presenterInteractor; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_photo_expanded_view); // // // Initialise butterknife, timber and the presenter layer // ButterKnife.bind(PhotoExpandedViewActivity.this); // Timber.tag(PhotoExpandedViewActivity.this.getClass().getSimpleName()); // presenterInteractor = new PhotoExpandedViewPresenterLayer(this); // // // Fetch the url of the image to be displayed and then show that image. // presenterInteractor.getImageUrl(); // } // // /** // * Set the images. // * @param imagePath // */ // protected void setImage(String imagePath) { // // ActivityCompat.postponeEnterTransition(this); // Picasso.with(this.getApplicationContext()) // .load(imagePath) // .fit() // .centerCrop() // .placeholder(R.drawable.square_placeholder) // .into(expandedPhotoHolder, new Callback() { // @Override // public void onSuccess() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // // @Override // public void onError() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // }); // } // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.AnimationSet; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.ExpandedPhotosConstants; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.PhotoExpandedViewActivity;
package io.github.krtkush.marsexplorer.RoverExplorer.ExplorerFragment; /** * Created by kartikeykushwaha on 25/08/16. */ public class PhotosRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context;
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/ExpandedPhotosConstants.java // public class ExpandedPhotosConstants { // // // Constants for identifying data being passed via intents // public static final String imageUrl = "ImageUrl"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/PhotoExpandedViewActivity.java // public class PhotoExpandedViewActivity extends AppCompatActivity { // // @BindView(R.id.expandedPhotoHolder) ImageView expandedPhotoHolder; // // private PhotoExpandedViewInteractor presenterInteractor; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_photo_expanded_view); // // // Initialise butterknife, timber and the presenter layer // ButterKnife.bind(PhotoExpandedViewActivity.this); // Timber.tag(PhotoExpandedViewActivity.this.getClass().getSimpleName()); // presenterInteractor = new PhotoExpandedViewPresenterLayer(this); // // // Fetch the url of the image to be displayed and then show that image. // presenterInteractor.getImageUrl(); // } // // /** // * Set the images. // * @param imagePath // */ // protected void setImage(String imagePath) { // // ActivityCompat.postponeEnterTransition(this); // Picasso.with(this.getApplicationContext()) // .load(imagePath) // .fit() // .centerCrop() // .placeholder(R.drawable.square_placeholder) // .into(expandedPhotoHolder, new Callback() { // @Override // public void onSuccess() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // // @Override // public void onError() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // }); // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/PhotosRecyclerViewAdapter.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.AnimationSet; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.ExpandedPhotosConstants; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.PhotoExpandedViewActivity; package io.github.krtkush.marsexplorer.RoverExplorer.ExplorerFragment; /** * Created by kartikeykushwaha on 25/08/16. */ public class PhotosRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context;
private List<Photos> photos;
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/PhotosRecyclerViewAdapter.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/ExpandedPhotosConstants.java // public class ExpandedPhotosConstants { // // // Constants for identifying data being passed via intents // public static final String imageUrl = "ImageUrl"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/PhotoExpandedViewActivity.java // public class PhotoExpandedViewActivity extends AppCompatActivity { // // @BindView(R.id.expandedPhotoHolder) ImageView expandedPhotoHolder; // // private PhotoExpandedViewInteractor presenterInteractor; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_photo_expanded_view); // // // Initialise butterknife, timber and the presenter layer // ButterKnife.bind(PhotoExpandedViewActivity.this); // Timber.tag(PhotoExpandedViewActivity.this.getClass().getSimpleName()); // presenterInteractor = new PhotoExpandedViewPresenterLayer(this); // // // Fetch the url of the image to be displayed and then show that image. // presenterInteractor.getImageUrl(); // } // // /** // * Set the images. // * @param imagePath // */ // protected void setImage(String imagePath) { // // ActivityCompat.postponeEnterTransition(this); // Picasso.with(this.getApplicationContext()) // .load(imagePath) // .fit() // .centerCrop() // .placeholder(R.drawable.square_placeholder) // .into(expandedPhotoHolder, new Callback() { // @Override // public void onSuccess() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // // @Override // public void onError() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // }); // } // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.AnimationSet; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.ExpandedPhotosConstants; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.PhotoExpandedViewActivity;
.placeholder(R.drawable.square_placeholder) .fit() .centerCrop() .into(photosViewHolder.photoHolder, new Callback() { @Override public void onSuccess() { photosViewHolder.photoHolder.setTag(R.integer.hasImageLoaded, activity.getString(R.string.imageHasLoaded)); } @Override public void onError() { photosViewHolder.photoHolder.setTag(R.integer.hasImageLoaded, null); } }); // Photo Id photosViewHolder.photoId .setText(String.valueOf(photos.get(viewHolder.getAdapterPosition()).id())); // Camera Initials photosViewHolder.cameraInitial .setText(photos.get(viewHolder.getAdapterPosition()).camera().name()); // On click action photosViewHolder.photoHolderLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent goToPhotoExpandedActivity =
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/ExpandedPhotosConstants.java // public class ExpandedPhotosConstants { // // // Constants for identifying data being passed via intents // public static final String imageUrl = "ImageUrl"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/PhotoExpandedViewActivity.java // public class PhotoExpandedViewActivity extends AppCompatActivity { // // @BindView(R.id.expandedPhotoHolder) ImageView expandedPhotoHolder; // // private PhotoExpandedViewInteractor presenterInteractor; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_photo_expanded_view); // // // Initialise butterknife, timber and the presenter layer // ButterKnife.bind(PhotoExpandedViewActivity.this); // Timber.tag(PhotoExpandedViewActivity.this.getClass().getSimpleName()); // presenterInteractor = new PhotoExpandedViewPresenterLayer(this); // // // Fetch the url of the image to be displayed and then show that image. // presenterInteractor.getImageUrl(); // } // // /** // * Set the images. // * @param imagePath // */ // protected void setImage(String imagePath) { // // ActivityCompat.postponeEnterTransition(this); // Picasso.with(this.getApplicationContext()) // .load(imagePath) // .fit() // .centerCrop() // .placeholder(R.drawable.square_placeholder) // .into(expandedPhotoHolder, new Callback() { // @Override // public void onSuccess() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // // @Override // public void onError() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // }); // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/PhotosRecyclerViewAdapter.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.AnimationSet; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.ExpandedPhotosConstants; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.PhotoExpandedViewActivity; .placeholder(R.drawable.square_placeholder) .fit() .centerCrop() .into(photosViewHolder.photoHolder, new Callback() { @Override public void onSuccess() { photosViewHolder.photoHolder.setTag(R.integer.hasImageLoaded, activity.getString(R.string.imageHasLoaded)); } @Override public void onError() { photosViewHolder.photoHolder.setTag(R.integer.hasImageLoaded, null); } }); // Photo Id photosViewHolder.photoId .setText(String.valueOf(photos.get(viewHolder.getAdapterPosition()).id())); // Camera Initials photosViewHolder.cameraInitial .setText(photos.get(viewHolder.getAdapterPosition()).camera().name()); // On click action photosViewHolder.photoHolderLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent goToPhotoExpandedActivity =
new Intent(context, PhotoExpandedViewActivity.class);
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/PhotosRecyclerViewAdapter.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/ExpandedPhotosConstants.java // public class ExpandedPhotosConstants { // // // Constants for identifying data being passed via intents // public static final String imageUrl = "ImageUrl"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/PhotoExpandedViewActivity.java // public class PhotoExpandedViewActivity extends AppCompatActivity { // // @BindView(R.id.expandedPhotoHolder) ImageView expandedPhotoHolder; // // private PhotoExpandedViewInteractor presenterInteractor; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_photo_expanded_view); // // // Initialise butterknife, timber and the presenter layer // ButterKnife.bind(PhotoExpandedViewActivity.this); // Timber.tag(PhotoExpandedViewActivity.this.getClass().getSimpleName()); // presenterInteractor = new PhotoExpandedViewPresenterLayer(this); // // // Fetch the url of the image to be displayed and then show that image. // presenterInteractor.getImageUrl(); // } // // /** // * Set the images. // * @param imagePath // */ // protected void setImage(String imagePath) { // // ActivityCompat.postponeEnterTransition(this); // Picasso.with(this.getApplicationContext()) // .load(imagePath) // .fit() // .centerCrop() // .placeholder(R.drawable.square_placeholder) // .into(expandedPhotoHolder, new Callback() { // @Override // public void onSuccess() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // // @Override // public void onError() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // }); // } // }
import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.AnimationSet; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.ExpandedPhotosConstants; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.PhotoExpandedViewActivity;
.fit() .centerCrop() .into(photosViewHolder.photoHolder, new Callback() { @Override public void onSuccess() { photosViewHolder.photoHolder.setTag(R.integer.hasImageLoaded, activity.getString(R.string.imageHasLoaded)); } @Override public void onError() { photosViewHolder.photoHolder.setTag(R.integer.hasImageLoaded, null); } }); // Photo Id photosViewHolder.photoId .setText(String.valueOf(photos.get(viewHolder.getAdapterPosition()).id())); // Camera Initials photosViewHolder.cameraInitial .setText(photos.get(viewHolder.getAdapterPosition()).camera().name()); // On click action photosViewHolder.photoHolderLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent goToPhotoExpandedActivity = new Intent(context, PhotoExpandedViewActivity.class);
// Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/ExpandedPhotosConstants.java // public class ExpandedPhotosConstants { // // // Constants for identifying data being passed via intents // public static final String imageUrl = "ImageUrl"; // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExpandedPhoto/PhotoExpandedViewActivity.java // public class PhotoExpandedViewActivity extends AppCompatActivity { // // @BindView(R.id.expandedPhotoHolder) ImageView expandedPhotoHolder; // // private PhotoExpandedViewInteractor presenterInteractor; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_photo_expanded_view); // // // Initialise butterknife, timber and the presenter layer // ButterKnife.bind(PhotoExpandedViewActivity.this); // Timber.tag(PhotoExpandedViewActivity.this.getClass().getSimpleName()); // presenterInteractor = new PhotoExpandedViewPresenterLayer(this); // // // Fetch the url of the image to be displayed and then show that image. // presenterInteractor.getImageUrl(); // } // // /** // * Set the images. // * @param imagePath // */ // protected void setImage(String imagePath) { // // ActivityCompat.postponeEnterTransition(this); // Picasso.with(this.getApplicationContext()) // .load(imagePath) // .fit() // .centerCrop() // .placeholder(R.drawable.square_placeholder) // .into(expandedPhotoHolder, new Callback() { // @Override // public void onSuccess() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // // @Override // public void onError() { // ActivityCompat // .startPostponedEnterTransition(PhotoExpandedViewActivity.this); // } // }); // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/PhotosRecyclerViewAdapter.java import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.AnimationSet; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.ExpandedPhotosConstants; import io.github.krtkush.marsexplorer.RoverExplorer.ExpandedPhoto.PhotoExpandedViewActivity; .fit() .centerCrop() .into(photosViewHolder.photoHolder, new Callback() { @Override public void onSuccess() { photosViewHolder.photoHolder.setTag(R.integer.hasImageLoaded, activity.getString(R.string.imageHasLoaded)); } @Override public void onError() { photosViewHolder.photoHolder.setTag(R.integer.hasImageLoaded, null); } }); // Photo Id photosViewHolder.photoId .setText(String.valueOf(photos.get(viewHolder.getAdapterPosition()).id())); // Camera Initials photosViewHolder.cameraInitial .setText(photos.get(viewHolder.getAdapterPosition()).camera().name()); // On click action photosViewHolder.photoHolderLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent goToPhotoExpandedActivity = new Intent(context, PhotoExpandedViewActivity.class);
goToPhotoExpandedActivity.putExtra(ExpandedPhotosConstants.imageUrl,
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/WeatherJsonDataModel/MarsWeatherResultDM.java // @AutoValue // public abstract class MarsWeatherResultDM { // // /** // * List of the weather report for every SOL // */ // // @SerializedName("soles") // public abstract List<Soles> weatherReportList(); // // public static TypeAdapter<MarsWeatherResultDM> typeAdapter(Gson gson) { // return new AutoValue_MarsWeatherResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/ResponseCacheInterceptor.java // public class ResponseCacheInterceptor implements Interceptor { // @Override // public Response intercept(Chain chain) throws IOException { // // Request request = chain.request(); // if(Boolean.valueOf(request.header(RestClientConstants.responseCachingFlagHeader))) { // Timber.i("Response cache applied"); // Response originalResponse = chain.proceed(chain.request()); // return originalResponse.newBuilder() // .removeHeader(RestClientConstants.responseCachingFlagHeader) // .header("Cache-Control", "public, max-age=" + (3600 * 6)) // .build(); // } else { // Timber.i("Response cache not applied"); // return chain.proceed(chain.request()); // } // } // }
import com.google.gson.GsonBuilder; import java.io.File; import io.github.krtkush.marsexplorer.BuildConfig; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.RESTClients.DataModels.WeatherJsonDataModel.MarsWeatherResultDM; import io.github.krtkush.marsexplorer.RESTClients.Interceptors.ResponseCacheInterceptor; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Header; import rx.Observable;
package io.github.krtkush.marsexplorer.RESTClients; /** * Created by kartikeykushwaha on 08/06/16. */ public class MarsWeatherClient { private static MarsWeatherInterface marsWeatherInterface; public static MarsWeatherInterface getMarsWeatherInterface() { if(marsWeatherInterface == null) { // Log level depending on build type. No logging in case of production APK HttpLoggingInterceptor.Level logLevel; if(BuildConfig.DEBUG) logLevel = HttpLoggingInterceptor.Level.BODY; else logLevel = HttpLoggingInterceptor.Level.NONE; OkHttpClient okHttpClient = new OkHttpClient.Builder() // Enable response caching
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/WeatherJsonDataModel/MarsWeatherResultDM.java // @AutoValue // public abstract class MarsWeatherResultDM { // // /** // * List of the weather report for every SOL // */ // // @SerializedName("soles") // public abstract List<Soles> weatherReportList(); // // public static TypeAdapter<MarsWeatherResultDM> typeAdapter(Gson gson) { // return new AutoValue_MarsWeatherResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/ResponseCacheInterceptor.java // public class ResponseCacheInterceptor implements Interceptor { // @Override // public Response intercept(Chain chain) throws IOException { // // Request request = chain.request(); // if(Boolean.valueOf(request.header(RestClientConstants.responseCachingFlagHeader))) { // Timber.i("Response cache applied"); // Response originalResponse = chain.proceed(chain.request()); // return originalResponse.newBuilder() // .removeHeader(RestClientConstants.responseCachingFlagHeader) // .header("Cache-Control", "public, max-age=" + (3600 * 6)) // .build(); // } else { // Timber.i("Response cache not applied"); // return chain.proceed(chain.request()); // } // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java import com.google.gson.GsonBuilder; import java.io.File; import io.github.krtkush.marsexplorer.BuildConfig; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.RESTClients.DataModels.WeatherJsonDataModel.MarsWeatherResultDM; import io.github.krtkush.marsexplorer.RESTClients.Interceptors.ResponseCacheInterceptor; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Header; import rx.Observable; package io.github.krtkush.marsexplorer.RESTClients; /** * Created by kartikeykushwaha on 08/06/16. */ public class MarsWeatherClient { private static MarsWeatherInterface marsWeatherInterface; public static MarsWeatherInterface getMarsWeatherInterface() { if(marsWeatherInterface == null) { // Log level depending on build type. No logging in case of production APK HttpLoggingInterceptor.Level logLevel; if(BuildConfig.DEBUG) logLevel = HttpLoggingInterceptor.Level.BODY; else logLevel = HttpLoggingInterceptor.Level.NONE; OkHttpClient okHttpClient = new OkHttpClient.Builder() // Enable response caching
.addNetworkInterceptor(new ResponseCacheInterceptor())
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/WeatherJsonDataModel/MarsWeatherResultDM.java // @AutoValue // public abstract class MarsWeatherResultDM { // // /** // * List of the weather report for every SOL // */ // // @SerializedName("soles") // public abstract List<Soles> weatherReportList(); // // public static TypeAdapter<MarsWeatherResultDM> typeAdapter(Gson gson) { // return new AutoValue_MarsWeatherResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/ResponseCacheInterceptor.java // public class ResponseCacheInterceptor implements Interceptor { // @Override // public Response intercept(Chain chain) throws IOException { // // Request request = chain.request(); // if(Boolean.valueOf(request.header(RestClientConstants.responseCachingFlagHeader))) { // Timber.i("Response cache applied"); // Response originalResponse = chain.proceed(chain.request()); // return originalResponse.newBuilder() // .removeHeader(RestClientConstants.responseCachingFlagHeader) // .header("Cache-Control", "public, max-age=" + (3600 * 6)) // .build(); // } else { // Timber.i("Response cache not applied"); // return chain.proceed(chain.request()); // } // } // }
import com.google.gson.GsonBuilder; import java.io.File; import io.github.krtkush.marsexplorer.BuildConfig; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.RESTClients.DataModels.WeatherJsonDataModel.MarsWeatherResultDM; import io.github.krtkush.marsexplorer.RESTClients.Interceptors.ResponseCacheInterceptor; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Header; import rx.Observable;
package io.github.krtkush.marsexplorer.RESTClients; /** * Created by kartikeykushwaha on 08/06/16. */ public class MarsWeatherClient { private static MarsWeatherInterface marsWeatherInterface; public static MarsWeatherInterface getMarsWeatherInterface() { if(marsWeatherInterface == null) { // Log level depending on build type. No logging in case of production APK HttpLoggingInterceptor.Level logLevel; if(BuildConfig.DEBUG) logLevel = HttpLoggingInterceptor.Level.BODY; else logLevel = HttpLoggingInterceptor.Level.NONE; OkHttpClient okHttpClient = new OkHttpClient.Builder() // Enable response caching .addNetworkInterceptor(new ResponseCacheInterceptor()) // Set the cache location and size (5 MB)
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/WeatherJsonDataModel/MarsWeatherResultDM.java // @AutoValue // public abstract class MarsWeatherResultDM { // // /** // * List of the weather report for every SOL // */ // // @SerializedName("soles") // public abstract List<Soles> weatherReportList(); // // public static TypeAdapter<MarsWeatherResultDM> typeAdapter(Gson gson) { // return new AutoValue_MarsWeatherResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/ResponseCacheInterceptor.java // public class ResponseCacheInterceptor implements Interceptor { // @Override // public Response intercept(Chain chain) throws IOException { // // Request request = chain.request(); // if(Boolean.valueOf(request.header(RestClientConstants.responseCachingFlagHeader))) { // Timber.i("Response cache applied"); // Response originalResponse = chain.proceed(chain.request()); // return originalResponse.newBuilder() // .removeHeader(RestClientConstants.responseCachingFlagHeader) // .header("Cache-Control", "public, max-age=" + (3600 * 6)) // .build(); // } else { // Timber.i("Response cache not applied"); // return chain.proceed(chain.request()); // } // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java import com.google.gson.GsonBuilder; import java.io.File; import io.github.krtkush.marsexplorer.BuildConfig; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.RESTClients.DataModels.WeatherJsonDataModel.MarsWeatherResultDM; import io.github.krtkush.marsexplorer.RESTClients.Interceptors.ResponseCacheInterceptor; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Header; import rx.Observable; package io.github.krtkush.marsexplorer.RESTClients; /** * Created by kartikeykushwaha on 08/06/16. */ public class MarsWeatherClient { private static MarsWeatherInterface marsWeatherInterface; public static MarsWeatherInterface getMarsWeatherInterface() { if(marsWeatherInterface == null) { // Log level depending on build type. No logging in case of production APK HttpLoggingInterceptor.Level logLevel; if(BuildConfig.DEBUG) logLevel = HttpLoggingInterceptor.Level.BODY; else logLevel = HttpLoggingInterceptor.Level.NONE; OkHttpClient okHttpClient = new OkHttpClient.Builder() // Enable response caching .addNetworkInterceptor(new ResponseCacheInterceptor()) // Set the cache location and size (5 MB)
.cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance()
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/WeatherJsonDataModel/MarsWeatherResultDM.java // @AutoValue // public abstract class MarsWeatherResultDM { // // /** // * List of the weather report for every SOL // */ // // @SerializedName("soles") // public abstract List<Soles> weatherReportList(); // // public static TypeAdapter<MarsWeatherResultDM> typeAdapter(Gson gson) { // return new AutoValue_MarsWeatherResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/ResponseCacheInterceptor.java // public class ResponseCacheInterceptor implements Interceptor { // @Override // public Response intercept(Chain chain) throws IOException { // // Request request = chain.request(); // if(Boolean.valueOf(request.header(RestClientConstants.responseCachingFlagHeader))) { // Timber.i("Response cache applied"); // Response originalResponse = chain.proceed(chain.request()); // return originalResponse.newBuilder() // .removeHeader(RestClientConstants.responseCachingFlagHeader) // .header("Cache-Control", "public, max-age=" + (3600 * 6)) // .build(); // } else { // Timber.i("Response cache not applied"); // return chain.proceed(chain.request()); // } // } // }
import com.google.gson.GsonBuilder; import java.io.File; import io.github.krtkush.marsexplorer.BuildConfig; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.RESTClients.DataModels.WeatherJsonDataModel.MarsWeatherResultDM; import io.github.krtkush.marsexplorer.RESTClients.Interceptors.ResponseCacheInterceptor; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Header; import rx.Observable;
.cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() .getCacheDir(), RestClientConstants.apiResponsesCache), 5 * 1024 * 1024)) // Enable logging .addInterceptor(new HttpLoggingInterceptor() .setLevel(logLevel)) .build(); GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( new GsonBuilder() .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) .create() ); Retrofit retrofitClient = new Retrofit.Builder() .baseUrl(RestClientConstants.marsWeatherBaseUrl) .client(okHttpClient) .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); marsWeatherInterface = retrofitClient.create(MarsWeatherInterface.class); } return marsWeatherInterface; } public interface MarsWeatherInterface { @GET("api.php")
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/WeatherJsonDataModel/MarsWeatherResultDM.java // @AutoValue // public abstract class MarsWeatherResultDM { // // /** // * List of the weather report for every SOL // */ // // @SerializedName("soles") // public abstract List<Soles> weatherReportList(); // // public static TypeAdapter<MarsWeatherResultDM> typeAdapter(Gson gson) { // return new AutoValue_MarsWeatherResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/Interceptors/ResponseCacheInterceptor.java // public class ResponseCacheInterceptor implements Interceptor { // @Override // public Response intercept(Chain chain) throws IOException { // // Request request = chain.request(); // if(Boolean.valueOf(request.header(RestClientConstants.responseCachingFlagHeader))) { // Timber.i("Response cache applied"); // Response originalResponse = chain.proceed(chain.request()); // return originalResponse.newBuilder() // .removeHeader(RestClientConstants.responseCachingFlagHeader) // .header("Cache-Control", "public, max-age=" + (3600 * 6)) // .build(); // } else { // Timber.i("Response cache not applied"); // return chain.proceed(chain.request()); // } // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/MarsWeatherClient.java import com.google.gson.GsonBuilder; import java.io.File; import io.github.krtkush.marsexplorer.BuildConfig; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.RESTClients.DataModels.WeatherJsonDataModel.MarsWeatherResultDM; import io.github.krtkush.marsexplorer.RESTClients.Interceptors.ResponseCacheInterceptor; import okhttp3.Cache; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import retrofit2.http.Header; import rx.Observable; .cache(new Cache(new File(MarsExplorerApplication.getApplicationInstance() .getCacheDir(), RestClientConstants.apiResponsesCache), 5 * 1024 * 1024)) // Enable logging .addInterceptor(new HttpLoggingInterceptor() .setLevel(logLevel)) .build(); GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create( new GsonBuilder() .registerTypeAdapterFactory(GsonTypeAdapterAdapterFactory.create()) .create() ); Retrofit retrofitClient = new Retrofit.Builder() .baseUrl(RestClientConstants.marsWeatherBaseUrl) .client(okHttpClient) .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); marsWeatherInterface = retrofitClient.create(MarsWeatherInterface.class); } return marsWeatherInterface; } public interface MarsWeatherInterface { @GET("api.php")
Observable<MarsWeatherResultDM> getLatestMarsWeather(
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/About/ShareUrlBroadcastReceiver.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.R;
package io.github.krtkush.marsexplorer.About; /** * Created by kartikeykushwaha on 25/10/16. */ public class ShareUrlBroadcastReceiver extends BroadcastReceiver { /** * Broadcast receiver to show the share pop-up. */ @Override public void onReceive(Context context, Intent intent) { String url = intent.getDataString(); if (url != null) { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, url); Intent chooserIntent = Intent.createChooser(shareIntent,
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/About/ShareUrlBroadcastReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.R; package io.github.krtkush.marsexplorer.About; /** * Created by kartikeykushwaha on 25/10/16. */ public class ShareUrlBroadcastReceiver extends BroadcastReceiver { /** * Broadcast receiver to show the share pop-up. */ @Override public void onReceive(Context context, Intent intent) { String url = intent.getDataString(); if (url != null) { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, url); Intent chooserIntent = Intent.createChooser(shareIntent,
MarsExplorerApplication.getApplicationInstance().getString(R.string.share));
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/RoverExplorerPresenterLayer.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/PhotosResultDM.java // @AutoValue // public abstract class PhotosResultDM { // // /** // * List of all the photos and their respective details taken by a rover. // */ // // @SerializedName("photos") // public abstract List<Photos> photos(); // // public static TypeAdapter<PhotosResultDM> typeAdapter(Gson gson) { // return new AutoValue_PhotosResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/RoverExplorerConstants.java // public class RoverExplorerConstants { // // // Constants for identifying data being passed via intents // public static final String roverNameExtra = "roverName"; // public static final String roverMaxSolExtra = "maxSol"; // public static final String roverSolTrackExtra = "solTrack"; // }
import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.PhotosResultDM; import io.github.krtkush.marsexplorer.RoverExplorer.RoverExplorerConstants; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber;
package io.github.krtkush.marsexplorer.RoverExplorer.ExplorerFragment; /** * Created by kartikeykushwaha on 17/07/16. */ public class RoverExplorerPresenterLayer implements RoverExplorerPresenterInteractor { private RoverExplorerFragment fragment; private String roverName; private String roverSol;
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/PhotosResultDM.java // @AutoValue // public abstract class PhotosResultDM { // // /** // * List of all the photos and their respective details taken by a rover. // */ // // @SerializedName("photos") // public abstract List<Photos> photos(); // // public static TypeAdapter<PhotosResultDM> typeAdapter(Gson gson) { // return new AutoValue_PhotosResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/RoverExplorerConstants.java // public class RoverExplorerConstants { // // // Constants for identifying data being passed via intents // public static final String roverNameExtra = "roverName"; // public static final String roverMaxSolExtra = "maxSol"; // public static final String roverSolTrackExtra = "solTrack"; // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/RoverExplorerPresenterLayer.java import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.PhotosResultDM; import io.github.krtkush.marsexplorer.RoverExplorer.RoverExplorerConstants; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber; package io.github.krtkush.marsexplorer.RoverExplorer.ExplorerFragment; /** * Created by kartikeykushwaha on 17/07/16. */ public class RoverExplorerPresenterLayer implements RoverExplorerPresenterInteractor { private RoverExplorerFragment fragment; private String roverName; private String roverSol;
private Subscriber<PhotosResultDM> nasaMarsPhotoSubscriber;
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/RoverExplorerPresenterLayer.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/PhotosResultDM.java // @AutoValue // public abstract class PhotosResultDM { // // /** // * List of all the photos and their respective details taken by a rover. // */ // // @SerializedName("photos") // public abstract List<Photos> photos(); // // public static TypeAdapter<PhotosResultDM> typeAdapter(Gson gson) { // return new AutoValue_PhotosResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/RoverExplorerConstants.java // public class RoverExplorerConstants { // // // Constants for identifying data being passed via intents // public static final String roverNameExtra = "roverName"; // public static final String roverMaxSolExtra = "maxSol"; // public static final String roverSolTrackExtra = "solTrack"; // }
import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.PhotosResultDM; import io.github.krtkush.marsexplorer.RoverExplorer.RoverExplorerConstants; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber;
package io.github.krtkush.marsexplorer.RoverExplorer.ExplorerFragment; /** * Created by kartikeykushwaha on 17/07/16. */ public class RoverExplorerPresenterLayer implements RoverExplorerPresenterInteractor { private RoverExplorerFragment fragment; private String roverName; private String roverSol; private Subscriber<PhotosResultDM> nasaMarsPhotoSubscriber; // Variables related to RecyclerView private PhotosRecyclerViewAdapter photosRecyclerViewAdapter; // List of all the photos and their respective details
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/PhotosResultDM.java // @AutoValue // public abstract class PhotosResultDM { // // /** // * List of all the photos and their respective details taken by a rover. // */ // // @SerializedName("photos") // public abstract List<Photos> photos(); // // public static TypeAdapter<PhotosResultDM> typeAdapter(Gson gson) { // return new AutoValue_PhotosResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/RoverExplorerConstants.java // public class RoverExplorerConstants { // // // Constants for identifying data being passed via intents // public static final String roverNameExtra = "roverName"; // public static final String roverMaxSolExtra = "maxSol"; // public static final String roverSolTrackExtra = "solTrack"; // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/RoverExplorerPresenterLayer.java import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.PhotosResultDM; import io.github.krtkush.marsexplorer.RoverExplorer.RoverExplorerConstants; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber; package io.github.krtkush.marsexplorer.RoverExplorer.ExplorerFragment; /** * Created by kartikeykushwaha on 17/07/16. */ public class RoverExplorerPresenterLayer implements RoverExplorerPresenterInteractor { private RoverExplorerFragment fragment; private String roverName; private String roverSol; private Subscriber<PhotosResultDM> nasaMarsPhotoSubscriber; // Variables related to RecyclerView private PhotosRecyclerViewAdapter photosRecyclerViewAdapter; // List of all the photos and their respective details
private List<Photos> photoList;
krtkush/MarsExplorer
app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/RoverExplorerPresenterLayer.java
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/PhotosResultDM.java // @AutoValue // public abstract class PhotosResultDM { // // /** // * List of all the photos and their respective details taken by a rover. // */ // // @SerializedName("photos") // public abstract List<Photos> photos(); // // public static TypeAdapter<PhotosResultDM> typeAdapter(Gson gson) { // return new AutoValue_PhotosResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/RoverExplorerConstants.java // public class RoverExplorerConstants { // // // Constants for identifying data being passed via intents // public static final String roverNameExtra = "roverName"; // public static final String roverMaxSolExtra = "maxSol"; // public static final String roverSolTrackExtra = "solTrack"; // }
import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.PhotosResultDM; import io.github.krtkush.marsexplorer.RoverExplorer.RoverExplorerConstants; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber;
// Define the action when user pulls down to refresh. swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { fragment.toggleSwipeRefreshing(false); getRoverPhotos(false); } }); } @Override public void unsubscribeRoverPhotosRequest() { if(nasaMarsPhotoSubscriber != null) nasaMarsPhotoSubscriber.unsubscribe(); // Also, stop the handler which is responsible for the delay in API call. if(fetchPhotosHandler != null) fetchPhotosHandler.removeCallbacks(fetchPhotosRunnable); } /** * Method to make the API call. * Always call this method via getRoverPhotos(flag) method not directly. */ private void requestPhotosApiCall() { // Define the observer Observable<PhotosResultDM> nasaMarsPhotosObservable
// Path: app/src/main/java/io/github/krtkush/marsexplorer/MarsExplorerApplication.java // public class MarsExplorerApplication extends Application { // // // Variable that holds instance of the application class // private static MarsExplorerApplication marsExplorerApplicationInstance; // // Variable that holds instance of the photos API interface // private NASARestApiClient.NASAMarsPhotosApiInterface nasaMarsPhotosApiInterface; // // Variable to hold instance of the weather API interface // private MarsWeatherClient.MarsWeatherInterface marsWeatherInterface; // // @Override // public void onCreate() { // super.onCreate(); // // marsExplorerApplicationInstance = this; // // // Initialize the API interfaces. // nasaMarsPhotosApiInterface = NASARestApiClient.getNasaMarsPhotosApiInterface(); // marsWeatherInterface = MarsWeatherClient.getMarsWeatherInterface(); // // // Initialize calligraphy with the preferred font. // CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() // .setDefaultFontPath("fonts/Lato-Regular.ttf") // .setFontAttrId(R.attr.fontPath) // .build() // ); // // // Initialize timber logging tool only if in debug mode. // if(BuildConfig.DEBUG) // Timber.plant(new Timber.DebugTree()); // // // Initialize picasso cache indicator and logging only if in debug mode. // if(BuildConfig.DEBUG) { // Picasso // .with(marsExplorerApplicationInstance) // .setIndicatorsEnabled(true); // // Picasso // .with(marsExplorerApplicationInstance) // .setLoggingEnabled(true); // } // // // Initialize Leak Canary only if in debug mode. // if(BuildConfig.DEBUG) // LeakCanary.install(this); // // // Initialize fabric only if NOT in debug mode. // /* if(!BuildConfig.DEBUG) // Fabric.with(this, new Crashlytics());*/ // } // // /** // * @return Instance of the application class (App Context) // */ // public static MarsExplorerApplication getApplicationInstance() { // return marsExplorerApplicationInstance; // } // // /** // * @return Instance of the NASAMarsPhotosApiInterface // */ // public NASARestApiClient.NASAMarsPhotosApiInterface getNasaMarsPhotosApiInterface() { // return nasaMarsPhotosApiInterface; // } // // /** // * @return Instance of MarsWeatherInterface // */ // public MarsWeatherClient.MarsWeatherInterface getMarsWeatherInterface() { // return marsWeatherInterface; // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/Photos.java // @AutoValue // public abstract class Photos { // // /** // *Details of the image taken by the rover // */ // // @SerializedName("id") // public abstract Integer id(); // // @SerializedName("sol") // public abstract Integer sol(); // // @SerializedName("img_src") // public abstract String imgSource(); // // @SerializedName("earth_date") // public abstract String earthDate(); // // @SerializedName("rover") // public abstract Rover rover(); // // @SerializedName("camera") // public abstract Camera camera(); // // public static TypeAdapter<Photos> typeAdapter(Gson gson) { // return new AutoValue_Photos.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RESTClients/DataModels/PhotosJsonDataModels/PhotosResultDM.java // @AutoValue // public abstract class PhotosResultDM { // // /** // * List of all the photos and their respective details taken by a rover. // */ // // @SerializedName("photos") // public abstract List<Photos> photos(); // // public static TypeAdapter<PhotosResultDM> typeAdapter(Gson gson) { // return new AutoValue_PhotosResultDM.GsonTypeAdapter(gson); // } // } // // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/RoverExplorerConstants.java // public class RoverExplorerConstants { // // // Constants for identifying data being passed via intents // public static final String roverNameExtra = "roverName"; // public static final String roverMaxSolExtra = "maxSol"; // public static final String roverSolTrackExtra = "solTrack"; // } // Path: app/src/main/java/io/github/krtkush/marsexplorer/RoverExplorer/ExplorerFragment/RoverExplorerPresenterLayer.java import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import java.util.ArrayList; import java.util.List; import io.github.krtkush.marsexplorer.MarsExplorerApplication; import io.github.krtkush.marsexplorer.R; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.Photos; import io.github.krtkush.marsexplorer.RESTClients.DataModels.PhotosJsonDataModels.PhotosResultDM; import io.github.krtkush.marsexplorer.RoverExplorer.RoverExplorerConstants; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber; // Define the action when user pulls down to refresh. swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { fragment.toggleSwipeRefreshing(false); getRoverPhotos(false); } }); } @Override public void unsubscribeRoverPhotosRequest() { if(nasaMarsPhotoSubscriber != null) nasaMarsPhotoSubscriber.unsubscribe(); // Also, stop the handler which is responsible for the delay in API call. if(fetchPhotosHandler != null) fetchPhotosHandler.removeCallbacks(fetchPhotosRunnable); } /** * Method to make the API call. * Always call this method via getRoverPhotos(flag) method not directly. */ private void requestPhotosApiCall() { // Define the observer Observable<PhotosResultDM> nasaMarsPhotosObservable
= MarsExplorerApplication.getApplicationInstance()