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 |
|---|---|---|---|---|---|---|
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/service/OAuthLoginSuccess.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationCreatedHandler.java
// @Component
// @NextRTCEventListener(CONVERSATION_CREATED)
// public class ConversationCreatedHandler extends ConversationHandler {
//
// private static final Logger log = Logger.getLogger(ConversationCreatedHandler.class);
// @Autowired
// private ConversationRepository repo;
//
// @Override
// protected void handleEvent(NextRTCConversation rtcConversation, NextRTCEvent event) {
// Conversation conversation = repo.getByConversationName(rtcConversation.getId());
// if (conversation == null) {
// log.info("Created conversation: " + repo.save(new Conversation(rtcConversation.getId())));
// }
// }
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.ConversationCreatedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Map; | package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class OAuthLoginSuccess implements ApplicationListener<InteractiveAuthenticationSuccessEvent> { | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationCreatedHandler.java
// @Component
// @NextRTCEventListener(CONVERSATION_CREATED)
// public class ConversationCreatedHandler extends ConversationHandler {
//
// private static final Logger log = Logger.getLogger(ConversationCreatedHandler.class);
// @Autowired
// private ConversationRepository repo;
//
// @Override
// protected void handleEvent(NextRTCConversation rtcConversation, NextRTCEvent event) {
// Conversation conversation = repo.getByConversationName(rtcConversation.getId());
// if (conversation == null) {
// log.info("Created conversation: " + repo.save(new Conversation(rtcConversation.getId())));
// }
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/OAuthLoginSuccess.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.ConversationCreatedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Map;
package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class OAuthLoginSuccess implements ApplicationListener<InteractiveAuthenticationSuccessEvent> { | private static final Logger log = Logger.getLogger(ConversationCreatedHandler.class); |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/SessionOpenedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionOpenedService.java
// @Service
// @Transactional
// @PreAuthorize(value = "USER")
// public class SessionOpenedService {
//
// private static final Logger log = Logger.getLogger(SessionOpenedService.class);
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private AuthUtils authUtils;
//
// public void execute(NextRTCMember member) {
// User user = authUtils.getAuthenticatedUser(member.getSession().getUserPrincipal());
//
// createConversationMemberFor(member.getId(), user);
// }
//
// private void createConversationMemberFor(String memberId, User user) {
// log.info("Created member: " + memberRepository.save(new Member(memberId, user)));
// }
//
// }
| import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.SessionOpenedService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static org.nextrtc.signalingserver.api.NextRTCEvents.SESSION_OPENED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Service
@NextRTCEventListener(SESSION_OPENED) | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionOpenedService.java
// @Service
// @Transactional
// @PreAuthorize(value = "USER")
// public class SessionOpenedService {
//
// private static final Logger log = Logger.getLogger(SessionOpenedService.class);
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private AuthUtils authUtils;
//
// public void execute(NextRTCMember member) {
// User user = authUtils.getAuthenticatedUser(member.getSession().getUserPrincipal());
//
// createConversationMemberFor(member.getId(), user);
// }
//
// private void createConversationMemberFor(String memberId, User user) {
// log.info("Created member: " + memberRepository.save(new Member(memberId, user)));
// }
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/SessionOpenedHandler.java
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.SessionOpenedService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static org.nextrtc.signalingserver.api.NextRTCEvents.SESSION_OPENED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Service
@NextRTCEventListener(SESSION_OPENED) | public class SessionOpenedHandler extends FromMemberHandler { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/SessionOpenedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionOpenedService.java
// @Service
// @Transactional
// @PreAuthorize(value = "USER")
// public class SessionOpenedService {
//
// private static final Logger log = Logger.getLogger(SessionOpenedService.class);
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private AuthUtils authUtils;
//
// public void execute(NextRTCMember member) {
// User user = authUtils.getAuthenticatedUser(member.getSession().getUserPrincipal());
//
// createConversationMemberFor(member.getId(), user);
// }
//
// private void createConversationMemberFor(String memberId, User user) {
// log.info("Created member: " + memberRepository.save(new Member(memberId, user)));
// }
//
// }
| import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.SessionOpenedService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static org.nextrtc.signalingserver.api.NextRTCEvents.SESSION_OPENED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Service
@NextRTCEventListener(SESSION_OPENED)
public class SessionOpenedHandler extends FromMemberHandler {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionOpenedService.java
// @Service
// @Transactional
// @PreAuthorize(value = "USER")
// public class SessionOpenedService {
//
// private static final Logger log = Logger.getLogger(SessionOpenedService.class);
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private AuthUtils authUtils;
//
// public void execute(NextRTCMember member) {
// User user = authUtils.getAuthenticatedUser(member.getSession().getUserPrincipal());
//
// createConversationMemberFor(member.getId(), user);
// }
//
// private void createConversationMemberFor(String memberId, User user) {
// log.info("Created member: " + memberRepository.save(new Member(memberId, user)));
// }
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/SessionOpenedHandler.java
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.SessionOpenedService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static org.nextrtc.signalingserver.api.NextRTCEvents.SESSION_OPENED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Service
@NextRTCEventListener(SESSION_OPENED)
public class SessionOpenedHandler extends FromMemberHandler {
@Autowired | private SessionOpenedService service; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/SessionClosedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionClosedService.java
// @Service
// @Transactional
// public class SessionClosedService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// public void execute(String memberId, Optional<String> reasonOfClose) {
// memberRepository.getByRtcId(memberId).disconnectWithReason(reasonOfClose);
// }
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.SessionClosedService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.SESSION_CLOSED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(SESSION_CLOSED) | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionClosedService.java
// @Service
// @Transactional
// public class SessionClosedService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// public void execute(String memberId, Optional<String> reasonOfClose) {
// memberRepository.getByRtcId(memberId).disconnectWithReason(reasonOfClose);
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/SessionClosedHandler.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.SessionClosedService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.SESSION_CLOSED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(SESSION_CLOSED) | public class SessionClosedHandler extends FromMemberHandler { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/SessionClosedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionClosedService.java
// @Service
// @Transactional
// public class SessionClosedService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// public void execute(String memberId, Optional<String> reasonOfClose) {
// memberRepository.getByRtcId(memberId).disconnectWithReason(reasonOfClose);
// }
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.SessionClosedService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.SESSION_CLOSED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(SESSION_CLOSED)
public class SessionClosedHandler extends FromMemberHandler {
private static final Logger log = Logger.getLogger(SessionClosedHandler.class);
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionClosedService.java
// @Service
// @Transactional
// public class SessionClosedService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// public void execute(String memberId, Optional<String> reasonOfClose) {
// memberRepository.getByRtcId(memberId).disconnectWithReason(reasonOfClose);
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/SessionClosedHandler.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.SessionClosedService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.SESSION_CLOSED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(SESSION_CLOSED)
public class SessionClosedHandler extends FromMemberHandler {
private static final Logger log = Logger.getLogger(SessionClosedHandler.class);
@Autowired | private SessionClosedService service; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/auth/AuthUtils.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
| import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.security.Principal;
import java.util.Optional; | package org.nextrtc.examples.videochat_with_rest.auth;
@Service
public class AuthUtils {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/auth/AuthUtils.java
import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.security.Principal;
import java.util.Optional;
package org.nextrtc.examples.videochat_with_rest.auth;
@Service
public class AuthUtils {
@Autowired | private UserRepository userRepository; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/auth/AuthUtils.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
| import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.security.Principal;
import java.util.Optional; | package org.nextrtc.examples.videochat_with_rest.auth;
@Service
public class AuthUtils {
@Autowired
private UserRepository userRepository;
| // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/auth/AuthUtils.java
import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.security.Principal;
import java.util.Optional;
package org.nextrtc.examples.videochat_with_rest.auth;
@Service
public class AuthUtils {
@Autowired
private UserRepository userRepository;
| public User getAuthenticatedUser(Principal userPrincipal) { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/service/RegisterUserService.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.UUID; | package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class RegisterUserService {
private static final Logger log = Logger.getLogger(RegisterUserService.class);
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/RegisterUserService.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.UUID;
package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class RegisterUserService {
private static final Logger log = Logger.getLogger(RegisterUserService.class);
@Autowired | private UserRepository userRepository; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/service/RegisterUserService.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.UUID; | package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class RegisterUserService {
private static final Logger log = Logger.getLogger(RegisterUserService.class);
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder encoder;
public String generateConfirmationKey() {
return UUID.randomUUID().toString();
}
public void register(String username, String password, String email, String confirmationKey) {
if (userRepository.findByUsername(username).isPresent()) {
throw new RuntimeException("user exists!");
}
if (userRepository.findByEmail(email).isPresent()) {
throw new RuntimeException("email is occupied!");
}
| // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/RegisterUserService.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.UUID;
package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class RegisterUserService {
private static final Logger log = Logger.getLogger(RegisterUserService.class);
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder encoder;
public String generateConfirmationKey() {
return UUID.randomUUID().toString();
}
public void register(String username, String password, String email, String confirmationKey) {
if (userRepository.findByUsername(username).isPresent()) {
throw new RuntimeException("user exists!");
}
if (userRepository.findByEmail(email).isPresent()) {
throw new RuntimeException("email is occupied!");
}
| User user = new User(username, encoder.encode(password), email, confirmationKey); |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/config/NextRTCEndpointConfig.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/MyEndpoint.java
// @ServerEndpoint(value = "/signaling",//
// decoders = MessageDecoder.class,//
// encoders = MessageEncoder.class)
// public class MyEndpoint extends NextRTCEndpoint {
// }
| import org.nextrtc.examples.videochat_with_rest.MyEndpoint;
import org.nextrtc.signalingserver.NextRTCConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; | package org.nextrtc.examples.videochat_with_rest.config;
@Configuration
@Import(NextRTCConfig.class)
public class NextRTCEndpointConfig {
@Bean | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/MyEndpoint.java
// @ServerEndpoint(value = "/signaling",//
// decoders = MessageDecoder.class,//
// encoders = MessageEncoder.class)
// public class MyEndpoint extends NextRTCEndpoint {
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/config/NextRTCEndpointConfig.java
import org.nextrtc.examples.videochat_with_rest.MyEndpoint;
import org.nextrtc.signalingserver.NextRTCConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
package org.nextrtc.examples.videochat_with_rest.config;
@Configuration
@Import(NextRTCConfig.class)
public class NextRTCEndpointConfig {
@Bean | public MyEndpoint myEndpoint() { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/controller/VerificationController.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/VerifyUserService.java
// @Service
// @Transactional
// public class VerifyUserService {
//
// @Autowired
// private UserRepository userRepository;
//
// public boolean verify(String key) {
// Optional<User> confirmationKey = userRepository.findByConfirmationKey(key);
// confirmationKey.ifPresent(User::confirmEmail);
// return confirmationKey.isPresent();
// }
// }
| import org.nextrtc.examples.videochat_with_rest.service.VerifyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; | package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action/verify")
public class VerificationController {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/VerifyUserService.java
// @Service
// @Transactional
// public class VerifyUserService {
//
// @Autowired
// private UserRepository userRepository;
//
// public boolean verify(String key) {
// Optional<User> confirmationKey = userRepository.findByConfirmationKey(key);
// confirmationKey.ifPresent(User::confirmEmail);
// return confirmationKey.isPresent();
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/controller/VerificationController.java
import org.nextrtc.examples.videochat_with_rest.service.VerifyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action/verify")
public class VerificationController {
@Autowired | private VerifyUserService service; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationCreatedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Conversation.java
// @Entity
// @Table(name = "Conversations")
// public class Conversation {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "conversation_id")
// private int id;
//
// @Column(name = "conversation_name")
// private String conversationName;
//
// @Column(name = "created")
// private Date created;
//
// @Column(name = "destroyed")
// private Date destroyed;
//
// @OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// private Set<Connection> connections;
//
// @Deprecated
// Conversation() {
// }
//
// public Conversation(String conversationName) {
// this.conversationName = conversationName;
// created = now().toDate();
// }
//
// @Override
// public String toString() {
// return String.format("(%s)[%s - %s]", conversationName, created, destroyed);
// }
//
// public void destroy() {
// destroyed = now().toDate();
// connections.stream()
// .filter(Connection::isClosed)
// .forEach(Connection::close);
// }
//
// public void join(Member member) {
// connections.add(new Connection(this, member));
// }
//
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Conversation)) return false;
// final Conversation other = (Conversation) o;
// return other.id == id;
// }
//
// public int hashCode() {
// return id;
// }
//
// public Set<Connection> getConnections() {
// return connections;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java
// @Repository
// @Transactional
// public interface ConversationRepository extends JpaRepository<Conversation, Integer> {
//
// @Query("select c from Conversation c where c.destroyed is null and c.conversationName = :conversationName")
// Conversation getByConversationName(@Param("conversationName") String conversationName);
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.Conversation;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.repo.ConversationRepository;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_CREATED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_CREATED) | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Conversation.java
// @Entity
// @Table(name = "Conversations")
// public class Conversation {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "conversation_id")
// private int id;
//
// @Column(name = "conversation_name")
// private String conversationName;
//
// @Column(name = "created")
// private Date created;
//
// @Column(name = "destroyed")
// private Date destroyed;
//
// @OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// private Set<Connection> connections;
//
// @Deprecated
// Conversation() {
// }
//
// public Conversation(String conversationName) {
// this.conversationName = conversationName;
// created = now().toDate();
// }
//
// @Override
// public String toString() {
// return String.format("(%s)[%s - %s]", conversationName, created, destroyed);
// }
//
// public void destroy() {
// destroyed = now().toDate();
// connections.stream()
// .filter(Connection::isClosed)
// .forEach(Connection::close);
// }
//
// public void join(Member member) {
// connections.add(new Connection(this, member));
// }
//
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Conversation)) return false;
// final Conversation other = (Conversation) o;
// return other.id == id;
// }
//
// public int hashCode() {
// return id;
// }
//
// public Set<Connection> getConnections() {
// return connections;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java
// @Repository
// @Transactional
// public interface ConversationRepository extends JpaRepository<Conversation, Integer> {
//
// @Query("select c from Conversation c where c.destroyed is null and c.conversationName = :conversationName")
// Conversation getByConversationName(@Param("conversationName") String conversationName);
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationCreatedHandler.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.Conversation;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.repo.ConversationRepository;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_CREATED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_CREATED) | public class ConversationCreatedHandler extends ConversationHandler { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationCreatedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Conversation.java
// @Entity
// @Table(name = "Conversations")
// public class Conversation {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "conversation_id")
// private int id;
//
// @Column(name = "conversation_name")
// private String conversationName;
//
// @Column(name = "created")
// private Date created;
//
// @Column(name = "destroyed")
// private Date destroyed;
//
// @OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// private Set<Connection> connections;
//
// @Deprecated
// Conversation() {
// }
//
// public Conversation(String conversationName) {
// this.conversationName = conversationName;
// created = now().toDate();
// }
//
// @Override
// public String toString() {
// return String.format("(%s)[%s - %s]", conversationName, created, destroyed);
// }
//
// public void destroy() {
// destroyed = now().toDate();
// connections.stream()
// .filter(Connection::isClosed)
// .forEach(Connection::close);
// }
//
// public void join(Member member) {
// connections.add(new Connection(this, member));
// }
//
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Conversation)) return false;
// final Conversation other = (Conversation) o;
// return other.id == id;
// }
//
// public int hashCode() {
// return id;
// }
//
// public Set<Connection> getConnections() {
// return connections;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java
// @Repository
// @Transactional
// public interface ConversationRepository extends JpaRepository<Conversation, Integer> {
//
// @Query("select c from Conversation c where c.destroyed is null and c.conversationName = :conversationName")
// Conversation getByConversationName(@Param("conversationName") String conversationName);
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.Conversation;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.repo.ConversationRepository;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_CREATED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_CREATED)
public class ConversationCreatedHandler extends ConversationHandler {
private static final Logger log = Logger.getLogger(ConversationCreatedHandler.class);
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Conversation.java
// @Entity
// @Table(name = "Conversations")
// public class Conversation {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "conversation_id")
// private int id;
//
// @Column(name = "conversation_name")
// private String conversationName;
//
// @Column(name = "created")
// private Date created;
//
// @Column(name = "destroyed")
// private Date destroyed;
//
// @OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// private Set<Connection> connections;
//
// @Deprecated
// Conversation() {
// }
//
// public Conversation(String conversationName) {
// this.conversationName = conversationName;
// created = now().toDate();
// }
//
// @Override
// public String toString() {
// return String.format("(%s)[%s - %s]", conversationName, created, destroyed);
// }
//
// public void destroy() {
// destroyed = now().toDate();
// connections.stream()
// .filter(Connection::isClosed)
// .forEach(Connection::close);
// }
//
// public void join(Member member) {
// connections.add(new Connection(this, member));
// }
//
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Conversation)) return false;
// final Conversation other = (Conversation) o;
// return other.id == id;
// }
//
// public int hashCode() {
// return id;
// }
//
// public Set<Connection> getConnections() {
// return connections;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java
// @Repository
// @Transactional
// public interface ConversationRepository extends JpaRepository<Conversation, Integer> {
//
// @Query("select c from Conversation c where c.destroyed is null and c.conversationName = :conversationName")
// Conversation getByConversationName(@Param("conversationName") String conversationName);
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationCreatedHandler.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.Conversation;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.repo.ConversationRepository;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_CREATED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_CREATED)
public class ConversationCreatedHandler extends ConversationHandler {
private static final Logger log = Logger.getLogger(ConversationCreatedHandler.class);
@Autowired | private ConversationRepository repo; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationCreatedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Conversation.java
// @Entity
// @Table(name = "Conversations")
// public class Conversation {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "conversation_id")
// private int id;
//
// @Column(name = "conversation_name")
// private String conversationName;
//
// @Column(name = "created")
// private Date created;
//
// @Column(name = "destroyed")
// private Date destroyed;
//
// @OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// private Set<Connection> connections;
//
// @Deprecated
// Conversation() {
// }
//
// public Conversation(String conversationName) {
// this.conversationName = conversationName;
// created = now().toDate();
// }
//
// @Override
// public String toString() {
// return String.format("(%s)[%s - %s]", conversationName, created, destroyed);
// }
//
// public void destroy() {
// destroyed = now().toDate();
// connections.stream()
// .filter(Connection::isClosed)
// .forEach(Connection::close);
// }
//
// public void join(Member member) {
// connections.add(new Connection(this, member));
// }
//
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Conversation)) return false;
// final Conversation other = (Conversation) o;
// return other.id == id;
// }
//
// public int hashCode() {
// return id;
// }
//
// public Set<Connection> getConnections() {
// return connections;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java
// @Repository
// @Transactional
// public interface ConversationRepository extends JpaRepository<Conversation, Integer> {
//
// @Query("select c from Conversation c where c.destroyed is null and c.conversationName = :conversationName")
// Conversation getByConversationName(@Param("conversationName") String conversationName);
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.Conversation;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.repo.ConversationRepository;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_CREATED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_CREATED)
public class ConversationCreatedHandler extends ConversationHandler {
private static final Logger log = Logger.getLogger(ConversationCreatedHandler.class);
@Autowired
private ConversationRepository repo;
@Override
protected void handleEvent(NextRTCConversation rtcConversation, NextRTCEvent event) { | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Conversation.java
// @Entity
// @Table(name = "Conversations")
// public class Conversation {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "conversation_id")
// private int id;
//
// @Column(name = "conversation_name")
// private String conversationName;
//
// @Column(name = "created")
// private Date created;
//
// @Column(name = "destroyed")
// private Date destroyed;
//
// @OneToMany(mappedBy = "conversation", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
// private Set<Connection> connections;
//
// @Deprecated
// Conversation() {
// }
//
// public Conversation(String conversationName) {
// this.conversationName = conversationName;
// created = now().toDate();
// }
//
// @Override
// public String toString() {
// return String.format("(%s)[%s - %s]", conversationName, created, destroyed);
// }
//
// public void destroy() {
// destroyed = now().toDate();
// connections.stream()
// .filter(Connection::isClosed)
// .forEach(Connection::close);
// }
//
// public void join(Member member) {
// connections.add(new Connection(this, member));
// }
//
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Conversation)) return false;
// final Conversation other = (Conversation) o;
// return other.id == id;
// }
//
// public int hashCode() {
// return id;
// }
//
// public Set<Connection> getConnections() {
// return connections;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/ConversationRepository.java
// @Repository
// @Transactional
// public interface ConversationRepository extends JpaRepository<Conversation, Integer> {
//
// @Query("select c from Conversation c where c.destroyed is null and c.conversationName = :conversationName")
// Conversation getByConversationName(@Param("conversationName") String conversationName);
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationCreatedHandler.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.Conversation;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.repo.ConversationRepository;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_CREATED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_CREATED)
public class ConversationCreatedHandler extends ConversationHandler {
private static final Logger log = Logger.getLogger(ConversationCreatedHandler.class);
@Autowired
private ConversationRepository repo;
@Override
protected void handleEvent(NextRTCConversation rtcConversation, NextRTCEvent event) { | Conversation conversation = repo.getByConversationName(rtcConversation.getId()); |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/service/VerifyUserService.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
| import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Optional; | package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class VerifyUserService {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/VerifyUserService.java
import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Optional;
package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class VerifyUserService {
@Autowired | private UserRepository userRepository; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/service/VerifyUserService.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
| import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Optional; | package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class VerifyUserService {
@Autowired
private UserRepository userRepository;
public boolean verify(String key) { | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
// @Entity
// @Table(name = "Users")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "user_id")
// private int id;
//
// @Column(name = "username")
// private String username;
//
// @Column(name = "password")
// private String password;
//
// @Column(name = "auth_provider_id")
// private String authProviderId;
//
// @Column(name = "confirmation_key")
// private String confirmationKey;
//
// @Column(name = "role")
// private String role = "USER";
//
// @Column(name = "email")
// private String email;
//
// @Column(name = "confirmed")
// private boolean confirmed = false;
//
// @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
// private Set<Member> conversationMember;
//
// @Deprecated
// User() {
// }
//
// public User(String username, String password, String email, String confirmationKey) {
// this.username = username;
// this.password = password;
// this.email = email;
// this.confirmationKey = confirmationKey;
// }
//
// public User(String username, String email, String authProviderId) {
// this.username = username;
// this.email = email;
// this.authProviderId = authProviderId;
// confirmed = true;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void confirmEmail() {
// confirmed = true;
// }
//
// public History prepareHistory() {
// return new History(conversationMember);
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/UserRepository.java
// @org.springframework.stereotype.Repository
// @RepositoryRestResource(exported = false)
// @Transactional
// public interface UserRepository extends JpaRepository<User, Integer> {
//
// Optional<User> findByUsername(@Param("username") String username);
//
// Optional<User> findByEmail(@Param("email") String email);
//
// Optional<User> findByConfirmationKey(@Param("confirmationKey") String key);
//
// Optional<User> findByAuthProviderId(@Param("authProviderId") String key);
//
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/VerifyUserService.java
import org.nextrtc.examples.videochat_with_rest.domain.User;
import org.nextrtc.examples.videochat_with_rest.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Optional;
package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class VerifyUserService {
@Autowired
private UserRepository userRepository;
public boolean verify(String key) { | Optional<User> confirmationKey = userRepository.findByConfirmationKey(key); |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/History.java
// public class History {
//
// private List<Call> calls;
//
// public History(Set<Member> conversationMember) {
// List<Member> sortedMembers = new ArrayList<>(conversationMember);
// sortedMembers.sort(Member::startedBefore);
// calls = sortedMembers.stream().map(Member::toCall).collect(toList());
// }
//
// public List<Call> getCalls() {
// return calls;
// }
// }
| import org.nextrtc.examples.videochat_with_rest.domain.history.History;
import javax.persistence.*;
import java.util.Set; |
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private Set<Member> conversationMember;
@Deprecated
User() {
}
public User(String username, String password, String email, String confirmationKey) {
this.username = username;
this.password = password;
this.email = email;
this.confirmationKey = confirmationKey;
}
public User(String username, String email, String authProviderId) {
this.username = username;
this.email = email;
this.authProviderId = authProviderId;
confirmed = true;
}
public String getUsername() {
return username;
}
public void confirmEmail() {
confirmed = true;
}
| // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/History.java
// public class History {
//
// private List<Call> calls;
//
// public History(Set<Member> conversationMember) {
// List<Member> sortedMembers = new ArrayList<>(conversationMember);
// sortedMembers.sort(Member::startedBefore);
// calls = sortedMembers.stream().map(Member::toCall).collect(toList());
// }
//
// public List<Call> getCalls() {
// return calls;
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/User.java
import org.nextrtc.examples.videochat_with_rest.domain.history.History;
import javax.persistence.*;
import java.util.Set;
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private Set<Member> conversationMember;
@Deprecated
User() {
}
public User(String username, String password, String email, String confirmationKey) {
this.username = username;
this.password = password;
this.email = email;
this.confirmationKey = confirmationKey;
}
public User(String username, String email, String authProviderId) {
this.username = username;
this.email = email;
this.authProviderId = authProviderId;
confirmed = true;
}
public String getUsername() {
return username;
}
public void confirmEmail() {
confirmed = true;
}
| public History prepareHistory() { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/repo/MemberRepository.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Member.java
// @Entity
// @Table(name = "Members")
// public class Member {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "member_id")
// private int id;
//
// @Column(name = "member_rtc_id")
// private String rtcId;
//
// @Column(name = "connected")
// private Date connected;
//
// @Column(name = "disconnected")
// private Date disconnected;
//
// @Column(name = "left_reason")
// private String leftReason;
//
// @OneToOne(mappedBy = "member", fetch = FetchType.LAZY)
// private Connection connection;
//
// @ManyToOne
// @JoinColumn(name = "user_id")
// private User user;
//
// /**
// * for hibernate only
// */
// @Deprecated
// Member() {
// }
//
// public Member(String memberId, User user) {
// this.rtcId = memberId;
// this.user = user;
// this.connected = now().toDate();
// }
//
// public void disconnectWithReason(Optional<String> reason) {
// disconnected = now().toDate();
// reason.ifPresent(this::setLeftReason);
// }
//
// @Override
// public String toString() {
// return String.format("(%s, %s)[%s - %s]", id, rtcId, connected, disconnected);
// }
//
// public void leaves(Conversation conversation) {
// if (connection.isFor(conversation)) {
// connection.close();
// }
// }
//
// private void setLeftReason(String leftReason) {
// this.leftReason = leftReason;
// }
//
// public int startedBefore(Member p) {
// return connected.compareTo(p.connected);
// }
//
// public Call toCall() {
// if (connection != null) {
// List<String> members = connection.getConversationMembers().stream()
// .filter(m -> !m.equals(this))
// .map(m -> m.rtcId)
// .collect(toList());
// return new Call(members, !connection.isClosed(), connection.getBegin(), connection.getDuration());
// } else {
// return new Call(new ArrayList<>(), false, connected, getDuration());
// }
// }
//
// private long getDuration() {
// if (disconnected == null) {
// return new Interval(new DateTime(connected), DateTime.now()).toDurationMillis();
// }
// return new Interval(new DateTime(connected), new DateTime(disconnected)).toDurationMillis();
// }
//
// public String getUsername() {
// return user.getUsername();
// }
// }
| import org.nextrtc.examples.videochat_with_rest.domain.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional; | package org.nextrtc.examples.videochat_with_rest.repo;
@Repository
@Transactional | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Member.java
// @Entity
// @Table(name = "Members")
// public class Member {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "member_id")
// private int id;
//
// @Column(name = "member_rtc_id")
// private String rtcId;
//
// @Column(name = "connected")
// private Date connected;
//
// @Column(name = "disconnected")
// private Date disconnected;
//
// @Column(name = "left_reason")
// private String leftReason;
//
// @OneToOne(mappedBy = "member", fetch = FetchType.LAZY)
// private Connection connection;
//
// @ManyToOne
// @JoinColumn(name = "user_id")
// private User user;
//
// /**
// * for hibernate only
// */
// @Deprecated
// Member() {
// }
//
// public Member(String memberId, User user) {
// this.rtcId = memberId;
// this.user = user;
// this.connected = now().toDate();
// }
//
// public void disconnectWithReason(Optional<String> reason) {
// disconnected = now().toDate();
// reason.ifPresent(this::setLeftReason);
// }
//
// @Override
// public String toString() {
// return String.format("(%s, %s)[%s - %s]", id, rtcId, connected, disconnected);
// }
//
// public void leaves(Conversation conversation) {
// if (connection.isFor(conversation)) {
// connection.close();
// }
// }
//
// private void setLeftReason(String leftReason) {
// this.leftReason = leftReason;
// }
//
// public int startedBefore(Member p) {
// return connected.compareTo(p.connected);
// }
//
// public Call toCall() {
// if (connection != null) {
// List<String> members = connection.getConversationMembers().stream()
// .filter(m -> !m.equals(this))
// .map(m -> m.rtcId)
// .collect(toList());
// return new Call(members, !connection.isClosed(), connection.getBegin(), connection.getDuration());
// } else {
// return new Call(new ArrayList<>(), false, connected, getDuration());
// }
// }
//
// private long getDuration() {
// if (disconnected == null) {
// return new Interval(new DateTime(connected), DateTime.now()).toDurationMillis();
// }
// return new Interval(new DateTime(connected), new DateTime(disconnected)).toDurationMillis();
// }
//
// public String getUsername() {
// return user.getUsername();
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/MemberRepository.java
import org.nextrtc.examples.videochat_with_rest.domain.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
package org.nextrtc.examples.videochat_with_rest.repo;
@Repository
@Transactional | public interface MemberRepository extends JpaRepository<Member, Integer> { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/controller/RegisterController.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/RegisterUserService.java
// @Service
// @Transactional
// public class RegisterUserService {
//
// private static final Logger log = Logger.getLogger(RegisterUserService.class);
// @Autowired
// private UserRepository userRepository;
//
// @Autowired
// private PasswordEncoder encoder;
//
// public String generateConfirmationKey() {
// return UUID.randomUUID().toString();
// }
//
// public void register(String username, String password, String email, String confirmationKey) {
// if (userRepository.findByUsername(username).isPresent()) {
// throw new RuntimeException("user exists!");
// }
// if (userRepository.findByEmail(email).isPresent()) {
// throw new RuntimeException("email is occupied!");
// }
//
// User user = new User(username, encoder.encode(password), email, confirmationKey);
//
// //TODO: send email
//
// userRepository.save(user);
// }
//
// public void register(String name, String email, String providerId) {
// if (!userRepository.findByAuthProviderId(providerId).isPresent()) {
// userRepository.save(new User(name, email, providerId));
// }
// }
// }
| import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.nextrtc.examples.videochat_with_rest.service.RegisterUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; | package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action")
public class RegisterController {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/RegisterUserService.java
// @Service
// @Transactional
// public class RegisterUserService {
//
// private static final Logger log = Logger.getLogger(RegisterUserService.class);
// @Autowired
// private UserRepository userRepository;
//
// @Autowired
// private PasswordEncoder encoder;
//
// public String generateConfirmationKey() {
// return UUID.randomUUID().toString();
// }
//
// public void register(String username, String password, String email, String confirmationKey) {
// if (userRepository.findByUsername(username).isPresent()) {
// throw new RuntimeException("user exists!");
// }
// if (userRepository.findByEmail(email).isPresent()) {
// throw new RuntimeException("email is occupied!");
// }
//
// User user = new User(username, encoder.encode(password), email, confirmationKey);
//
// //TODO: send email
//
// userRepository.save(user);
// }
//
// public void register(String name, String email, String providerId) {
// if (!userRepository.findByAuthProviderId(providerId).isPresent()) {
// userRepository.save(new User(name, email, providerId));
// }
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/controller/RegisterController.java
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.nextrtc.examples.videochat_with_rest.service.RegisterUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action")
public class RegisterController {
@Autowired | private RegisterUserService service; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/controller/HistoryController.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/History.java
// public class History {
//
// private List<Call> calls;
//
// public History(Set<Member> conversationMember) {
// List<Member> sortedMembers = new ArrayList<>(conversationMember);
// sortedMembers.sort(Member::startedBefore);
// calls = sortedMembers.stream().map(Member::toCall).collect(toList());
// }
//
// public List<Call> getCalls() {
// return calls;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/HistoryService.java
// @Service
// @Transactional
// public class HistoryService {
//
// @Autowired
// private AuthUtils authUtils;
//
// @Autowired
// private MemberRepository memberRepository;
//
// public History getHistoryFor(Principal principal) {
// User user = authUtils.getAuthenticatedUser(principal);
//
// History history = user.prepareHistory();
//
// fillUserNamesBaseOnRtcIds(history);
//
// return history;
// }
//
// private void fillUserNamesBaseOnRtcIds(History history) {
// for (Call call : history.getCalls()) {
// List<String> others = call.getOtherRtcIds().stream()
// .map(memberRepository::getByRtcId)
// .map(Member::getUsername)
// .collect(toList());
// call.setOtherNames(others);
// }
// }
//
// }
| import org.nextrtc.examples.videochat_with_rest.domain.history.History;
import org.nextrtc.examples.videochat_with_rest.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal; | package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action/history")
public class HistoryController {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/History.java
// public class History {
//
// private List<Call> calls;
//
// public History(Set<Member> conversationMember) {
// List<Member> sortedMembers = new ArrayList<>(conversationMember);
// sortedMembers.sort(Member::startedBefore);
// calls = sortedMembers.stream().map(Member::toCall).collect(toList());
// }
//
// public List<Call> getCalls() {
// return calls;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/HistoryService.java
// @Service
// @Transactional
// public class HistoryService {
//
// @Autowired
// private AuthUtils authUtils;
//
// @Autowired
// private MemberRepository memberRepository;
//
// public History getHistoryFor(Principal principal) {
// User user = authUtils.getAuthenticatedUser(principal);
//
// History history = user.prepareHistory();
//
// fillUserNamesBaseOnRtcIds(history);
//
// return history;
// }
//
// private void fillUserNamesBaseOnRtcIds(History history) {
// for (Call call : history.getCalls()) {
// List<String> others = call.getOtherRtcIds().stream()
// .map(memberRepository::getByRtcId)
// .map(Member::getUsername)
// .collect(toList());
// call.setOtherNames(others);
// }
// }
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/controller/HistoryController.java
import org.nextrtc.examples.videochat_with_rest.domain.history.History;
import org.nextrtc.examples.videochat_with_rest.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action/history")
public class HistoryController {
@Autowired | private HistoryService historyService; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/controller/HistoryController.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/History.java
// public class History {
//
// private List<Call> calls;
//
// public History(Set<Member> conversationMember) {
// List<Member> sortedMembers = new ArrayList<>(conversationMember);
// sortedMembers.sort(Member::startedBefore);
// calls = sortedMembers.stream().map(Member::toCall).collect(toList());
// }
//
// public List<Call> getCalls() {
// return calls;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/HistoryService.java
// @Service
// @Transactional
// public class HistoryService {
//
// @Autowired
// private AuthUtils authUtils;
//
// @Autowired
// private MemberRepository memberRepository;
//
// public History getHistoryFor(Principal principal) {
// User user = authUtils.getAuthenticatedUser(principal);
//
// History history = user.prepareHistory();
//
// fillUserNamesBaseOnRtcIds(history);
//
// return history;
// }
//
// private void fillUserNamesBaseOnRtcIds(History history) {
// for (Call call : history.getCalls()) {
// List<String> others = call.getOtherRtcIds().stream()
// .map(memberRepository::getByRtcId)
// .map(Member::getUsername)
// .collect(toList());
// call.setOtherNames(others);
// }
// }
//
// }
| import org.nextrtc.examples.videochat_with_rest.domain.history.History;
import org.nextrtc.examples.videochat_with_rest.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal; | package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action/history")
public class HistoryController {
@Autowired
private HistoryService historyService;
@RequestMapping(value = "get", method = RequestMethod.GET) | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/History.java
// public class History {
//
// private List<Call> calls;
//
// public History(Set<Member> conversationMember) {
// List<Member> sortedMembers = new ArrayList<>(conversationMember);
// sortedMembers.sort(Member::startedBefore);
// calls = sortedMembers.stream().map(Member::toCall).collect(toList());
// }
//
// public List<Call> getCalls() {
// return calls;
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/HistoryService.java
// @Service
// @Transactional
// public class HistoryService {
//
// @Autowired
// private AuthUtils authUtils;
//
// @Autowired
// private MemberRepository memberRepository;
//
// public History getHistoryFor(Principal principal) {
// User user = authUtils.getAuthenticatedUser(principal);
//
// History history = user.prepareHistory();
//
// fillUserNamesBaseOnRtcIds(history);
//
// return history;
// }
//
// private void fillUserNamesBaseOnRtcIds(History history) {
// for (Call call : history.getCalls()) {
// List<String> others = call.getOtherRtcIds().stream()
// .map(memberRepository::getByRtcId)
// .map(Member::getUsername)
// .collect(toList());
// call.setOtherNames(others);
// }
// }
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/controller/HistoryController.java
import org.nextrtc.examples.videochat_with_rest.domain.history.History;
import org.nextrtc.examples.videochat_with_rest.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action/history")
public class HistoryController {
@Autowired
private HistoryService historyService;
@RequestMapping(value = "get", method = RequestMethod.GET) | public History getHistory(Principal authentication) { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/History.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Member.java
// @Entity
// @Table(name = "Members")
// public class Member {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "member_id")
// private int id;
//
// @Column(name = "member_rtc_id")
// private String rtcId;
//
// @Column(name = "connected")
// private Date connected;
//
// @Column(name = "disconnected")
// private Date disconnected;
//
// @Column(name = "left_reason")
// private String leftReason;
//
// @OneToOne(mappedBy = "member", fetch = FetchType.LAZY)
// private Connection connection;
//
// @ManyToOne
// @JoinColumn(name = "user_id")
// private User user;
//
// /**
// * for hibernate only
// */
// @Deprecated
// Member() {
// }
//
// public Member(String memberId, User user) {
// this.rtcId = memberId;
// this.user = user;
// this.connected = now().toDate();
// }
//
// public void disconnectWithReason(Optional<String> reason) {
// disconnected = now().toDate();
// reason.ifPresent(this::setLeftReason);
// }
//
// @Override
// public String toString() {
// return String.format("(%s, %s)[%s - %s]", id, rtcId, connected, disconnected);
// }
//
// public void leaves(Conversation conversation) {
// if (connection.isFor(conversation)) {
// connection.close();
// }
// }
//
// private void setLeftReason(String leftReason) {
// this.leftReason = leftReason;
// }
//
// public int startedBefore(Member p) {
// return connected.compareTo(p.connected);
// }
//
// public Call toCall() {
// if (connection != null) {
// List<String> members = connection.getConversationMembers().stream()
// .filter(m -> !m.equals(this))
// .map(m -> m.rtcId)
// .collect(toList());
// return new Call(members, !connection.isClosed(), connection.getBegin(), connection.getDuration());
// } else {
// return new Call(new ArrayList<>(), false, connected, getDuration());
// }
// }
//
// private long getDuration() {
// if (disconnected == null) {
// return new Interval(new DateTime(connected), DateTime.now()).toDurationMillis();
// }
// return new Interval(new DateTime(connected), new DateTime(disconnected)).toDurationMillis();
// }
//
// public String getUsername() {
// return user.getUsername();
// }
// }
| import org.nextrtc.examples.videochat_with_rest.domain.Member;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static java.util.stream.Collectors.toList; | package org.nextrtc.examples.videochat_with_rest.domain.history;
public class History {
private List<Call> calls;
| // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Member.java
// @Entity
// @Table(name = "Members")
// public class Member {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "member_id")
// private int id;
//
// @Column(name = "member_rtc_id")
// private String rtcId;
//
// @Column(name = "connected")
// private Date connected;
//
// @Column(name = "disconnected")
// private Date disconnected;
//
// @Column(name = "left_reason")
// private String leftReason;
//
// @OneToOne(mappedBy = "member", fetch = FetchType.LAZY)
// private Connection connection;
//
// @ManyToOne
// @JoinColumn(name = "user_id")
// private User user;
//
// /**
// * for hibernate only
// */
// @Deprecated
// Member() {
// }
//
// public Member(String memberId, User user) {
// this.rtcId = memberId;
// this.user = user;
// this.connected = now().toDate();
// }
//
// public void disconnectWithReason(Optional<String> reason) {
// disconnected = now().toDate();
// reason.ifPresent(this::setLeftReason);
// }
//
// @Override
// public String toString() {
// return String.format("(%s, %s)[%s - %s]", id, rtcId, connected, disconnected);
// }
//
// public void leaves(Conversation conversation) {
// if (connection.isFor(conversation)) {
// connection.close();
// }
// }
//
// private void setLeftReason(String leftReason) {
// this.leftReason = leftReason;
// }
//
// public int startedBefore(Member p) {
// return connected.compareTo(p.connected);
// }
//
// public Call toCall() {
// if (connection != null) {
// List<String> members = connection.getConversationMembers().stream()
// .filter(m -> !m.equals(this))
// .map(m -> m.rtcId)
// .collect(toList());
// return new Call(members, !connection.isClosed(), connection.getBegin(), connection.getDuration());
// } else {
// return new Call(new ArrayList<>(), false, connected, getDuration());
// }
// }
//
// private long getDuration() {
// if (disconnected == null) {
// return new Interval(new DateTime(connected), DateTime.now()).toDurationMillis();
// }
// return new Interval(new DateTime(connected), new DateTime(disconnected)).toDurationMillis();
// }
//
// public String getUsername() {
// return user.getUsername();
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/history/History.java
import org.nextrtc.examples.videochat_with_rest.domain.Member;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static java.util.stream.Collectors.toList;
package org.nextrtc.examples.videochat_with_rest.domain.history;
public class History {
private List<Call> calls;
| public History(Set<Member> conversationMember) { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/MemberLeftHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/MemberLeftService.java
// @Service
// @Transactional
// public class MemberLeftService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String memberId, String conversationId) {
// Member member = memberRepository.getByRtcId(memberId);
// Conversation conversation = conversationRepository.getByConversationName(conversationId);
//
// member.leaves(conversation);
// }
// }
| import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.service.MemberLeftService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.MEMBER_LEFT; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(MEMBER_LEFT) | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/MemberLeftService.java
// @Service
// @Transactional
// public class MemberLeftService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String memberId, String conversationId) {
// Member member = memberRepository.getByRtcId(memberId);
// Conversation conversation = conversationRepository.getByConversationName(conversationId);
//
// member.leaves(conversation);
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/MemberLeftHandler.java
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.service.MemberLeftService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.MEMBER_LEFT;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(MEMBER_LEFT) | public class MemberLeftHandler extends ConversationHandler { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/MemberLeftHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/MemberLeftService.java
// @Service
// @Transactional
// public class MemberLeftService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String memberId, String conversationId) {
// Member member = memberRepository.getByRtcId(memberId);
// Conversation conversation = conversationRepository.getByConversationName(conversationId);
//
// member.leaves(conversation);
// }
// }
| import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.service.MemberLeftService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.MEMBER_LEFT; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(MEMBER_LEFT)
public class MemberLeftHandler extends ConversationHandler {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/MemberLeftService.java
// @Service
// @Transactional
// public class MemberLeftService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String memberId, String conversationId) {
// Member member = memberRepository.getByRtcId(memberId);
// Conversation conversation = conversationRepository.getByConversationName(conversationId);
//
// member.leaves(conversation);
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/MemberLeftHandler.java
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.service.MemberLeftService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.MEMBER_LEFT;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(MEMBER_LEFT)
public class MemberLeftHandler extends ConversationHandler {
@Autowired | private MemberLeftService service; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/controller/CheckMyName.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/auth/AuthUtils.java
// @Service
// public class AuthUtils {
//
// @Autowired
// private UserRepository userRepository;
//
// public User getAuthenticatedUser(Principal userPrincipal) {
// String name = userPrincipal.getName();
// Optional<User> byUsername = userRepository.findByUsername(name);
// if (!byUsername.isPresent()) {
// byUsername = userRepository.findByAuthProviderId(name);
//
// }
// return byUsername.orElseThrow(() -> new RuntimeException("User isn't authenticated!"));
// }
// }
| import org.nextrtc.examples.videochat_with_rest.auth.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal; | package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action/check")
public class CheckMyName {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/auth/AuthUtils.java
// @Service
// public class AuthUtils {
//
// @Autowired
// private UserRepository userRepository;
//
// public User getAuthenticatedUser(Principal userPrincipal) {
// String name = userPrincipal.getName();
// Optional<User> byUsername = userRepository.findByUsername(name);
// if (!byUsername.isPresent()) {
// byUsername = userRepository.findByAuthProviderId(name);
//
// }
// return byUsername.orElseThrow(() -> new RuntimeException("User isn't authenticated!"));
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/controller/CheckMyName.java
import org.nextrtc.examples.videochat_with_rest.auth.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
package org.nextrtc.examples.videochat_with_rest.controller;
@RestController
@RequestMapping("/action/check")
public class CheckMyName {
@Autowired | private AuthUtils authUtils; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/config/DBConfig.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Member.java
// @Entity
// @Table(name = "Members")
// public class Member {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "member_id")
// private int id;
//
// @Column(name = "member_rtc_id")
// private String rtcId;
//
// @Column(name = "connected")
// private Date connected;
//
// @Column(name = "disconnected")
// private Date disconnected;
//
// @Column(name = "left_reason")
// private String leftReason;
//
// @OneToOne(mappedBy = "member", fetch = FetchType.LAZY)
// private Connection connection;
//
// @ManyToOne
// @JoinColumn(name = "user_id")
// private User user;
//
// /**
// * for hibernate only
// */
// @Deprecated
// Member() {
// }
//
// public Member(String memberId, User user) {
// this.rtcId = memberId;
// this.user = user;
// this.connected = now().toDate();
// }
//
// public void disconnectWithReason(Optional<String> reason) {
// disconnected = now().toDate();
// reason.ifPresent(this::setLeftReason);
// }
//
// @Override
// public String toString() {
// return String.format("(%s, %s)[%s - %s]", id, rtcId, connected, disconnected);
// }
//
// public void leaves(Conversation conversation) {
// if (connection.isFor(conversation)) {
// connection.close();
// }
// }
//
// private void setLeftReason(String leftReason) {
// this.leftReason = leftReason;
// }
//
// public int startedBefore(Member p) {
// return connected.compareTo(p.connected);
// }
//
// public Call toCall() {
// if (connection != null) {
// List<String> members = connection.getConversationMembers().stream()
// .filter(m -> !m.equals(this))
// .map(m -> m.rtcId)
// .collect(toList());
// return new Call(members, !connection.isClosed(), connection.getBegin(), connection.getDuration());
// } else {
// return new Call(new ArrayList<>(), false, connected, getDuration());
// }
// }
//
// private long getDuration() {
// if (disconnected == null) {
// return new Interval(new DateTime(connected), DateTime.now()).toDurationMillis();
// }
// return new Interval(new DateTime(connected), new DateTime(disconnected)).toDurationMillis();
// }
//
// public String getUsername() {
// return user.getUsername();
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/MemberRepository.java
// @Repository
// @Transactional
// public interface MemberRepository extends JpaRepository<Member, Integer> {
//
// @Query("select m from Member m where m.rtcId = :rtcId and m.connected = (select max(mm.connected) from Member mm where mm.rtcId = m.rtcId)")
// Optional<Member> findByRtcId(@Param("rtcId") String rtcId);
//
// @Query("select m from Member m where m.rtcId = :rtcId and m.connected = (select max(mm.connected) from Member mm where mm.rtcId = m.rtcId)")
// Member getByRtcId(@Param("rtcId") String rtcId);
//
// }
| import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.nextrtc.examples.videochat_with_rest.domain.Member;
import org.nextrtc.examples.videochat_with_rest.repo.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.Properties; | ds.setMaxIdleTime(30 * 60); // 30 minutes
ds.setMaxStatements(10);
ds.setMaxStatementsPerConnection(10);
ds.setAutoCommitOnClose(true);
ds.setDriverClass(environment.getRequiredProperty("nextrtc.db.driverClassName"));
ds.setJdbcUrl(environment.getRequiredProperty("nextrtc.db.url"));
ds.setUser(environment.getRequiredProperty("nextrtc.db.username"));
ds.setPassword(environment.getRequiredProperty("nextrtc.db.password"));
return ds;
}
private Properties hibernateProperties() {
Properties props = new Properties();
props.setProperty("hibernate.dialect", environment.getRequiredProperty("nextrtc.db.dialect"));
props.setProperty("hibernate.hbm2ddl.auto", environment.getProperty("nextrtc.db.hbm2ddl", "validate"));
props.setProperty("hibernate.show_sql", "false");
props.setProperty("hibernate.format_sql", "true");
props.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.DefaultNamingStrategy");
props.setProperty("hibernate.cache.use_second_level_cache", "false");
props.setProperty("jadira.usertype.autoRegisterUserTypes", "true");
return props;
}
@Bean(name = "NextRTCEntityMangerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factoryBean.setJpaProperties(hibernateProperties());
factoryBean.setDataSource(datasource()); | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/Member.java
// @Entity
// @Table(name = "Members")
// public class Member {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// @Column(name = "member_id")
// private int id;
//
// @Column(name = "member_rtc_id")
// private String rtcId;
//
// @Column(name = "connected")
// private Date connected;
//
// @Column(name = "disconnected")
// private Date disconnected;
//
// @Column(name = "left_reason")
// private String leftReason;
//
// @OneToOne(mappedBy = "member", fetch = FetchType.LAZY)
// private Connection connection;
//
// @ManyToOne
// @JoinColumn(name = "user_id")
// private User user;
//
// /**
// * for hibernate only
// */
// @Deprecated
// Member() {
// }
//
// public Member(String memberId, User user) {
// this.rtcId = memberId;
// this.user = user;
// this.connected = now().toDate();
// }
//
// public void disconnectWithReason(Optional<String> reason) {
// disconnected = now().toDate();
// reason.ifPresent(this::setLeftReason);
// }
//
// @Override
// public String toString() {
// return String.format("(%s, %s)[%s - %s]", id, rtcId, connected, disconnected);
// }
//
// public void leaves(Conversation conversation) {
// if (connection.isFor(conversation)) {
// connection.close();
// }
// }
//
// private void setLeftReason(String leftReason) {
// this.leftReason = leftReason;
// }
//
// public int startedBefore(Member p) {
// return connected.compareTo(p.connected);
// }
//
// public Call toCall() {
// if (connection != null) {
// List<String> members = connection.getConversationMembers().stream()
// .filter(m -> !m.equals(this))
// .map(m -> m.rtcId)
// .collect(toList());
// return new Call(members, !connection.isClosed(), connection.getBegin(), connection.getDuration());
// } else {
// return new Call(new ArrayList<>(), false, connected, getDuration());
// }
// }
//
// private long getDuration() {
// if (disconnected == null) {
// return new Interval(new DateTime(connected), DateTime.now()).toDurationMillis();
// }
// return new Interval(new DateTime(connected), new DateTime(disconnected)).toDurationMillis();
// }
//
// public String getUsername() {
// return user.getUsername();
// }
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/MemberRepository.java
// @Repository
// @Transactional
// public interface MemberRepository extends JpaRepository<Member, Integer> {
//
// @Query("select m from Member m where m.rtcId = :rtcId and m.connected = (select max(mm.connected) from Member mm where mm.rtcId = m.rtcId)")
// Optional<Member> findByRtcId(@Param("rtcId") String rtcId);
//
// @Query("select m from Member m where m.rtcId = :rtcId and m.connected = (select max(mm.connected) from Member mm where mm.rtcId = m.rtcId)")
// Member getByRtcId(@Param("rtcId") String rtcId);
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/config/DBConfig.java
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.nextrtc.examples.videochat_with_rest.domain.Member;
import org.nextrtc.examples.videochat_with_rest.repo.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.Properties;
ds.setMaxIdleTime(30 * 60); // 30 minutes
ds.setMaxStatements(10);
ds.setMaxStatementsPerConnection(10);
ds.setAutoCommitOnClose(true);
ds.setDriverClass(environment.getRequiredProperty("nextrtc.db.driverClassName"));
ds.setJdbcUrl(environment.getRequiredProperty("nextrtc.db.url"));
ds.setUser(environment.getRequiredProperty("nextrtc.db.username"));
ds.setPassword(environment.getRequiredProperty("nextrtc.db.password"));
return ds;
}
private Properties hibernateProperties() {
Properties props = new Properties();
props.setProperty("hibernate.dialect", environment.getRequiredProperty("nextrtc.db.dialect"));
props.setProperty("hibernate.hbm2ddl.auto", environment.getProperty("nextrtc.db.hbm2ddl", "validate"));
props.setProperty("hibernate.show_sql", "false");
props.setProperty("hibernate.format_sql", "true");
props.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.DefaultNamingStrategy");
props.setProperty("hibernate.cache.use_second_level_cache", "false");
props.setProperty("jadira.usertype.autoRegisterUserTypes", "true");
return props;
}
@Bean(name = "NextRTCEntityMangerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factoryBean.setJpaProperties(hibernateProperties());
factoryBean.setDataSource(datasource()); | factoryBean.setPackagesToScan(Member.class.getPackage().getName()); |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionClosedService.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/MemberRepository.java
// @Repository
// @Transactional
// public interface MemberRepository extends JpaRepository<Member, Integer> {
//
// @Query("select m from Member m where m.rtcId = :rtcId and m.connected = (select max(mm.connected) from Member mm where mm.rtcId = m.rtcId)")
// Optional<Member> findByRtcId(@Param("rtcId") String rtcId);
//
// @Query("select m from Member m where m.rtcId = :rtcId and m.connected = (select max(mm.connected) from Member mm where mm.rtcId = m.rtcId)")
// Member getByRtcId(@Param("rtcId") String rtcId);
//
// }
| import org.nextrtc.examples.videochat_with_rest.repo.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional; | package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class SessionClosedService {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/repo/MemberRepository.java
// @Repository
// @Transactional
// public interface MemberRepository extends JpaRepository<Member, Integer> {
//
// @Query("select m from Member m where m.rtcId = :rtcId and m.connected = (select max(mm.connected) from Member mm where mm.rtcId = m.rtcId)")
// Optional<Member> findByRtcId(@Param("rtcId") String rtcId);
//
// @Query("select m from Member m where m.rtcId = :rtcId and m.connected = (select max(mm.connected) from Member mm where mm.rtcId = m.rtcId)")
// Member getByRtcId(@Param("rtcId") String rtcId);
//
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/SessionClosedService.java
import org.nextrtc.examples.videochat_with_rest.repo.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
package org.nextrtc.examples.videochat_with_rest.service;
@Service
@Transactional
public class SessionClosedService {
@Autowired | private MemberRepository memberRepository; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/MemberJoinedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/MemberJoinService.java
// @Service
// @Transactional
// public class MemberJoinService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String memberId, String conversationId) {
// Conversation conversation = conversationRepository.getByConversationName(conversationId);
// Member member = memberRepository.getByRtcId(memberId);
//
// conversation.join(member);
// }
// }
| import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.MemberJoinService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.MEMBER_JOINED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(MEMBER_JOINED) | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/MemberJoinService.java
// @Service
// @Transactional
// public class MemberJoinService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String memberId, String conversationId) {
// Conversation conversation = conversationRepository.getByConversationName(conversationId);
// Member member = memberRepository.getByRtcId(memberId);
//
// conversation.join(member);
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/MemberJoinedHandler.java
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.MemberJoinService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.MEMBER_JOINED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(MEMBER_JOINED) | public class MemberJoinedHandler extends FromMemberHandler { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/MemberJoinedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/MemberJoinService.java
// @Service
// @Transactional
// public class MemberJoinService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String memberId, String conversationId) {
// Conversation conversation = conversationRepository.getByConversationName(conversationId);
// Member member = memberRepository.getByRtcId(memberId);
//
// conversation.join(member);
// }
// }
| import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.MemberJoinService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.MEMBER_JOINED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(MEMBER_JOINED)
public class MemberJoinedHandler extends FromMemberHandler {
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/FromMemberHandler.java
// public abstract class FromMemberHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.from().ifPresent(from -> handleEvent(from, event));
// }
//
// protected abstract void handleEvent(NextRTCMember from, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/MemberJoinService.java
// @Service
// @Transactional
// public class MemberJoinService {
//
// @Autowired
// private MemberRepository memberRepository;
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String memberId, String conversationId) {
// Conversation conversation = conversationRepository.getByConversationName(conversationId);
// Member member = memberRepository.getByRtcId(memberId);
//
// conversation.join(member);
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/MemberJoinedHandler.java
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.FromMemberHandler;
import org.nextrtc.examples.videochat_with_rest.service.MemberJoinService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.nextrtc.signalingserver.api.dto.NextRTCMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.MEMBER_JOINED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(MEMBER_JOINED)
public class MemberJoinedHandler extends FromMemberHandler {
@Autowired | private MemberJoinService service; |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationDestroyedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/DestroyConversationService.java
// @Service
// @Transactional
// public class DestroyConversationService {
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String roomName) {
// conversationRepository.getByConversationName(roomName).destroy();
// }
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.service.DestroyConversationService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_DESTROYED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_DESTROYED) | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/DestroyConversationService.java
// @Service
// @Transactional
// public class DestroyConversationService {
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String roomName) {
// conversationRepository.getByConversationName(roomName).destroy();
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationDestroyedHandler.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.service.DestroyConversationService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_DESTROYED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_DESTROYED) | public class ConversationDestroyedHandler extends ConversationHandler { |
mslosarz/nextrtc-videochat-with-rest | src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationDestroyedHandler.java | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/DestroyConversationService.java
// @Service
// @Transactional
// public class DestroyConversationService {
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String roomName) {
// conversationRepository.getByConversationName(roomName).destroy();
// }
// }
| import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.service.DestroyConversationService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_DESTROYED; | package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_DESTROYED)
public class ConversationDestroyedHandler extends ConversationHandler {
private static final Logger log = Logger.getLogger(ConversationDestroyedHandler.class);
@Autowired | // Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/common/ConversationHandler.java
// public abstract class ConversationHandler implements NextRTCHandler {
//
// @Override
// public final void handleEvent(NextRTCEvent event) {
// event.conversation().ifPresent(conversation -> handleEvent(conversation, event));
// }
//
// protected abstract void handleEvent(NextRTCConversation conversation, NextRTCEvent event);
// }
//
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/service/DestroyConversationService.java
// @Service
// @Transactional
// public class DestroyConversationService {
//
// @Autowired
// private ConversationRepository conversationRepository;
//
// public void execute(String roomName) {
// conversationRepository.getByConversationName(roomName).destroy();
// }
// }
// Path: src/main/java/org/nextrtc/examples/videochat_with_rest/domain/handler/ConversationDestroyedHandler.java
import org.apache.log4j.Logger;
import org.nextrtc.examples.videochat_with_rest.domain.handler.common.ConversationHandler;
import org.nextrtc.examples.videochat_with_rest.service.DestroyConversationService;
import org.nextrtc.signalingserver.api.annotation.NextRTCEventListener;
import org.nextrtc.signalingserver.api.dto.NextRTCConversation;
import org.nextrtc.signalingserver.api.dto.NextRTCEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.nextrtc.signalingserver.api.NextRTCEvents.CONVERSATION_DESTROYED;
package org.nextrtc.examples.videochat_with_rest.domain.handler;
@Component
@NextRTCEventListener(CONVERSATION_DESTROYED)
public class ConversationDestroyedHandler extends ConversationHandler {
private static final Logger log = Logger.getLogger(ConversationDestroyedHandler.class);
@Autowired | private DestroyConversationService service; |
ethlo/itu | src/test/java/com/ethlo/time/AbstractTest.java | // Path: src/main/java/com/ethlo/time/internal/Rfc3339Formatter.java
// public interface Rfc3339Formatter
// {
// /**
// * Format the {@link Date} as a UTC formatted date-time string
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with millisecond resolution, for example 1999-12-31T16:48:36.123Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMilli(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with microsecond resolution, aka 1999-12-31T16:48:36.123456Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMicro(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with nanosecond resolution, aka 1999-12-31T16:48:36.123456789Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcNano(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with specified resolution, aka 1999-12-31T16:48:36[.123456789]Z
// *
// * @param date The date to format
// * @param fractionDigits The number of fractional digits in the second
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date, int fractionDigits);
// }
//
// Path: src/main/java/com/ethlo/time/internal/Rfc3339Parser.java
// public interface Rfc3339Parser
// {
// /**
// * Parse the date-time and return it as a {@link OffsetDateTime}.
// *
// * @param dateTimeStr The date-time string to parse
// * @return The {@link OffsetDateTime} as parsed from the input
// */
// OffsetDateTime parseDateTime(String dateTimeStr);
// }
| import org.junit.jupiter.api.BeforeEach;
import com.ethlo.time.internal.Rfc3339Formatter;
import com.ethlo.time.internal.Rfc3339Parser; | package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
public abstract class AbstractTest
{ | // Path: src/main/java/com/ethlo/time/internal/Rfc3339Formatter.java
// public interface Rfc3339Formatter
// {
// /**
// * Format the {@link Date} as a UTC formatted date-time string
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with millisecond resolution, for example 1999-12-31T16:48:36.123Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMilli(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with microsecond resolution, aka 1999-12-31T16:48:36.123456Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMicro(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with nanosecond resolution, aka 1999-12-31T16:48:36.123456789Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcNano(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with specified resolution, aka 1999-12-31T16:48:36[.123456789]Z
// *
// * @param date The date to format
// * @param fractionDigits The number of fractional digits in the second
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date, int fractionDigits);
// }
//
// Path: src/main/java/com/ethlo/time/internal/Rfc3339Parser.java
// public interface Rfc3339Parser
// {
// /**
// * Parse the date-time and return it as a {@link OffsetDateTime}.
// *
// * @param dateTimeStr The date-time string to parse
// * @return The {@link OffsetDateTime} as parsed from the input
// */
// OffsetDateTime parseDateTime(String dateTimeStr);
// }
// Path: src/test/java/com/ethlo/time/AbstractTest.java
import org.junit.jupiter.api.BeforeEach;
import com.ethlo.time.internal.Rfc3339Formatter;
import com.ethlo.time.internal.Rfc3339Parser;
package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
public abstract class AbstractTest
{ | protected Rfc3339Parser parser; |
ethlo/itu | src/test/java/com/ethlo/time/AbstractTest.java | // Path: src/main/java/com/ethlo/time/internal/Rfc3339Formatter.java
// public interface Rfc3339Formatter
// {
// /**
// * Format the {@link Date} as a UTC formatted date-time string
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with millisecond resolution, for example 1999-12-31T16:48:36.123Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMilli(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with microsecond resolution, aka 1999-12-31T16:48:36.123456Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMicro(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with nanosecond resolution, aka 1999-12-31T16:48:36.123456789Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcNano(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with specified resolution, aka 1999-12-31T16:48:36[.123456789]Z
// *
// * @param date The date to format
// * @param fractionDigits The number of fractional digits in the second
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date, int fractionDigits);
// }
//
// Path: src/main/java/com/ethlo/time/internal/Rfc3339Parser.java
// public interface Rfc3339Parser
// {
// /**
// * Parse the date-time and return it as a {@link OffsetDateTime}.
// *
// * @param dateTimeStr The date-time string to parse
// * @return The {@link OffsetDateTime} as parsed from the input
// */
// OffsetDateTime parseDateTime(String dateTimeStr);
// }
| import org.junit.jupiter.api.BeforeEach;
import com.ethlo.time.internal.Rfc3339Formatter;
import com.ethlo.time.internal.Rfc3339Parser; | package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
public abstract class AbstractTest
{
protected Rfc3339Parser parser; | // Path: src/main/java/com/ethlo/time/internal/Rfc3339Formatter.java
// public interface Rfc3339Formatter
// {
// /**
// * Format the {@link Date} as a UTC formatted date-time string
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with millisecond resolution, for example 1999-12-31T16:48:36.123Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMilli(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with microsecond resolution, aka 1999-12-31T16:48:36.123456Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMicro(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with nanosecond resolution, aka 1999-12-31T16:48:36.123456789Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcNano(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with specified resolution, aka 1999-12-31T16:48:36[.123456789]Z
// *
// * @param date The date to format
// * @param fractionDigits The number of fractional digits in the second
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date, int fractionDigits);
// }
//
// Path: src/main/java/com/ethlo/time/internal/Rfc3339Parser.java
// public interface Rfc3339Parser
// {
// /**
// * Parse the date-time and return it as a {@link OffsetDateTime}.
// *
// * @param dateTimeStr The date-time string to parse
// * @return The {@link OffsetDateTime} as parsed from the input
// */
// OffsetDateTime parseDateTime(String dateTimeStr);
// }
// Path: src/test/java/com/ethlo/time/AbstractTest.java
import org.junit.jupiter.api.BeforeEach;
import com.ethlo.time.internal.Rfc3339Formatter;
import com.ethlo.time.internal.Rfc3339Parser;
package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
public abstract class AbstractTest
{
protected Rfc3339Parser parser; | protected Rfc3339Formatter formatter; |
ethlo/itu | src/test/java/com/ethlo/time/FormatterBenchmarkTest.java | // Path: src/main/java/com/ethlo/time/internal/Rfc3339Formatter.java
// public interface Rfc3339Formatter
// {
// /**
// * Format the {@link Date} as a UTC formatted date-time string
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with millisecond resolution, for example 1999-12-31T16:48:36.123Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMilli(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with microsecond resolution, aka 1999-12-31T16:48:36.123456Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMicro(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with nanosecond resolution, aka 1999-12-31T16:48:36.123456789Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcNano(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with specified resolution, aka 1999-12-31T16:48:36[.123456789]Z
// *
// * @param date The date to format
// * @param fractionDigits The number of fractional digits in the second
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date, int fractionDigits);
// }
| import java.time.OffsetDateTime;
import java.util.concurrent.TimeUnit;
import com.ethlo.time.internal.Rfc3339Formatter;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.infra.Blackhole; | package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public abstract class FormatterBenchmarkTest
{
private static final OffsetDateTime input = OffsetDateTime.parse("2017-12-21T12:20:45.987654321Z"); | // Path: src/main/java/com/ethlo/time/internal/Rfc3339Formatter.java
// public interface Rfc3339Formatter
// {
// /**
// * Format the {@link Date} as a UTC formatted date-time string
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with millisecond resolution, for example 1999-12-31T16:48:36.123Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMilli(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with microsecond resolution, aka 1999-12-31T16:48:36.123456Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcMicro(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with nanosecond resolution, aka 1999-12-31T16:48:36.123456789Z
// *
// * @param date The date to format
// * @return the formatted string
// */
// String formatUtcNano(OffsetDateTime date);
//
// /**
// * Format the date as a date-time String with specified resolution, aka 1999-12-31T16:48:36[.123456789]Z
// *
// * @param date The date to format
// * @param fractionDigits The number of fractional digits in the second
// * @return the formatted string
// */
// String formatUtc(OffsetDateTime date, int fractionDigits);
// }
// Path: src/test/java/com/ethlo/time/FormatterBenchmarkTest.java
import java.time.OffsetDateTime;
import java.util.concurrent.TimeUnit;
import com.ethlo.time.internal.Rfc3339Formatter;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.infra.Blackhole;
package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public abstract class FormatterBenchmarkTest
{
private static final OffsetDateTime input = OffsetDateTime.parse("2017-12-21T12:20:45.987654321Z"); | private static Rfc3339Formatter formatter; |
ethlo/itu | src/test/java/com/ethlo/time/ParserBenchmarkTest.java | // Path: src/main/java/com/ethlo/time/internal/Rfc3339Parser.java
// public interface Rfc3339Parser
// {
// /**
// * Parse the date-time and return it as a {@link OffsetDateTime}.
// *
// * @param dateTimeStr The date-time string to parse
// * @return The {@link OffsetDateTime} as parsed from the input
// */
// OffsetDateTime parseDateTime(String dateTimeStr);
// }
| import java.util.concurrent.TimeUnit;
import com.ethlo.time.internal.Rfc3339Parser;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.infra.Blackhole; | package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public abstract class ParserBenchmarkTest
{ | // Path: src/main/java/com/ethlo/time/internal/Rfc3339Parser.java
// public interface Rfc3339Parser
// {
// /**
// * Parse the date-time and return it as a {@link OffsetDateTime}.
// *
// * @param dateTimeStr The date-time string to parse
// * @return The {@link OffsetDateTime} as parsed from the input
// */
// OffsetDateTime parseDateTime(String dateTimeStr);
// }
// Path: src/test/java/com/ethlo/time/ParserBenchmarkTest.java
import java.util.concurrent.TimeUnit;
import com.ethlo.time.internal.Rfc3339Parser;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.infra.Blackhole;
package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public abstract class ParserBenchmarkTest
{ | protected static Rfc3339Parser parser; |
ethlo/itu | src/test/java/com/ethlo/time/CharArrayUtilTest.java | // Path: src/main/java/com/ethlo/time/internal/LimitedCharArrayIntegerUtil.java
// public final class LimitedCharArrayIntegerUtil
// {
// public static final char DIGIT_9 = '9';
// private static final char ZERO = '0';
// private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
// private static final int TABLE_WIDTH = 4;
// private static final int RADIX = 10;
// private static final int MAX_INT_WIDTH = 10;
// private static final int TABLE_SIZE = (int) Math.pow(RADIX, TABLE_WIDTH);
// private static final char[] INT_CONVERSION_CACHE = new char[(TABLE_SIZE * TABLE_WIDTH) + MAX_INT_WIDTH];
//
// static
// {
// int offset = 0;
// for (int i = 0; i < TABLE_SIZE; i++)
// {
// createBufferEntry(INT_CONVERSION_CACHE, offset, TABLE_WIDTH, i);
// offset += TABLE_WIDTH;
// }
// }
//
// private LimitedCharArrayIntegerUtil()
// {
// }
//
// public static int parsePositiveInt(final char[] strNum, int startInclusive, int endExclusive)
// {
// if (endExclusive > strNum.length)
// {
// throw new DateTimeException("Unexpected end of expression at position " + strNum.length + ": '" + new String(strNum) + "'");
// }
//
// int result = 0;
// for (int i = startInclusive; i < endExclusive; i++)
// {
// final char c = strNum[i];
// if (isNotDigit(c))
// {
// throw new DateTimeException("Character " + c + " is not a digit");
// }
// int digit = digit(c);
// result *= RADIX;
// result -= digit;
// }
// return -result;
// }
//
// public static int uncheckedParsePositiveInt(final char[] strNum, int startInclusive, int endExclusive)
// {
// int result = 0;
// for (int i = startInclusive; i < endExclusive; i++)
// {
// final char c = strNum[i];
// int digit = digit(c);
// result *= RADIX;
// result -= digit;
// }
// return -result;
// }
//
// public static void toString(final int value, final char[] buf, final int offset, final int charLength)
// {
// if (value < TABLE_SIZE)
// {
// final int length = Math.min(TABLE_WIDTH, charLength);
// final int padPrefixLen = charLength - length;
// final int start = charLength > TABLE_WIDTH ? TABLE_WIDTH : TABLE_WIDTH - charLength;
// final int targetOffset = offset + padPrefixLen;
// final int srcPos = (value * TABLE_WIDTH) + (charLength < TABLE_WIDTH ? start : 0);
// copy(INT_CONVERSION_CACHE, srcPos, buf, targetOffset, length);
// if (padPrefixLen > 0)
// {
// zeroFill(buf, offset, padPrefixLen);
// }
// }
// else
// {
// createBufferEntry(buf, offset, charLength, value);
// }
// }
//
// private static void createBufferEntry(char[] buf, int offset, int charLength, int value)
// {
// int charPos = offset + MAX_INT_WIDTH;
// value = -value;
// int div;
// int rem;
// while (value <= -10)
// {
// div = value / 10;
// rem = -(value - 10 * div);
// buf[charPos--] = DIGITS[rem];
// value = div;
// }
// buf[charPos] = DIGITS[-value];
//
// int l = ((MAX_INT_WIDTH + offset) - charPos) + 1;
// while (l < charLength)
// {
// buf[--charPos] = ZERO;
// l++;
// }
// final int srcPos = charPos;
// copy(buf, srcPos, offset, charLength);
// }
//
// private static void zeroFill(char[] buf, int offset, int padPrefixLen)
// {
// Arrays.fill(buf, offset, offset + padPrefixLen, ZERO);
// }
//
// private static void copy(char[] buf, int srcPos, int offset, int length)
// {
// copy(buf, srcPos, buf, offset, length);
// }
//
// private static void copy(char[] buf, int srcPos, char[] target, int offset, int length)
// {
// System.arraycopy(buf, srcPos, target, offset, length);
// }
//
// public static int indexOfNonDigit(final char[] text, int offset)
// {
// for (int i = offset; i < text.length; i++)
// {
// if (isNotDigit(text[i]))
// {
// return i;
// }
// }
// return -1;
// }
//
// private static boolean isNotDigit(char c)
// {
// return (c < ZERO || c > DIGIT_9);
// }
//
// private static int digit(char c)
// {
// return c - ZERO;
// }
// }
| import java.util.Arrays;
import com.ethlo.time.internal.LimitedCharArrayIntegerUtil;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; | package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
public class CharArrayUtilTest
{
@Test
public void testConvertWithoutTable()
{
final char[] expected = new char[]{'0', '1', '2', '3', '4', '5', '6'};
final int value = 123456;
final char[] buf = new char[16]; | // Path: src/main/java/com/ethlo/time/internal/LimitedCharArrayIntegerUtil.java
// public final class LimitedCharArrayIntegerUtil
// {
// public static final char DIGIT_9 = '9';
// private static final char ZERO = '0';
// private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
// private static final int TABLE_WIDTH = 4;
// private static final int RADIX = 10;
// private static final int MAX_INT_WIDTH = 10;
// private static final int TABLE_SIZE = (int) Math.pow(RADIX, TABLE_WIDTH);
// private static final char[] INT_CONVERSION_CACHE = new char[(TABLE_SIZE * TABLE_WIDTH) + MAX_INT_WIDTH];
//
// static
// {
// int offset = 0;
// for (int i = 0; i < TABLE_SIZE; i++)
// {
// createBufferEntry(INT_CONVERSION_CACHE, offset, TABLE_WIDTH, i);
// offset += TABLE_WIDTH;
// }
// }
//
// private LimitedCharArrayIntegerUtil()
// {
// }
//
// public static int parsePositiveInt(final char[] strNum, int startInclusive, int endExclusive)
// {
// if (endExclusive > strNum.length)
// {
// throw new DateTimeException("Unexpected end of expression at position " + strNum.length + ": '" + new String(strNum) + "'");
// }
//
// int result = 0;
// for (int i = startInclusive; i < endExclusive; i++)
// {
// final char c = strNum[i];
// if (isNotDigit(c))
// {
// throw new DateTimeException("Character " + c + " is not a digit");
// }
// int digit = digit(c);
// result *= RADIX;
// result -= digit;
// }
// return -result;
// }
//
// public static int uncheckedParsePositiveInt(final char[] strNum, int startInclusive, int endExclusive)
// {
// int result = 0;
// for (int i = startInclusive; i < endExclusive; i++)
// {
// final char c = strNum[i];
// int digit = digit(c);
// result *= RADIX;
// result -= digit;
// }
// return -result;
// }
//
// public static void toString(final int value, final char[] buf, final int offset, final int charLength)
// {
// if (value < TABLE_SIZE)
// {
// final int length = Math.min(TABLE_WIDTH, charLength);
// final int padPrefixLen = charLength - length;
// final int start = charLength > TABLE_WIDTH ? TABLE_WIDTH : TABLE_WIDTH - charLength;
// final int targetOffset = offset + padPrefixLen;
// final int srcPos = (value * TABLE_WIDTH) + (charLength < TABLE_WIDTH ? start : 0);
// copy(INT_CONVERSION_CACHE, srcPos, buf, targetOffset, length);
// if (padPrefixLen > 0)
// {
// zeroFill(buf, offset, padPrefixLen);
// }
// }
// else
// {
// createBufferEntry(buf, offset, charLength, value);
// }
// }
//
// private static void createBufferEntry(char[] buf, int offset, int charLength, int value)
// {
// int charPos = offset + MAX_INT_WIDTH;
// value = -value;
// int div;
// int rem;
// while (value <= -10)
// {
// div = value / 10;
// rem = -(value - 10 * div);
// buf[charPos--] = DIGITS[rem];
// value = div;
// }
// buf[charPos] = DIGITS[-value];
//
// int l = ((MAX_INT_WIDTH + offset) - charPos) + 1;
// while (l < charLength)
// {
// buf[--charPos] = ZERO;
// l++;
// }
// final int srcPos = charPos;
// copy(buf, srcPos, offset, charLength);
// }
//
// private static void zeroFill(char[] buf, int offset, int padPrefixLen)
// {
// Arrays.fill(buf, offset, offset + padPrefixLen, ZERO);
// }
//
// private static void copy(char[] buf, int srcPos, int offset, int length)
// {
// copy(buf, srcPos, buf, offset, length);
// }
//
// private static void copy(char[] buf, int srcPos, char[] target, int offset, int length)
// {
// System.arraycopy(buf, srcPos, target, offset, length);
// }
//
// public static int indexOfNonDigit(final char[] text, int offset)
// {
// for (int i = offset; i < text.length; i++)
// {
// if (isNotDigit(text[i]))
// {
// return i;
// }
// }
// return -1;
// }
//
// private static boolean isNotDigit(char c)
// {
// return (c < ZERO || c > DIGIT_9);
// }
//
// private static int digit(char c)
// {
// return c - ZERO;
// }
// }
// Path: src/test/java/com/ethlo/time/CharArrayUtilTest.java
import java.util.Arrays;
import com.ethlo.time.internal.LimitedCharArrayIntegerUtil;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
package com.ethlo.time;
/*-
* #%L
* Internet Time Utility
* %%
* Copyright (C) 2017 Morten Haraldsen (ethlo)
* %%
* 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.
* #L%
*/
public class CharArrayUtilTest
{
@Test
public void testConvertWithoutTable()
{
final char[] expected = new char[]{'0', '1', '2', '3', '4', '5', '6'};
final int value = 123456;
final char[] buf = new char[16]; | LimitedCharArrayIntegerUtil.toString(value, buf, 0, 7); |
eternnoir/ToS_Bot | app/src/main/java/com/tos_bot/utility/jsonToSolution.java | // Path: app/src/main/java/com/tos_bot/puzzleslove/solution.java
// @SuppressLint("NewApi")
// public class solution implements Comparator<solution> {
// public int[][] board;
// public int[][] currentboard;
// public pos cursor;
// public pos initcursor;
// public ArrayList<Integer> path;
// public boolean is_done;
// public ArrayList<matchPair> matches;
// public solution(int[][] inboard,pos c,pos ic,ArrayList<Integer> p,boolean done,ArrayList<matchPair> m){
// board = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// board[i][j] = inboard[i][j];
// cursor = c;
// initcursor = ic;
// path = new ArrayList<Integer>();
// path.addAll(p);
// is_done = done;
// matches = m;
// }
// public solution(){
//
// }
// public int compare(solution a, solution b) {
// return Integer.signum(a.matches.size() - b.matches.size());
// }
// public void setCB(int[][] b){
// currentboard = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// currentboard[i][j] = b[i][j];
// }
//
//
// }
| import java.util.ArrayList;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.tos_bot.puzzleslove.solution; | package com.tos_bot.utility;
/**
* 原本puzzle server會回傳一組json裡面包含所有solution
* 為了節省流量將puzzle server只回傳最高分數的那組,所以這
* 個class沒有使用了.
*
* @author frankwang
*
*/
public class jsonToSolution {
public static boolean cmdDone;
| // Path: app/src/main/java/com/tos_bot/puzzleslove/solution.java
// @SuppressLint("NewApi")
// public class solution implements Comparator<solution> {
// public int[][] board;
// public int[][] currentboard;
// public pos cursor;
// public pos initcursor;
// public ArrayList<Integer> path;
// public boolean is_done;
// public ArrayList<matchPair> matches;
// public solution(int[][] inboard,pos c,pos ic,ArrayList<Integer> p,boolean done,ArrayList<matchPair> m){
// board = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// board[i][j] = inboard[i][j];
// cursor = c;
// initcursor = ic;
// path = new ArrayList<Integer>();
// path.addAll(p);
// is_done = done;
// matches = m;
// }
// public solution(){
//
// }
// public int compare(solution a, solution b) {
// return Integer.signum(a.matches.size() - b.matches.size());
// }
// public void setCB(int[][] b){
// currentboard = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// currentboard[i][j] = b[i][j];
// }
//
//
// }
// Path: app/src/main/java/com/tos_bot/utility/jsonToSolution.java
import java.util.ArrayList;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.tos_bot.puzzleslove.solution;
package com.tos_bot.utility;
/**
* 原本puzzle server會回傳一組json裡面包含所有solution
* 為了節省流量將puzzle server只回傳最高分數的那組,所以這
* 個class沒有使用了.
*
* @author frankwang
*
*/
public class jsonToSolution {
public static boolean cmdDone;
| public static ArrayList<solution> passJsonToSol(String str) { |
eternnoir/ToS_Bot | app/src/main/java/com/tos_bot/touchservice/AbstractTouchService.java | // Path: app/src/main/java/com/tos_bot/ConfigData.java
// public class ConfigData {
// public static String Serverurl;
// public static int eightd = 0; // 0 is no eight direction
// public static int deep = 30; // max move
// public static int waitForStageChageTimeSec = 12;
// public static String DeviceName = "";
// public static Integer StyleName = R.id.Vary_color_Single;
// public static String TempDir = "";
// public static Thread solverThread = null;
// public static String maxCombo = "0"; //0 is no limit
// public static String gap = "70"; //the sleep time between two touch command
// public static int timeOut = 10;
// //For TouchEvent
// public static String touchEventNum;
// public static String posXId;
// public static String posYId;
// public static String posXMax;
// public static String posYMax;
// public static String trackingId;
// public static String pressureId;
// public static String trackingMax;
// public static String pressureMax;
// public static String oneBallMove;
// public static String startPosX;
// public static String startPosY;
// //For Image Setting
// public static int oneOrbWitdh=0;
// public static int boardStartX=0;
// public static int boardStartY=0;
//
//
// public static int MaxOrbType=7;
// public static LinkedHashMap<String, String> baseOrbHash = null;
//
// /**
// * get config data from SharedPreferences
// */
// static public void setConfig(SharedPreferences settings ){
// ConfigData.Serverurl = settings.getString("Serverurl", "http://tbserver.ap01.aws.af.cm/");
// ConfigData.deep = settings.getInt("deep", 30);
// ConfigData.maxCombo = settings.getString("maxCombo", "0");
// ConfigData.gap = settings.getString("gap","70");
// ConfigData.DeviceName = settings.getString("DeviceName","Auto");
// ConfigData.touchEventNum = settings.getString("touchEventNum","");
// ConfigData.posXId = settings.getString("posXId","");
// ConfigData.posYId = settings.getString("posYId","");
// ConfigData.posXMax = settings.getString("posXMax","");
// ConfigData.posYMax = settings.getString("posYMax","");
// ConfigData.trackingId = settings.getString("trackingId","");
// ConfigData.pressureId = settings.getString("pressureId","");
// ConfigData.trackingMax = settings.getString("trackingMax","");
// ConfigData.pressureMax = settings.getString("pressureMax","");
// ConfigData.oneBallMove = settings.getString("oneBallMove","");
// ConfigData.startPosX = settings.getString("startPosX","");
// ConfigData.startPosY = settings.getString("startPosY","");
//
// //For Image
// ConfigData.oneOrbWitdh = settings.getInt("oneOrbWitdh", 0);
// ConfigData.boardStartX = settings.getInt("boardStartX", 0);
// ConfigData.boardStartY = settings.getInt("boardStartY", 0);
//
//
// }
//
// }
//
// Path: app/src/main/java/com/tos_bot/puzzleslove/solution.java
// @SuppressLint("NewApi")
// public class solution implements Comparator<solution> {
// public int[][] board;
// public int[][] currentboard;
// public pos cursor;
// public pos initcursor;
// public ArrayList<Integer> path;
// public boolean is_done;
// public ArrayList<matchPair> matches;
// public solution(int[][] inboard,pos c,pos ic,ArrayList<Integer> p,boolean done,ArrayList<matchPair> m){
// board = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// board[i][j] = inboard[i][j];
// cursor = c;
// initcursor = ic;
// path = new ArrayList<Integer>();
// path.addAll(p);
// is_done = done;
// matches = m;
// }
// public solution(){
//
// }
// public int compare(solution a, solution b) {
// return Integer.signum(a.matches.size() - b.matches.size());
// }
// public void setCB(int[][] b){
// currentboard = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// currentboard[i][j] = b[i][j];
// }
//
//
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import android.os.SystemClock;
import com.tos_bot.ConfigData;
import com.tos_bot.puzzleslove.solution; | package com.tos_bot.touchservice;
public abstract class AbstractTouchService {
private int _ballgap;
private int _inix;
private int _iniy;
public void setUp(int bg, int inix, int iniy) {
_ballgap = bg;
_inix = inix;
_iniy = iniy;
}
public void SendCommand(Vector<String> str) {
Process sh;
try {
sh = Runtime.getRuntime().exec("su", null, null);
OutputStream os = sh.getOutputStream();
for (String s : str) {
os.write(s.getBytes("ASCII"));
os.flush();
}
os.close();
sh.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| // Path: app/src/main/java/com/tos_bot/ConfigData.java
// public class ConfigData {
// public static String Serverurl;
// public static int eightd = 0; // 0 is no eight direction
// public static int deep = 30; // max move
// public static int waitForStageChageTimeSec = 12;
// public static String DeviceName = "";
// public static Integer StyleName = R.id.Vary_color_Single;
// public static String TempDir = "";
// public static Thread solverThread = null;
// public static String maxCombo = "0"; //0 is no limit
// public static String gap = "70"; //the sleep time between two touch command
// public static int timeOut = 10;
// //For TouchEvent
// public static String touchEventNum;
// public static String posXId;
// public static String posYId;
// public static String posXMax;
// public static String posYMax;
// public static String trackingId;
// public static String pressureId;
// public static String trackingMax;
// public static String pressureMax;
// public static String oneBallMove;
// public static String startPosX;
// public static String startPosY;
// //For Image Setting
// public static int oneOrbWitdh=0;
// public static int boardStartX=0;
// public static int boardStartY=0;
//
//
// public static int MaxOrbType=7;
// public static LinkedHashMap<String, String> baseOrbHash = null;
//
// /**
// * get config data from SharedPreferences
// */
// static public void setConfig(SharedPreferences settings ){
// ConfigData.Serverurl = settings.getString("Serverurl", "http://tbserver.ap01.aws.af.cm/");
// ConfigData.deep = settings.getInt("deep", 30);
// ConfigData.maxCombo = settings.getString("maxCombo", "0");
// ConfigData.gap = settings.getString("gap","70");
// ConfigData.DeviceName = settings.getString("DeviceName","Auto");
// ConfigData.touchEventNum = settings.getString("touchEventNum","");
// ConfigData.posXId = settings.getString("posXId","");
// ConfigData.posYId = settings.getString("posYId","");
// ConfigData.posXMax = settings.getString("posXMax","");
// ConfigData.posYMax = settings.getString("posYMax","");
// ConfigData.trackingId = settings.getString("trackingId","");
// ConfigData.pressureId = settings.getString("pressureId","");
// ConfigData.trackingMax = settings.getString("trackingMax","");
// ConfigData.pressureMax = settings.getString("pressureMax","");
// ConfigData.oneBallMove = settings.getString("oneBallMove","");
// ConfigData.startPosX = settings.getString("startPosX","");
// ConfigData.startPosY = settings.getString("startPosY","");
//
// //For Image
// ConfigData.oneOrbWitdh = settings.getInt("oneOrbWitdh", 0);
// ConfigData.boardStartX = settings.getInt("boardStartX", 0);
// ConfigData.boardStartY = settings.getInt("boardStartY", 0);
//
//
// }
//
// }
//
// Path: app/src/main/java/com/tos_bot/puzzleslove/solution.java
// @SuppressLint("NewApi")
// public class solution implements Comparator<solution> {
// public int[][] board;
// public int[][] currentboard;
// public pos cursor;
// public pos initcursor;
// public ArrayList<Integer> path;
// public boolean is_done;
// public ArrayList<matchPair> matches;
// public solution(int[][] inboard,pos c,pos ic,ArrayList<Integer> p,boolean done,ArrayList<matchPair> m){
// board = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// board[i][j] = inboard[i][j];
// cursor = c;
// initcursor = ic;
// path = new ArrayList<Integer>();
// path.addAll(p);
// is_done = done;
// matches = m;
// }
// public solution(){
//
// }
// public int compare(solution a, solution b) {
// return Integer.signum(a.matches.size() - b.matches.size());
// }
// public void setCB(int[][] b){
// currentboard = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// currentboard[i][j] = b[i][j];
// }
//
//
// }
// Path: app/src/main/java/com/tos_bot/touchservice/AbstractTouchService.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import android.os.SystemClock;
import com.tos_bot.ConfigData;
import com.tos_bot.puzzleslove.solution;
package com.tos_bot.touchservice;
public abstract class AbstractTouchService {
private int _ballgap;
private int _inix;
private int _iniy;
public void setUp(int bg, int inix, int iniy) {
_ballgap = bg;
_inix = inix;
_iniy = iniy;
}
public void SendCommand(Vector<String> str) {
Process sh;
try {
sh = Runtime.getRuntime().exec("su", null, null);
OutputStream os = sh.getOutputStream();
for (String s : str) {
os.write(s.getBytes("ASCII"));
os.flush();
}
os.close();
sh.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public Vector<String> getCommandBySol(solution s) { |
eternnoir/ToS_Bot | app/src/main/java/com/tos_bot/touchservice/AbstractTouchService.java | // Path: app/src/main/java/com/tos_bot/ConfigData.java
// public class ConfigData {
// public static String Serverurl;
// public static int eightd = 0; // 0 is no eight direction
// public static int deep = 30; // max move
// public static int waitForStageChageTimeSec = 12;
// public static String DeviceName = "";
// public static Integer StyleName = R.id.Vary_color_Single;
// public static String TempDir = "";
// public static Thread solverThread = null;
// public static String maxCombo = "0"; //0 is no limit
// public static String gap = "70"; //the sleep time between two touch command
// public static int timeOut = 10;
// //For TouchEvent
// public static String touchEventNum;
// public static String posXId;
// public static String posYId;
// public static String posXMax;
// public static String posYMax;
// public static String trackingId;
// public static String pressureId;
// public static String trackingMax;
// public static String pressureMax;
// public static String oneBallMove;
// public static String startPosX;
// public static String startPosY;
// //For Image Setting
// public static int oneOrbWitdh=0;
// public static int boardStartX=0;
// public static int boardStartY=0;
//
//
// public static int MaxOrbType=7;
// public static LinkedHashMap<String, String> baseOrbHash = null;
//
// /**
// * get config data from SharedPreferences
// */
// static public void setConfig(SharedPreferences settings ){
// ConfigData.Serverurl = settings.getString("Serverurl", "http://tbserver.ap01.aws.af.cm/");
// ConfigData.deep = settings.getInt("deep", 30);
// ConfigData.maxCombo = settings.getString("maxCombo", "0");
// ConfigData.gap = settings.getString("gap","70");
// ConfigData.DeviceName = settings.getString("DeviceName","Auto");
// ConfigData.touchEventNum = settings.getString("touchEventNum","");
// ConfigData.posXId = settings.getString("posXId","");
// ConfigData.posYId = settings.getString("posYId","");
// ConfigData.posXMax = settings.getString("posXMax","");
// ConfigData.posYMax = settings.getString("posYMax","");
// ConfigData.trackingId = settings.getString("trackingId","");
// ConfigData.pressureId = settings.getString("pressureId","");
// ConfigData.trackingMax = settings.getString("trackingMax","");
// ConfigData.pressureMax = settings.getString("pressureMax","");
// ConfigData.oneBallMove = settings.getString("oneBallMove","");
// ConfigData.startPosX = settings.getString("startPosX","");
// ConfigData.startPosY = settings.getString("startPosY","");
//
// //For Image
// ConfigData.oneOrbWitdh = settings.getInt("oneOrbWitdh", 0);
// ConfigData.boardStartX = settings.getInt("boardStartX", 0);
// ConfigData.boardStartY = settings.getInt("boardStartY", 0);
//
//
// }
//
// }
//
// Path: app/src/main/java/com/tos_bot/puzzleslove/solution.java
// @SuppressLint("NewApi")
// public class solution implements Comparator<solution> {
// public int[][] board;
// public int[][] currentboard;
// public pos cursor;
// public pos initcursor;
// public ArrayList<Integer> path;
// public boolean is_done;
// public ArrayList<matchPair> matches;
// public solution(int[][] inboard,pos c,pos ic,ArrayList<Integer> p,boolean done,ArrayList<matchPair> m){
// board = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// board[i][j] = inboard[i][j];
// cursor = c;
// initcursor = ic;
// path = new ArrayList<Integer>();
// path.addAll(p);
// is_done = done;
// matches = m;
// }
// public solution(){
//
// }
// public int compare(solution a, solution b) {
// return Integer.signum(a.matches.size() - b.matches.size());
// }
// public void setCB(int[][] b){
// currentboard = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// currentboard[i][j] = b[i][j];
// }
//
//
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import android.os.SystemClock;
import com.tos_bot.ConfigData;
import com.tos_bot.puzzleslove.solution; | ret.addAll(touchDown(inix, iniy));
int nowx = inix;
int nowy = iniy;
// step 2. add path
for (Integer p : s.path) {
touchpos pos = changePathToPos(p);
int passx = nowx;
int passy = nowy;
nowx += pos.x;
nowy += pos.y;
ret.addAll(touchMove(passx, passy, nowx, nowy, 1));
}
ret.addAll(touchUp());
return ret;
}
public Vector<String> getCommandByPath(int inith, int initw,
String[] pathsetp) {
Vector<String> ret = new Vector<String>();
// step 1. get init
int inix = _inix + initw * _ballgap;
int iniy = _iniy + inith * _ballgap;
ret.addAll(touchDown(inix, iniy));
SystemClock.sleep(100);
int nowx = inix;
int nowy = iniy;
// step 2. add path | // Path: app/src/main/java/com/tos_bot/ConfigData.java
// public class ConfigData {
// public static String Serverurl;
// public static int eightd = 0; // 0 is no eight direction
// public static int deep = 30; // max move
// public static int waitForStageChageTimeSec = 12;
// public static String DeviceName = "";
// public static Integer StyleName = R.id.Vary_color_Single;
// public static String TempDir = "";
// public static Thread solverThread = null;
// public static String maxCombo = "0"; //0 is no limit
// public static String gap = "70"; //the sleep time between two touch command
// public static int timeOut = 10;
// //For TouchEvent
// public static String touchEventNum;
// public static String posXId;
// public static String posYId;
// public static String posXMax;
// public static String posYMax;
// public static String trackingId;
// public static String pressureId;
// public static String trackingMax;
// public static String pressureMax;
// public static String oneBallMove;
// public static String startPosX;
// public static String startPosY;
// //For Image Setting
// public static int oneOrbWitdh=0;
// public static int boardStartX=0;
// public static int boardStartY=0;
//
//
// public static int MaxOrbType=7;
// public static LinkedHashMap<String, String> baseOrbHash = null;
//
// /**
// * get config data from SharedPreferences
// */
// static public void setConfig(SharedPreferences settings ){
// ConfigData.Serverurl = settings.getString("Serverurl", "http://tbserver.ap01.aws.af.cm/");
// ConfigData.deep = settings.getInt("deep", 30);
// ConfigData.maxCombo = settings.getString("maxCombo", "0");
// ConfigData.gap = settings.getString("gap","70");
// ConfigData.DeviceName = settings.getString("DeviceName","Auto");
// ConfigData.touchEventNum = settings.getString("touchEventNum","");
// ConfigData.posXId = settings.getString("posXId","");
// ConfigData.posYId = settings.getString("posYId","");
// ConfigData.posXMax = settings.getString("posXMax","");
// ConfigData.posYMax = settings.getString("posYMax","");
// ConfigData.trackingId = settings.getString("trackingId","");
// ConfigData.pressureId = settings.getString("pressureId","");
// ConfigData.trackingMax = settings.getString("trackingMax","");
// ConfigData.pressureMax = settings.getString("pressureMax","");
// ConfigData.oneBallMove = settings.getString("oneBallMove","");
// ConfigData.startPosX = settings.getString("startPosX","");
// ConfigData.startPosY = settings.getString("startPosY","");
//
// //For Image
// ConfigData.oneOrbWitdh = settings.getInt("oneOrbWitdh", 0);
// ConfigData.boardStartX = settings.getInt("boardStartX", 0);
// ConfigData.boardStartY = settings.getInt("boardStartY", 0);
//
//
// }
//
// }
//
// Path: app/src/main/java/com/tos_bot/puzzleslove/solution.java
// @SuppressLint("NewApi")
// public class solution implements Comparator<solution> {
// public int[][] board;
// public int[][] currentboard;
// public pos cursor;
// public pos initcursor;
// public ArrayList<Integer> path;
// public boolean is_done;
// public ArrayList<matchPair> matches;
// public solution(int[][] inboard,pos c,pos ic,ArrayList<Integer> p,boolean done,ArrayList<matchPair> m){
// board = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// board[i][j] = inboard[i][j];
// cursor = c;
// initcursor = ic;
// path = new ArrayList<Integer>();
// path.addAll(p);
// is_done = done;
// matches = m;
// }
// public solution(){
//
// }
// public int compare(solution a, solution b) {
// return Integer.signum(a.matches.size() - b.matches.size());
// }
// public void setCB(int[][] b){
// currentboard = new int[5][6];
// for(int i =0;i<5;i++)
// for(int j=0;j<6;j++)
// currentboard[i][j] = b[i][j];
// }
//
//
// }
// Path: app/src/main/java/com/tos_bot/touchservice/AbstractTouchService.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import android.os.SystemClock;
import com.tos_bot.ConfigData;
import com.tos_bot.puzzleslove.solution;
ret.addAll(touchDown(inix, iniy));
int nowx = inix;
int nowy = iniy;
// step 2. add path
for (Integer p : s.path) {
touchpos pos = changePathToPos(p);
int passx = nowx;
int passy = nowy;
nowx += pos.x;
nowy += pos.y;
ret.addAll(touchMove(passx, passy, nowx, nowy, 1));
}
ret.addAll(touchUp());
return ret;
}
public Vector<String> getCommandByPath(int inith, int initw,
String[] pathsetp) {
Vector<String> ret = new Vector<String>();
// step 1. get init
int inix = _inix + initw * _ballgap;
int iniy = _iniy + inith * _ballgap;
ret.addAll(touchDown(inix, iniy));
SystemClock.sleep(100);
int nowx = inix;
int nowy = iniy;
// step 2. add path | int gap = Integer.parseInt(ConfigData.gap); |
eternnoir/ToS_Bot | app/src/main/java/com/tos_bot/board/BoardManager.java | // Path: app/src/main/java/com/tos_bot/ConfigData.java
// public class ConfigData {
// public static String Serverurl;
// public static int eightd = 0; // 0 is no eight direction
// public static int deep = 30; // max move
// public static int waitForStageChageTimeSec = 12;
// public static String DeviceName = "";
// public static Integer StyleName = R.id.Vary_color_Single;
// public static String TempDir = "";
// public static Thread solverThread = null;
// public static String maxCombo = "0"; //0 is no limit
// public static String gap = "70"; //the sleep time between two touch command
// public static int timeOut = 10;
// //For TouchEvent
// public static String touchEventNum;
// public static String posXId;
// public static String posYId;
// public static String posXMax;
// public static String posYMax;
// public static String trackingId;
// public static String pressureId;
// public static String trackingMax;
// public static String pressureMax;
// public static String oneBallMove;
// public static String startPosX;
// public static String startPosY;
// //For Image Setting
// public static int oneOrbWitdh=0;
// public static int boardStartX=0;
// public static int boardStartY=0;
//
//
// public static int MaxOrbType=7;
// public static LinkedHashMap<String, String> baseOrbHash = null;
//
// /**
// * get config data from SharedPreferences
// */
// static public void setConfig(SharedPreferences settings ){
// ConfigData.Serverurl = settings.getString("Serverurl", "http://tbserver.ap01.aws.af.cm/");
// ConfigData.deep = settings.getInt("deep", 30);
// ConfigData.maxCombo = settings.getString("maxCombo", "0");
// ConfigData.gap = settings.getString("gap","70");
// ConfigData.DeviceName = settings.getString("DeviceName","Auto");
// ConfigData.touchEventNum = settings.getString("touchEventNum","");
// ConfigData.posXId = settings.getString("posXId","");
// ConfigData.posYId = settings.getString("posYId","");
// ConfigData.posXMax = settings.getString("posXMax","");
// ConfigData.posYMax = settings.getString("posYMax","");
// ConfigData.trackingId = settings.getString("trackingId","");
// ConfigData.pressureId = settings.getString("pressureId","");
// ConfigData.trackingMax = settings.getString("trackingMax","");
// ConfigData.pressureMax = settings.getString("pressureMax","");
// ConfigData.oneBallMove = settings.getString("oneBallMove","");
// ConfigData.startPosX = settings.getString("startPosX","");
// ConfigData.startPosY = settings.getString("startPosY","");
//
// //For Image
// ConfigData.oneOrbWitdh = settings.getInt("oneOrbWitdh", 0);
// ConfigData.boardStartX = settings.getInt("boardStartX", 0);
// ConfigData.boardStartY = settings.getInt("boardStartY", 0);
//
//
// }
//
// }
//
// Path: app/src/main/java/com/tos_bot/NotInTosException.java
// public class NotInTosException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// }
| import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.tos_bot.ConfigData;
import com.tos_bot.NotInTosException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log; | package com.tos_bot.board;
public class BoardManager {
static String _Path = "";
private BoardManager() {
}
| // Path: app/src/main/java/com/tos_bot/ConfigData.java
// public class ConfigData {
// public static String Serverurl;
// public static int eightd = 0; // 0 is no eight direction
// public static int deep = 30; // max move
// public static int waitForStageChageTimeSec = 12;
// public static String DeviceName = "";
// public static Integer StyleName = R.id.Vary_color_Single;
// public static String TempDir = "";
// public static Thread solverThread = null;
// public static String maxCombo = "0"; //0 is no limit
// public static String gap = "70"; //the sleep time between two touch command
// public static int timeOut = 10;
// //For TouchEvent
// public static String touchEventNum;
// public static String posXId;
// public static String posYId;
// public static String posXMax;
// public static String posYMax;
// public static String trackingId;
// public static String pressureId;
// public static String trackingMax;
// public static String pressureMax;
// public static String oneBallMove;
// public static String startPosX;
// public static String startPosY;
// //For Image Setting
// public static int oneOrbWitdh=0;
// public static int boardStartX=0;
// public static int boardStartY=0;
//
//
// public static int MaxOrbType=7;
// public static LinkedHashMap<String, String> baseOrbHash = null;
//
// /**
// * get config data from SharedPreferences
// */
// static public void setConfig(SharedPreferences settings ){
// ConfigData.Serverurl = settings.getString("Serverurl", "http://tbserver.ap01.aws.af.cm/");
// ConfigData.deep = settings.getInt("deep", 30);
// ConfigData.maxCombo = settings.getString("maxCombo", "0");
// ConfigData.gap = settings.getString("gap","70");
// ConfigData.DeviceName = settings.getString("DeviceName","Auto");
// ConfigData.touchEventNum = settings.getString("touchEventNum","");
// ConfigData.posXId = settings.getString("posXId","");
// ConfigData.posYId = settings.getString("posYId","");
// ConfigData.posXMax = settings.getString("posXMax","");
// ConfigData.posYMax = settings.getString("posYMax","");
// ConfigData.trackingId = settings.getString("trackingId","");
// ConfigData.pressureId = settings.getString("pressureId","");
// ConfigData.trackingMax = settings.getString("trackingMax","");
// ConfigData.pressureMax = settings.getString("pressureMax","");
// ConfigData.oneBallMove = settings.getString("oneBallMove","");
// ConfigData.startPosX = settings.getString("startPosX","");
// ConfigData.startPosY = settings.getString("startPosY","");
//
// //For Image
// ConfigData.oneOrbWitdh = settings.getInt("oneOrbWitdh", 0);
// ConfigData.boardStartX = settings.getInt("boardStartX", 0);
// ConfigData.boardStartY = settings.getInt("boardStartY", 0);
//
//
// }
//
// }
//
// Path: app/src/main/java/com/tos_bot/NotInTosException.java
// public class NotInTosException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// }
// Path: app/src/main/java/com/tos_bot/board/BoardManager.java
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.tos_bot.ConfigData;
import com.tos_bot.NotInTosException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;
package com.tos_bot.board;
public class BoardManager {
static String _Path = "";
private BoardManager() {
}
| public static int[][] getBallArray() throws NotInTosException { |
eternnoir/ToS_Bot | app/src/main/java/com/tos_bot/board/BoardManager.java | // Path: app/src/main/java/com/tos_bot/ConfigData.java
// public class ConfigData {
// public static String Serverurl;
// public static int eightd = 0; // 0 is no eight direction
// public static int deep = 30; // max move
// public static int waitForStageChageTimeSec = 12;
// public static String DeviceName = "";
// public static Integer StyleName = R.id.Vary_color_Single;
// public static String TempDir = "";
// public static Thread solverThread = null;
// public static String maxCombo = "0"; //0 is no limit
// public static String gap = "70"; //the sleep time between two touch command
// public static int timeOut = 10;
// //For TouchEvent
// public static String touchEventNum;
// public static String posXId;
// public static String posYId;
// public static String posXMax;
// public static String posYMax;
// public static String trackingId;
// public static String pressureId;
// public static String trackingMax;
// public static String pressureMax;
// public static String oneBallMove;
// public static String startPosX;
// public static String startPosY;
// //For Image Setting
// public static int oneOrbWitdh=0;
// public static int boardStartX=0;
// public static int boardStartY=0;
//
//
// public static int MaxOrbType=7;
// public static LinkedHashMap<String, String> baseOrbHash = null;
//
// /**
// * get config data from SharedPreferences
// */
// static public void setConfig(SharedPreferences settings ){
// ConfigData.Serverurl = settings.getString("Serverurl", "http://tbserver.ap01.aws.af.cm/");
// ConfigData.deep = settings.getInt("deep", 30);
// ConfigData.maxCombo = settings.getString("maxCombo", "0");
// ConfigData.gap = settings.getString("gap","70");
// ConfigData.DeviceName = settings.getString("DeviceName","Auto");
// ConfigData.touchEventNum = settings.getString("touchEventNum","");
// ConfigData.posXId = settings.getString("posXId","");
// ConfigData.posYId = settings.getString("posYId","");
// ConfigData.posXMax = settings.getString("posXMax","");
// ConfigData.posYMax = settings.getString("posYMax","");
// ConfigData.trackingId = settings.getString("trackingId","");
// ConfigData.pressureId = settings.getString("pressureId","");
// ConfigData.trackingMax = settings.getString("trackingMax","");
// ConfigData.pressureMax = settings.getString("pressureMax","");
// ConfigData.oneBallMove = settings.getString("oneBallMove","");
// ConfigData.startPosX = settings.getString("startPosX","");
// ConfigData.startPosY = settings.getString("startPosY","");
//
// //For Image
// ConfigData.oneOrbWitdh = settings.getInt("oneOrbWitdh", 0);
// ConfigData.boardStartX = settings.getInt("boardStartX", 0);
// ConfigData.boardStartY = settings.getInt("boardStartY", 0);
//
//
// }
//
// }
//
// Path: app/src/main/java/com/tos_bot/NotInTosException.java
// public class NotInTosException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// }
| import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.tos_bot.ConfigData;
import com.tos_bot.NotInTosException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log; | package com.tos_bot.board;
public class BoardManager {
static String _Path = "";
private BoardManager() {
}
public static int[][] getBallArray() throws NotInTosException {
IBoardProcesser bp = new TosBoardProcesser();
return bp.getBoardOrbArrary();
}
public static void setOrbHash(){
TosBoardProcesser bp = new TosBoardProcesser(); | // Path: app/src/main/java/com/tos_bot/ConfigData.java
// public class ConfigData {
// public static String Serverurl;
// public static int eightd = 0; // 0 is no eight direction
// public static int deep = 30; // max move
// public static int waitForStageChageTimeSec = 12;
// public static String DeviceName = "";
// public static Integer StyleName = R.id.Vary_color_Single;
// public static String TempDir = "";
// public static Thread solverThread = null;
// public static String maxCombo = "0"; //0 is no limit
// public static String gap = "70"; //the sleep time between two touch command
// public static int timeOut = 10;
// //For TouchEvent
// public static String touchEventNum;
// public static String posXId;
// public static String posYId;
// public static String posXMax;
// public static String posYMax;
// public static String trackingId;
// public static String pressureId;
// public static String trackingMax;
// public static String pressureMax;
// public static String oneBallMove;
// public static String startPosX;
// public static String startPosY;
// //For Image Setting
// public static int oneOrbWitdh=0;
// public static int boardStartX=0;
// public static int boardStartY=0;
//
//
// public static int MaxOrbType=7;
// public static LinkedHashMap<String, String> baseOrbHash = null;
//
// /**
// * get config data from SharedPreferences
// */
// static public void setConfig(SharedPreferences settings ){
// ConfigData.Serverurl = settings.getString("Serverurl", "http://tbserver.ap01.aws.af.cm/");
// ConfigData.deep = settings.getInt("deep", 30);
// ConfigData.maxCombo = settings.getString("maxCombo", "0");
// ConfigData.gap = settings.getString("gap","70");
// ConfigData.DeviceName = settings.getString("DeviceName","Auto");
// ConfigData.touchEventNum = settings.getString("touchEventNum","");
// ConfigData.posXId = settings.getString("posXId","");
// ConfigData.posYId = settings.getString("posYId","");
// ConfigData.posXMax = settings.getString("posXMax","");
// ConfigData.posYMax = settings.getString("posYMax","");
// ConfigData.trackingId = settings.getString("trackingId","");
// ConfigData.pressureId = settings.getString("pressureId","");
// ConfigData.trackingMax = settings.getString("trackingMax","");
// ConfigData.pressureMax = settings.getString("pressureMax","");
// ConfigData.oneBallMove = settings.getString("oneBallMove","");
// ConfigData.startPosX = settings.getString("startPosX","");
// ConfigData.startPosY = settings.getString("startPosY","");
//
// //For Image
// ConfigData.oneOrbWitdh = settings.getInt("oneOrbWitdh", 0);
// ConfigData.boardStartX = settings.getInt("boardStartX", 0);
// ConfigData.boardStartY = settings.getInt("boardStartY", 0);
//
//
// }
//
// }
//
// Path: app/src/main/java/com/tos_bot/NotInTosException.java
// public class NotInTosException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// }
// Path: app/src/main/java/com/tos_bot/board/BoardManager.java
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.tos_bot.ConfigData;
import com.tos_bot.NotInTosException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;
package com.tos_bot.board;
public class BoardManager {
static String _Path = "";
private BoardManager() {
}
public static int[][] getBallArray() throws NotInTosException {
IBoardProcesser bp = new TosBoardProcesser();
return bp.getBoardOrbArrary();
}
public static void setOrbHash(){
TosBoardProcesser bp = new TosBoardProcesser(); | ConfigData.baseOrbHash = bp.getBaseOrbFingerPrintMap(); |
eternnoir/ToS_Bot | app/src/main/java/com/tos_bot/ImageSettingActivity.java | // Path: app/src/main/java/com/tos_bot/board/BoardManager.java
// public class BoardManager {
// static String _Path = "";
//
// private BoardManager() {
//
// }
//
// public static int[][] getBallArray() throws NotInTosException {
// IBoardProcesser bp = new TosBoardProcesser();
// return bp.getBoardOrbArrary();
// }
// public static void setOrbHash(){
// TosBoardProcesser bp = new TosBoardProcesser();
// ConfigData.baseOrbHash = bp.getBaseOrbFingerPrintMap();
// }
//
// }
| import com.tos_bot.board.BoardManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; | getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void loadSetting() {
SharedPreferences settings = getSharedPreferences("Config", 0);
oneOrbWitdh.setText(settings.getInt("oneOrbWitdh", 0)+"");
posX.setText(settings.getInt("boardStartX", 0)+"");
posY.setText(settings.getInt("boardStartY", 0)+"");
}
private void saveSetting() {
SharedPreferences settings = getSharedPreferences("Config", 0);
settings.edit()
.putInt("oneOrbWitdh",
Integer.parseInt(oneOrbWitdh.getText().toString()))
.commit();
settings.edit()
.putInt("boardStartX",
Integer.parseInt(posX.getText().toString())).commit();
settings.edit()
.putInt("boardStartY",
Integer.parseInt(posY.getText().toString())).commit();
}
private String getBoardFromPic() {
Log.i("Bot:", "Use Data Frome Pic");
int[][] orbArray;
try { | // Path: app/src/main/java/com/tos_bot/board/BoardManager.java
// public class BoardManager {
// static String _Path = "";
//
// private BoardManager() {
//
// }
//
// public static int[][] getBallArray() throws NotInTosException {
// IBoardProcesser bp = new TosBoardProcesser();
// return bp.getBoardOrbArrary();
// }
// public static void setOrbHash(){
// TosBoardProcesser bp = new TosBoardProcesser();
// ConfigData.baseOrbHash = bp.getBaseOrbFingerPrintMap();
// }
//
// }
// Path: app/src/main/java/com/tos_bot/ImageSettingActivity.java
import com.tos_bot.board.BoardManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void loadSetting() {
SharedPreferences settings = getSharedPreferences("Config", 0);
oneOrbWitdh.setText(settings.getInt("oneOrbWitdh", 0)+"");
posX.setText(settings.getInt("boardStartX", 0)+"");
posY.setText(settings.getInt("boardStartY", 0)+"");
}
private void saveSetting() {
SharedPreferences settings = getSharedPreferences("Config", 0);
settings.edit()
.putInt("oneOrbWitdh",
Integer.parseInt(oneOrbWitdh.getText().toString()))
.commit();
settings.edit()
.putInt("boardStartX",
Integer.parseInt(posX.getText().toString())).commit();
settings.edit()
.putInt("boardStartY",
Integer.parseInt(posY.getText().toString())).commit();
}
private String getBoardFromPic() {
Log.i("Bot:", "Use Data Frome Pic");
int[][] orbArray;
try { | orbArray = BoardManager.getBallArray(); |
eternnoir/ToS_Bot | app/src/main/java/com/tos_bot/ui/TosImageButton.java | // Path: app/src/main/java/com/tos_bot/utility/FileLoader.java
// public class FileLoader {
// private static Context ctx = null;
// private FileLoader(){
//
// }
// static public void setContext(Context c){
// ctx = c;
// }
//
// static public InputStream getFileStreamByAsset(String path){
// assert(ctx!=null);
// AssetManager am = ctx.getAssets();
// try {
// return am.open(path);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// return null;
// }
// }
// }
| import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageButton;
import com.tos_bot.utility.FileLoader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream; | package com.tos_bot.ui;
/**
* Created by Sean.
*/
public abstract class TosImageButton extends ImageButton{
public TosImageButton(Context context) {
super(context);
}
protected Bitmap resizeImage(Bitmap srcImage, double ratio){
return srcImage;
/*
return Bitmap.createScaledBitmap(
srcImage,
(int) (srcImage.getWidth() * ratio),
(int) (srcImage.getHeight() * ratio),
false);
*/
}
protected Bitmap getBitmapByFilename(String filename, double ratio) { | // Path: app/src/main/java/com/tos_bot/utility/FileLoader.java
// public class FileLoader {
// private static Context ctx = null;
// private FileLoader(){
//
// }
// static public void setContext(Context c){
// ctx = c;
// }
//
// static public InputStream getFileStreamByAsset(String path){
// assert(ctx!=null);
// AssetManager am = ctx.getAssets();
// try {
// return am.open(path);
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: app/src/main/java/com/tos_bot/ui/TosImageButton.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageButton;
import com.tos_bot.utility.FileLoader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
package com.tos_bot.ui;
/**
* Created by Sean.
*/
public abstract class TosImageButton extends ImageButton{
public TosImageButton(Context context) {
super(context);
}
protected Bitmap resizeImage(Bitmap srcImage, double ratio){
return srcImage;
/*
return Bitmap.createScaledBitmap(
srcImage,
(int) (srcImage.getWidth() * ratio),
(int) (srcImage.getHeight() * ratio),
false);
*/
}
protected Bitmap getBitmapByFilename(String filename, double ratio) { | FileLoader.setContext(this.getContext()); |
eternnoir/ToS_Bot | app/src/main/java/com/tos_bot/ui/StrategyImageButton.java | // Path: app/src/main/java/com/tos_bot/Constants.java
// public class Constants {
// public static final LinkedHashMap<Integer, String> IdStringMap = new LinkedHashMap<Integer, String>() {
// {
// put(R.id.Vary_color_Single, "Vary_color_Single");
// put(R.id.Vary_color_Multi, "Vary_color_Multi");
// put(R.id.Water_Single, "Water_Single");
// put(R.id.Water_Multi, "Water_Multi");
// put(R.id.Fire_Single, "Fire_Single");
// put(R.id.Fire_Multi, "Fire_Multi");
// put(R.id.Wood_Single, "Wood_Single");
// put(R.id.Wood_Multi, "Wood_Multi");
// put(R.id.Light_Single, "Light_Single");
// put(R.id.Light_Multi, "Light_Multi");
// put(R.id.Dark_Single, "Dark_Single");
// put(R.id.Dark_Multi, "Dark_Multi");
// put(R.id.Recover_Single, "Recover_Single");
// put(R.id.Recover_Multi, "Recover_Multi");
// put(R.id.Water_Except, "Water_Except");
// put(R.id.Fire_Except, "Fire_Except");
// put(R.id.Wood_Except, "Wood_Except");
// put(R.id.Light_Except, "Light_Except");
// put(R.id.Dark_Except, "Dark_Except");
// put(R.id.Recover_Except, "Recover_Except");
// put(R.id.Low_HP_Single, "Low_HP_Single");
// put(R.id.Low_HP_Multi, "Low_HP_Multi");
// }
// };
//
// public static final int STANDARD_X = 720;
// public static final int STANDARD_Y = 1280;
// public static final double LEFT_TOP_WIDGET_X = 0;
// public static final double LEFT_TOP_WIDGET_Y = 0;
// public static final double SEEK_BAR_WIDTH = 2D / 3D;
// public static final double STEP_SEEK_BAR_X = 1D / 5D;
// public static final double STEP_SEEK_BAR_Y = 0;
// public static final int STEP_SEEK_BAR_MAX = 100;
// public static final double COMBO_SEEK_BAR_X = STEP_SEEK_BAR_X;
// public static final double COMBO_SEEK_BAR_Y = 1D / 12D;
// public static final int COMBO_SEEK_BAR_MAX = 8;
// public static final double SEEK_BAR_TEXT_X = STEP_SEEK_BAR_X + SEEK_BAR_WIDTH;
// public static final int SEEK_BAR_TEXT_SIZE = 20;
// }
| import android.content.Context;
import android.graphics.Bitmap;
import com.tos_bot.Constants; | package com.tos_bot.ui;
/**
* Created by Sean.
*/
public class StrategyImageButton extends TosImageButton {
public StrategyImageButton(Context context){
super(context);
this.getBackground().setAlpha(0);
}
public void setUpImage(Integer styleName, double ratio){ | // Path: app/src/main/java/com/tos_bot/Constants.java
// public class Constants {
// public static final LinkedHashMap<Integer, String> IdStringMap = new LinkedHashMap<Integer, String>() {
// {
// put(R.id.Vary_color_Single, "Vary_color_Single");
// put(R.id.Vary_color_Multi, "Vary_color_Multi");
// put(R.id.Water_Single, "Water_Single");
// put(R.id.Water_Multi, "Water_Multi");
// put(R.id.Fire_Single, "Fire_Single");
// put(R.id.Fire_Multi, "Fire_Multi");
// put(R.id.Wood_Single, "Wood_Single");
// put(R.id.Wood_Multi, "Wood_Multi");
// put(R.id.Light_Single, "Light_Single");
// put(R.id.Light_Multi, "Light_Multi");
// put(R.id.Dark_Single, "Dark_Single");
// put(R.id.Dark_Multi, "Dark_Multi");
// put(R.id.Recover_Single, "Recover_Single");
// put(R.id.Recover_Multi, "Recover_Multi");
// put(R.id.Water_Except, "Water_Except");
// put(R.id.Fire_Except, "Fire_Except");
// put(R.id.Wood_Except, "Wood_Except");
// put(R.id.Light_Except, "Light_Except");
// put(R.id.Dark_Except, "Dark_Except");
// put(R.id.Recover_Except, "Recover_Except");
// put(R.id.Low_HP_Single, "Low_HP_Single");
// put(R.id.Low_HP_Multi, "Low_HP_Multi");
// }
// };
//
// public static final int STANDARD_X = 720;
// public static final int STANDARD_Y = 1280;
// public static final double LEFT_TOP_WIDGET_X = 0;
// public static final double LEFT_TOP_WIDGET_Y = 0;
// public static final double SEEK_BAR_WIDTH = 2D / 3D;
// public static final double STEP_SEEK_BAR_X = 1D / 5D;
// public static final double STEP_SEEK_BAR_Y = 0;
// public static final int STEP_SEEK_BAR_MAX = 100;
// public static final double COMBO_SEEK_BAR_X = STEP_SEEK_BAR_X;
// public static final double COMBO_SEEK_BAR_Y = 1D / 12D;
// public static final int COMBO_SEEK_BAR_MAX = 8;
// public static final double SEEK_BAR_TEXT_X = STEP_SEEK_BAR_X + SEEK_BAR_WIDTH;
// public static final int SEEK_BAR_TEXT_SIZE = 20;
// }
// Path: app/src/main/java/com/tos_bot/ui/StrategyImageButton.java
import android.content.Context;
import android.graphics.Bitmap;
import com.tos_bot.Constants;
package com.tos_bot.ui;
/**
* Created by Sean.
*/
public class StrategyImageButton extends TosImageButton {
public StrategyImageButton(Context context){
super(context);
this.getBackground().setAlpha(0);
}
public void setUpImage(Integer styleName, double ratio){ | Bitmap srcImage = getBitmapByFilename(Constants.IdStringMap.get(styleName),ratio); |
playn/playn | tests/core/src/main/java/playn/tests/core/Test.java | // Path: tests/core/src/main/java/playn/tests/core/TestsGame.java
// public static TestsGame game;
| import react.Closeable;
import react.SignalView;
import playn.core.*;
import playn.scene.*;
import static playn.tests.core.TestsGame.game; | /**
* Copyright 2011 The PlayN Authors
*
* 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 playn.tests.core;
public abstract class Test {
public static final int UPDATE_RATE = 25;
public final String name;
public final String descrip;
| // Path: tests/core/src/main/java/playn/tests/core/TestsGame.java
// public static TestsGame game;
// Path: tests/core/src/main/java/playn/tests/core/Test.java
import react.Closeable;
import react.SignalView;
import playn.core.*;
import playn.scene.*;
import static playn.tests.core.TestsGame.game;
/**
* Copyright 2011 The PlayN Authors
*
* 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 playn.tests.core;
public abstract class Test {
public static final int UPDATE_RATE = 25;
public final String name;
public final String descrip;
| protected final TestsGame game; |
playn/playn | java-swt/src/playn/java/SWTGraphics.java | // Path: core/src/playn/core/Scale.java
// public class Scale {
//
// /** Used by {@link #getScaledResources}. */
// public static class ScaledResource {
// /** The scale factor for this resource. */
// public final Scale scale;
//
// /**
// * The path to the resource, including any scale factor annotation. If the scale is one, the
// * image path is unadjusted. If the scale is greater than one, the scale is tacked onto the
// * image path (before the extension). The scale factor will be converted to an integer per the
// * following examples:
// * <ul>
// * <li> Scale factor 2: {@code foo.png} becomes {@code foo@2x.png}</li>
// * <li> Scale factor 4: {@code foo.png} becomes {@code foo@4x.png}</li>
// * <li> Scale factor 1.5: {@code foo.png} becomes {@code foo@15x.png}</li>
// * <li> Scale factor 1.25: {@code foo.png} becomes {@code foo@13x.png}</li>
// * </ul>
// */
// public final String path;
//
// public ScaledResource(Scale scale, String path) {
// this.scale = scale;
// this.path = path;
// }
//
// @Override public String toString () {
// return scale + ": " + path;
// }
// }
//
// /** An unscaled scale factor singleton. */
// public static final Scale ONE = new Scale(1);
//
// /** The scale factor for HiDPI mode, or 1 if HDPI mode is not enabled. */
// public final float factor;
//
// public Scale (float factor) {
// assert factor > 0 : "Scale factor must be > 0.";
// this.factor = factor;
// }
//
// /** Returns the supplied length scaled by our scale factor. */
// public float scaled(float length) {
// return factor*length;
// }
//
// /** Returns the supplied length scaled by our scale factor and rounded up. */
// public int scaledCeil(float length) {
// return MathUtil.iceil(scaled(length));
// }
//
// /** Returns the supplied length scaled by our scale factor and rounded down. */
// public int scaledFloor(float length) {
// return MathUtil.ifloor(scaled(length));
// }
//
// /** Returns the supplied length inverse scaled by our scale factor. */
// public float invScaled(float length) {
// return length/factor;
// }
//
// /** Returns the supplied length inverse scaled by our scale factor and rounded down. */
// public int invScaledFloor(float length) {
// return MathUtil.ifloor(invScaled(length));
// }
//
// /** Returns the supplied length inverse scaled by our scale factor and rounded up. */
// public int invScaledCeil(float length) {
// return MathUtil.iceil(invScaled(length));
// }
//
// /**
// * Rounds the supplied length to the nearest length value that corresponds to an integer
// * pixel length after the scale factor is applied. For example, for a scale factor of 3,
// * scale.roundToNearestPixel(8.4) = 8.33, which corresponds to exactly (8.33 * 3)= 25 pixels.
// */
// public float roundToNearestPixel(float length) {
// return MathUtil.round(length * factor) / factor;
// }
//
// /**
// * Returns an ordered series of scaled resources to try when loading an asset. The native
// * resolution will be tried first, then that will be rounded up to the nearest whole integer and
// * stepped down through all whole integers to {@code 1}. If the native scale factor is {@code 2},
// * this will yield {@code 2, 1}. If the native scale factor is {@code 4}, this will yield
// * {@code 4, 3, 2, 1}. Android devices often have fractional scale factors, which demonstrates
// * the rounding up then back down approach: a native scale factor of {@code 2.5} would yield
// * {@code 2.5, 3, 2, 1}.
// */
// public List<ScaledResource> getScaledResources(String path) {
// List<ScaledResource> rsrcs = new ArrayList<ScaledResource>();
// rsrcs.add(new ScaledResource(this, computePath(path, factor)));
// for (float rscale = MathUtil.iceil(factor); rscale > 1; rscale -= 1) {
// if (rscale != factor) rsrcs.add(
// new ScaledResource(new Scale(rscale), computePath(path, rscale)));
// }
// rsrcs.add(new ScaledResource(ONE, path));
// return rsrcs;
// }
//
// @Override
// public String toString() {
// return "x" + factor;
// }
//
// private String computePath(String path, float scale) {
// if (scale <= 1) return path;
// int scaleFactor = (int)(scale * 10);
// if (scaleFactor % 10 == 0)
// scaleFactor /= 10;
// int didx = path.lastIndexOf(".");
// if (didx == -1) {
// return path; // no extension!?
// } else {
// return path.substring(0, didx) + "@" + scaleFactor + "x" + path.substring(didx);
// }
// }
// }
| import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.opengl.GLCanvas;
import org.eclipse.swt.opengl.GLData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.lwjgl.opengl.GL;
import playn.core.Scale;
import pythagoras.f.Dimension;
import pythagoras.f.IDimension; | /**
* Copyright 2010 The PlayN Authors
*
* 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 playn.java;
public class SWTGraphics extends LWJGLGraphics {
public static class Hack { | // Path: core/src/playn/core/Scale.java
// public class Scale {
//
// /** Used by {@link #getScaledResources}. */
// public static class ScaledResource {
// /** The scale factor for this resource. */
// public final Scale scale;
//
// /**
// * The path to the resource, including any scale factor annotation. If the scale is one, the
// * image path is unadjusted. If the scale is greater than one, the scale is tacked onto the
// * image path (before the extension). The scale factor will be converted to an integer per the
// * following examples:
// * <ul>
// * <li> Scale factor 2: {@code foo.png} becomes {@code foo@2x.png}</li>
// * <li> Scale factor 4: {@code foo.png} becomes {@code foo@4x.png}</li>
// * <li> Scale factor 1.5: {@code foo.png} becomes {@code foo@15x.png}</li>
// * <li> Scale factor 1.25: {@code foo.png} becomes {@code foo@13x.png}</li>
// * </ul>
// */
// public final String path;
//
// public ScaledResource(Scale scale, String path) {
// this.scale = scale;
// this.path = path;
// }
//
// @Override public String toString () {
// return scale + ": " + path;
// }
// }
//
// /** An unscaled scale factor singleton. */
// public static final Scale ONE = new Scale(1);
//
// /** The scale factor for HiDPI mode, or 1 if HDPI mode is not enabled. */
// public final float factor;
//
// public Scale (float factor) {
// assert factor > 0 : "Scale factor must be > 0.";
// this.factor = factor;
// }
//
// /** Returns the supplied length scaled by our scale factor. */
// public float scaled(float length) {
// return factor*length;
// }
//
// /** Returns the supplied length scaled by our scale factor and rounded up. */
// public int scaledCeil(float length) {
// return MathUtil.iceil(scaled(length));
// }
//
// /** Returns the supplied length scaled by our scale factor and rounded down. */
// public int scaledFloor(float length) {
// return MathUtil.ifloor(scaled(length));
// }
//
// /** Returns the supplied length inverse scaled by our scale factor. */
// public float invScaled(float length) {
// return length/factor;
// }
//
// /** Returns the supplied length inverse scaled by our scale factor and rounded down. */
// public int invScaledFloor(float length) {
// return MathUtil.ifloor(invScaled(length));
// }
//
// /** Returns the supplied length inverse scaled by our scale factor and rounded up. */
// public int invScaledCeil(float length) {
// return MathUtil.iceil(invScaled(length));
// }
//
// /**
// * Rounds the supplied length to the nearest length value that corresponds to an integer
// * pixel length after the scale factor is applied. For example, for a scale factor of 3,
// * scale.roundToNearestPixel(8.4) = 8.33, which corresponds to exactly (8.33 * 3)= 25 pixels.
// */
// public float roundToNearestPixel(float length) {
// return MathUtil.round(length * factor) / factor;
// }
//
// /**
// * Returns an ordered series of scaled resources to try when loading an asset. The native
// * resolution will be tried first, then that will be rounded up to the nearest whole integer and
// * stepped down through all whole integers to {@code 1}. If the native scale factor is {@code 2},
// * this will yield {@code 2, 1}. If the native scale factor is {@code 4}, this will yield
// * {@code 4, 3, 2, 1}. Android devices often have fractional scale factors, which demonstrates
// * the rounding up then back down approach: a native scale factor of {@code 2.5} would yield
// * {@code 2.5, 3, 2, 1}.
// */
// public List<ScaledResource> getScaledResources(String path) {
// List<ScaledResource> rsrcs = new ArrayList<ScaledResource>();
// rsrcs.add(new ScaledResource(this, computePath(path, factor)));
// for (float rscale = MathUtil.iceil(factor); rscale > 1; rscale -= 1) {
// if (rscale != factor) rsrcs.add(
// new ScaledResource(new Scale(rscale), computePath(path, rscale)));
// }
// rsrcs.add(new ScaledResource(ONE, path));
// return rsrcs;
// }
//
// @Override
// public String toString() {
// return "x" + factor;
// }
//
// private String computePath(String path, float scale) {
// if (scale <= 1) return path;
// int scaleFactor = (int)(scale * 10);
// if (scaleFactor % 10 == 0)
// scaleFactor /= 10;
// int didx = path.lastIndexOf(".");
// if (didx == -1) {
// return path; // no extension!?
// } else {
// return path.substring(0, didx) + "@" + scaleFactor + "x" + path.substring(didx);
// }
// }
// }
// Path: java-swt/src/playn/java/SWTGraphics.java
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.opengl.GLCanvas;
import org.eclipse.swt.opengl.GLData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.lwjgl.opengl.GL;
import playn.core.Scale;
import pythagoras.f.Dimension;
import pythagoras.f.IDimension;
/**
* Copyright 2010 The PlayN Authors
*
* 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 playn.java;
public class SWTGraphics extends LWJGLGraphics {
public static class Hack { | public Scale hackScale () { return Scale.ONE; } |
playn/playn | tests/core/src/main/java/playn/tests/core/PointerMouseTouchTest.java | // Path: tests/core/src/main/java/playn/tests/core/TestsGame.java
// public static TestsGame game;
| import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import pythagoras.f.Point;
import pythagoras.f.Vector;
import react.UnitSlot;
import playn.core.*;
import playn.scene.*;
import playn.scene.Mouse;
import playn.scene.Pointer;
import playn.scene.Touch;
import static playn.tests.core.TestsGame.game; | /**
* Copyright 2012 The PlayN Authors
*
* 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 playn.tests.core;
class PointerMouseTouchTest extends Test {
private TextFormat baseFormat = new TextFormat(new Font("Times New Roman", 20));
private TextFormat logFormat = new TextFormat(new Font("Times New Roman", 12));
private TextLogger logger;
private TextMapper motionLabel;
private TestsGame.Toggle preventDefault, capture;
// private TestsGame.NToggle<String> propagate;
| // Path: tests/core/src/main/java/playn/tests/core/TestsGame.java
// public static TestsGame game;
// Path: tests/core/src/main/java/playn/tests/core/PointerMouseTouchTest.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import pythagoras.f.Point;
import pythagoras.f.Vector;
import react.UnitSlot;
import playn.core.*;
import playn.scene.*;
import playn.scene.Mouse;
import playn.scene.Pointer;
import playn.scene.Touch;
import static playn.tests.core.TestsGame.game;
/**
* Copyright 2012 The PlayN Authors
*
* 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 playn.tests.core;
class PointerMouseTouchTest extends Test {
private TextFormat baseFormat = new TextFormat(new Font("Times New Roman", 20));
private TextFormat logFormat = new TextFormat(new Font("Times New Roman", 12));
private TextLogger logger;
private TextMapper motionLabel;
private TestsGame.Toggle preventDefault, capture;
// private TestsGame.NToggle<String> propagate;
| public PointerMouseTouchTest (TestsGame game) { |
JackFish/jfinal-weixin | src/com/jfinal/weixin/sdk/jfinal/MsgInterceptor.java | // Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
// public class ApiConfigKit {
//
// private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
//
// // 开发模式将输出消息交互 xml 到控制台
// private static boolean devMode = false;
//
// public static void setDevMode(boolean devMode) {
// ApiConfigKit.devMode = devMode;
// }
//
// public static boolean isDevMode() {
// return devMode;
// }
//
// public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
// tl.set(apiConfig);
// }
//
// public static void removeThreadLocalApiConfig() {
// tl.remove();
// }
//
// public static ApiConfig getApiConfig() {
// ApiConfig result = tl.get();
// if (result == null)
// throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
// return result;
// }
//
// static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
//
// public static void setAccessTokenCache(IAccessTokenCache accessTokenCache) {
// ApiConfigKit.accessTokenCache = accessTokenCache;
// }
//
// public static IAccessTokenCache getAccessTokenCache() {
// return ApiConfigKit.accessTokenCache;
// }
// }
| import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.kit.SignatureCheckKit;
import org.slf4j.LoggerFactory; | /**
* Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.sdk.jfinal;
/**
* Msg 拦截器
* 1:通过 MsgController.getApiConfig() 得到 ApiConfig 对象,并将其绑定到当前线程之上(利用了 ApiConfigKit 中的 ThreadLocal 对象)
* 2:响应开发者中心服务器配置 URL 与 Token 请求
* 3:签名检测
* 注意: MsgController 的继承类如果覆盖了 index 方法,则需要对该 index 方法声明该拦截器
* 因为子类覆盖父类方法会使父类方法配置的拦截器失效,从而失去本拦截器的功能
*/
public class MsgInterceptor implements Interceptor {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MsgInterceptor.class);
public void intercept(Invocation inv) {
Controller controller = inv.getController();
if (controller instanceof MsgController == false)
throw new RuntimeException("控制器需要继承 MsgController");
try {
// 将 ApiConfig 对象与当前线程绑定,以便在后续操作中方便获取该对象: ApiConfigKit.getApiConfig(); | // Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
// public class ApiConfigKit {
//
// private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
//
// // 开发模式将输出消息交互 xml 到控制台
// private static boolean devMode = false;
//
// public static void setDevMode(boolean devMode) {
// ApiConfigKit.devMode = devMode;
// }
//
// public static boolean isDevMode() {
// return devMode;
// }
//
// public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
// tl.set(apiConfig);
// }
//
// public static void removeThreadLocalApiConfig() {
// tl.remove();
// }
//
// public static ApiConfig getApiConfig() {
// ApiConfig result = tl.get();
// if (result == null)
// throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
// return result;
// }
//
// static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
//
// public static void setAccessTokenCache(IAccessTokenCache accessTokenCache) {
// ApiConfigKit.accessTokenCache = accessTokenCache;
// }
//
// public static IAccessTokenCache getAccessTokenCache() {
// return ApiConfigKit.accessTokenCache;
// }
// }
// Path: src/com/jfinal/weixin/sdk/jfinal/MsgInterceptor.java
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.kit.SignatureCheckKit;
import org.slf4j.LoggerFactory;
/**
* Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.sdk.jfinal;
/**
* Msg 拦截器
* 1:通过 MsgController.getApiConfig() 得到 ApiConfig 对象,并将其绑定到当前线程之上(利用了 ApiConfigKit 中的 ThreadLocal 对象)
* 2:响应开发者中心服务器配置 URL 与 Token 请求
* 3:签名检测
* 注意: MsgController 的继承类如果覆盖了 index 方法,则需要对该 index 方法声明该拦截器
* 因为子类覆盖父类方法会使父类方法配置的拦截器失效,从而失去本拦截器的功能
*/
public class MsgInterceptor implements Interceptor {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MsgInterceptor.class);
public void intercept(Invocation inv) {
Controller controller = inv.getController();
if (controller instanceof MsgController == false)
throw new RuntimeException("控制器需要继承 MsgController");
try {
// 将 ApiConfig 对象与当前线程绑定,以便在后续操作中方便获取该对象: ApiConfigKit.getApiConfig(); | ApiConfigKit.setThreadLocalApiConfig(((MsgController)controller).getApiConfig()); |
JackFish/jfinal-weixin | src/com/jfinal/weixin/sdk/jfinal/ApiInterceptor.java | // Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
// public class ApiConfigKit {
//
// private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
//
// // 开发模式将输出消息交互 xml 到控制台
// private static boolean devMode = false;
//
// public static void setDevMode(boolean devMode) {
// ApiConfigKit.devMode = devMode;
// }
//
// public static boolean isDevMode() {
// return devMode;
// }
//
// public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
// tl.set(apiConfig);
// }
//
// public static void removeThreadLocalApiConfig() {
// tl.remove();
// }
//
// public static ApiConfig getApiConfig() {
// ApiConfig result = tl.get();
// if (result == null)
// throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
// return result;
// }
//
// static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
//
// public static void setAccessTokenCache(IAccessTokenCache accessTokenCache) {
// ApiConfigKit.accessTokenCache = accessTokenCache;
// }
//
// public static IAccessTokenCache getAccessTokenCache() {
// return ApiConfigKit.accessTokenCache;
// }
// }
| import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
| package com.jfinal.weixin.sdk.jfinal;
/**
* ApiController 为 ApiController 绑定 ApiConfig 对象到当前线程,
* 以便在后续的操作中可以使用 ApiConfigKit.getApiConfig() 获取到该对象
*/
public class ApiInterceptor implements Interceptor {
public void intercept(Invocation inv) {
Controller controller = inv.getController();
if (controller instanceof ApiController == false)
throw new RuntimeException("控制器需要继承 ApiController");
try {
| // Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
// public class ApiConfigKit {
//
// private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
//
// // 开发模式将输出消息交互 xml 到控制台
// private static boolean devMode = false;
//
// public static void setDevMode(boolean devMode) {
// ApiConfigKit.devMode = devMode;
// }
//
// public static boolean isDevMode() {
// return devMode;
// }
//
// public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
// tl.set(apiConfig);
// }
//
// public static void removeThreadLocalApiConfig() {
// tl.remove();
// }
//
// public static ApiConfig getApiConfig() {
// ApiConfig result = tl.get();
// if (result == null)
// throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
// return result;
// }
//
// static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
//
// public static void setAccessTokenCache(IAccessTokenCache accessTokenCache) {
// ApiConfigKit.accessTokenCache = accessTokenCache;
// }
//
// public static IAccessTokenCache getAccessTokenCache() {
// return ApiConfigKit.accessTokenCache;
// }
// }
// Path: src/com/jfinal/weixin/sdk/jfinal/ApiInterceptor.java
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
package com.jfinal.weixin.sdk.jfinal;
/**
* ApiController 为 ApiController 绑定 ApiConfig 对象到当前线程,
* 以便在后续的操作中可以使用 ApiConfigKit.getApiConfig() 获取到该对象
*/
public class ApiInterceptor implements Interceptor {
public void intercept(Invocation inv) {
Controller controller = inv.getController();
if (controller instanceof ApiController == false)
throw new RuntimeException("控制器需要继承 ApiController");
try {
| ApiConfigKit.setThreadLocalApiConfig(((ApiController)controller).getApiConfig());
|
JackFish/jfinal-weixin | src/com/jfinal/weixin/demo/WeixinConfig.java | // Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
// public class ApiConfigKit {
//
// private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
//
// // 开发模式将输出消息交互 xml 到控制台
// private static boolean devMode = false;
//
// public static void setDevMode(boolean devMode) {
// ApiConfigKit.devMode = devMode;
// }
//
// public static boolean isDevMode() {
// return devMode;
// }
//
// public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
// tl.set(apiConfig);
// }
//
// public static void removeThreadLocalApiConfig() {
// tl.remove();
// }
//
// public static ApiConfig getApiConfig() {
// ApiConfig result = tl.get();
// if (result == null)
// throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
// return result;
// }
//
// static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
//
// public static void setAccessTokenCache(IAccessTokenCache accessTokenCache) {
// ApiConfigKit.accessTokenCache = accessTokenCache;
// }
//
// public static IAccessTokenCache getAccessTokenCache() {
// return ApiConfigKit.accessTokenCache;
// }
// }
| import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit; | /**
* Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.demo;
public class WeixinConfig extends JFinalConfig {
/**
* 如果生产环境配置文件存在,则优先加载该配置,否则加载开发环境配置文件
* @param pro 生产环境配置文件
* @param dev 开发环境配置文件
*/
public void loadProp(String pro, String dev) {
try {
PropKit.use(pro);
}
catch (Exception e) {
PropKit.use(dev);
}
}
public void configConstant(Constants me) {
loadProp("a_little_config_pro.txt", "a_little_config.txt");
me.setDevMode(PropKit.getBoolean("devMode", false));
// ApiConfigKit 设为开发模式可以在开发阶段输出请求交互的 xml 与 json 数据 | // Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
// public class ApiConfigKit {
//
// private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
//
// // 开发模式将输出消息交互 xml 到控制台
// private static boolean devMode = false;
//
// public static void setDevMode(boolean devMode) {
// ApiConfigKit.devMode = devMode;
// }
//
// public static boolean isDevMode() {
// return devMode;
// }
//
// public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
// tl.set(apiConfig);
// }
//
// public static void removeThreadLocalApiConfig() {
// tl.remove();
// }
//
// public static ApiConfig getApiConfig() {
// ApiConfig result = tl.get();
// if (result == null)
// throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
// return result;
// }
//
// static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
//
// public static void setAccessTokenCache(IAccessTokenCache accessTokenCache) {
// ApiConfigKit.accessTokenCache = accessTokenCache;
// }
//
// public static IAccessTokenCache getAccessTokenCache() {
// return ApiConfigKit.accessTokenCache;
// }
// }
// Path: src/com/jfinal/weixin/demo/WeixinConfig.java
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.core.JFinal;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
/**
* Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.demo;
public class WeixinConfig extends JFinalConfig {
/**
* 如果生产环境配置文件存在,则优先加载该配置,否则加载开发环境配置文件
* @param pro 生产环境配置文件
* @param dev 开发环境配置文件
*/
public void loadProp(String pro, String dev) {
try {
PropKit.use(pro);
}
catch (Exception e) {
PropKit.use(dev);
}
}
public void configConstant(Constants me) {
loadProp("a_little_config_pro.txt", "a_little_config.txt");
me.setDevMode(PropKit.getBoolean("devMode", false));
// ApiConfigKit 设为开发模式可以在开发阶段输出请求交互的 xml 与 json 数据 | ApiConfigKit.setDevMode(me.getDevMode()); |
JackFish/jfinal-weixin | test/com/jfinal/weixin/sdk/api/CustomServiceApiTest.java | // Path: src/com/jfinal/weixin/sdk/api/CustomServiceApi.java
// public static class Articles {
// private String title;
// private String description;
// private String url;
// private String picurl;
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
// public String getUrl() {
// return url;
// }
// public void setUrl(String url) {
// this.url = url;
// }
// public String getPicurl() {
// return picurl;
// }
// public void setPicurl(String picurl) {
// this.picurl = picurl;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import com.jfinal.weixin.sdk.api.CustomServiceApi.Articles;
| package com.jfinal.weixin.sdk.api;
public class CustomServiceApiTest {
// 请找有权限的帐号测试
public static void main(String[] args) {
String openId = "oOGf-jgjmwxFVU66D-lFO2AFK8ic";
// 测试发送纯文本:pass
System.out.println(CustomServiceApi.sendText(openId, "hello JFinal!"));
// 测试发图文:pass
| // Path: src/com/jfinal/weixin/sdk/api/CustomServiceApi.java
// public static class Articles {
// private String title;
// private String description;
// private String url;
// private String picurl;
//
// public String getTitle() {
// return title;
// }
// public void setTitle(String title) {
// this.title = title;
// }
// public String getDescription() {
// return description;
// }
// public void setDescription(String description) {
// this.description = description;
// }
// public String getUrl() {
// return url;
// }
// public void setUrl(String url) {
// this.url = url;
// }
// public String getPicurl() {
// return picurl;
// }
// public void setPicurl(String picurl) {
// this.picurl = picurl;
// }
// }
// Path: test/com/jfinal/weixin/sdk/api/CustomServiceApiTest.java
import java.util.ArrayList;
import java.util.List;
import com.jfinal.weixin.sdk.api.CustomServiceApi.Articles;
package com.jfinal.weixin.sdk.api;
public class CustomServiceApiTest {
// 请找有权限的帐号测试
public static void main(String[] args) {
String openId = "oOGf-jgjmwxFVU66D-lFO2AFK8ic";
// 测试发送纯文本:pass
System.out.println(CustomServiceApi.sendText(openId, "hello JFinal!"));
// 测试发图文:pass
| List<Articles> articles = new ArrayList<Articles>();
|
JackFish/jfinal-weixin | src/com/jfinal/weixin/sdk/api/AccessTokenApi.java | // Path: src/com/jfinal/weixin/sdk/cache/IAccessTokenCache.java
// public interface IAccessTokenCache {
//
// // 默认超时时间7200秒 5秒用于程序执行误差
// final int DEFAULT_TIME_OUT = 7200 - 5;
//
// <T> T get(String key);
//
// void set(String key, Object value);
//
// void remove(String key);
//
// }
| import java.util.Map;
import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import com.jfinal.weixin.sdk.kit.ParaMap;
| /**
* Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.sdk.api;
/**
* 认证并获取 access_token API
* http://mp.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96access_token
*
* AccessToken默认存储于内存中,可设置存储于redis或者实现IAccessTokenCache到数据库中实现分布式可用
*
* 具体配置:
* <pre>
* ApiConfigKit.setAccessTokenCache(new RedisAccessTokenCache());
* </pre>
*/
public class AccessTokenApi {
// "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private static String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
// 利用 appId 与 accessToken 建立关联,支持多账户
| // Path: src/com/jfinal/weixin/sdk/cache/IAccessTokenCache.java
// public interface IAccessTokenCache {
//
// // 默认超时时间7200秒 5秒用于程序执行误差
// final int DEFAULT_TIME_OUT = 7200 - 5;
//
// <T> T get(String key);
//
// void set(String key, Object value);
//
// void remove(String key);
//
// }
// Path: src/com/jfinal/weixin/sdk/api/AccessTokenApi.java
import java.util.Map;
import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import com.jfinal.weixin.sdk.kit.ParaMap;
/**
* Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.sdk.api;
/**
* 认证并获取 access_token API
* http://mp.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96access_token
*
* AccessToken默认存储于内存中,可设置存储于redis或者实现IAccessTokenCache到数据库中实现分布式可用
*
* 具体配置:
* <pre>
* ApiConfigKit.setAccessTokenCache(new RedisAccessTokenCache());
* </pre>
*/
public class AccessTokenApi {
// "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
private static String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
// 利用 appId 与 accessToken 建立关联,支持多账户
| static IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache();
|
JackFish/jfinal-weixin | src/com/jfinal/weixin/sdk/api/ApiConfigKit.java | // Path: src/com/jfinal/weixin/sdk/cache/DefaultAccessTokenCache.java
// public class DefaultAccessTokenCache implements IAccessTokenCache {
//
// private Map<String, Object> map = new ConcurrentHashMap<String, Object>();
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T get(String key) {
// return (T) map.get(key);
// }
//
// @Override
// public void set(String key, Object value) {
// map.put(key, value);
// }
//
// @Override
// public void remove(String key) {
// map.remove(key);
// }
//
// }
//
// Path: src/com/jfinal/weixin/sdk/cache/IAccessTokenCache.java
// public interface IAccessTokenCache {
//
// // 默认超时时间7200秒 5秒用于程序执行误差
// final int DEFAULT_TIME_OUT = 7200 - 5;
//
// <T> T get(String key);
//
// void set(String key, Object value);
//
// void remove(String key);
//
// }
| import com.jfinal.weixin.sdk.cache.DefaultAccessTokenCache;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
| package com.jfinal.weixin.sdk.api;
/**
* 将 ApiConfig 绑定到 ThreadLocal 的工具类,以方便在当前线程的各个地方获取 ApiConfig 对象:
* 1:如果控制器继承自 MsgController 该过程是自动的,详细可查看 MsgInterceptor 与之的配合
* 2:如果控制器继承自 ApiController 该过程是自动的,详细可查看 ApiInterceptor 与之的配合
* 3:如果控制器没有继承自 MsgController、ApiController,则需要先手动调用
* ApiConfigKit.setThreadLocalApiConfig(ApiConfig) 来绑定 apiConfig 到线程之上
*/
public class ApiConfigKit {
private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
// 开发模式将输出消息交互 xml 到控制台
private static boolean devMode = false;
public static void setDevMode(boolean devMode) {
ApiConfigKit.devMode = devMode;
}
public static boolean isDevMode() {
return devMode;
}
public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
tl.set(apiConfig);
}
public static void removeThreadLocalApiConfig() {
tl.remove();
}
public static ApiConfig getApiConfig() {
ApiConfig result = tl.get();
if (result == null)
throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
return result;
}
| // Path: src/com/jfinal/weixin/sdk/cache/DefaultAccessTokenCache.java
// public class DefaultAccessTokenCache implements IAccessTokenCache {
//
// private Map<String, Object> map = new ConcurrentHashMap<String, Object>();
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T get(String key) {
// return (T) map.get(key);
// }
//
// @Override
// public void set(String key, Object value) {
// map.put(key, value);
// }
//
// @Override
// public void remove(String key) {
// map.remove(key);
// }
//
// }
//
// Path: src/com/jfinal/weixin/sdk/cache/IAccessTokenCache.java
// public interface IAccessTokenCache {
//
// // 默认超时时间7200秒 5秒用于程序执行误差
// final int DEFAULT_TIME_OUT = 7200 - 5;
//
// <T> T get(String key);
//
// void set(String key, Object value);
//
// void remove(String key);
//
// }
// Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
import com.jfinal.weixin.sdk.cache.DefaultAccessTokenCache;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
package com.jfinal.weixin.sdk.api;
/**
* 将 ApiConfig 绑定到 ThreadLocal 的工具类,以方便在当前线程的各个地方获取 ApiConfig 对象:
* 1:如果控制器继承自 MsgController 该过程是自动的,详细可查看 MsgInterceptor 与之的配合
* 2:如果控制器继承自 ApiController 该过程是自动的,详细可查看 ApiInterceptor 与之的配合
* 3:如果控制器没有继承自 MsgController、ApiController,则需要先手动调用
* ApiConfigKit.setThreadLocalApiConfig(ApiConfig) 来绑定 apiConfig 到线程之上
*/
public class ApiConfigKit {
private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
// 开发模式将输出消息交互 xml 到控制台
private static boolean devMode = false;
public static void setDevMode(boolean devMode) {
ApiConfigKit.devMode = devMode;
}
public static boolean isDevMode() {
return devMode;
}
public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
tl.set(apiConfig);
}
public static void removeThreadLocalApiConfig() {
tl.remove();
}
public static ApiConfig getApiConfig() {
ApiConfig result = tl.get();
if (result == null)
throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
return result;
}
| static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
|
JackFish/jfinal-weixin | src/com/jfinal/weixin/sdk/api/ApiConfigKit.java | // Path: src/com/jfinal/weixin/sdk/cache/DefaultAccessTokenCache.java
// public class DefaultAccessTokenCache implements IAccessTokenCache {
//
// private Map<String, Object> map = new ConcurrentHashMap<String, Object>();
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T get(String key) {
// return (T) map.get(key);
// }
//
// @Override
// public void set(String key, Object value) {
// map.put(key, value);
// }
//
// @Override
// public void remove(String key) {
// map.remove(key);
// }
//
// }
//
// Path: src/com/jfinal/weixin/sdk/cache/IAccessTokenCache.java
// public interface IAccessTokenCache {
//
// // 默认超时时间7200秒 5秒用于程序执行误差
// final int DEFAULT_TIME_OUT = 7200 - 5;
//
// <T> T get(String key);
//
// void set(String key, Object value);
//
// void remove(String key);
//
// }
| import com.jfinal.weixin.sdk.cache.DefaultAccessTokenCache;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
| package com.jfinal.weixin.sdk.api;
/**
* 将 ApiConfig 绑定到 ThreadLocal 的工具类,以方便在当前线程的各个地方获取 ApiConfig 对象:
* 1:如果控制器继承自 MsgController 该过程是自动的,详细可查看 MsgInterceptor 与之的配合
* 2:如果控制器继承自 ApiController 该过程是自动的,详细可查看 ApiInterceptor 与之的配合
* 3:如果控制器没有继承自 MsgController、ApiController,则需要先手动调用
* ApiConfigKit.setThreadLocalApiConfig(ApiConfig) 来绑定 apiConfig 到线程之上
*/
public class ApiConfigKit {
private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
// 开发模式将输出消息交互 xml 到控制台
private static boolean devMode = false;
public static void setDevMode(boolean devMode) {
ApiConfigKit.devMode = devMode;
}
public static boolean isDevMode() {
return devMode;
}
public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
tl.set(apiConfig);
}
public static void removeThreadLocalApiConfig() {
tl.remove();
}
public static ApiConfig getApiConfig() {
ApiConfig result = tl.get();
if (result == null)
throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
return result;
}
| // Path: src/com/jfinal/weixin/sdk/cache/DefaultAccessTokenCache.java
// public class DefaultAccessTokenCache implements IAccessTokenCache {
//
// private Map<String, Object> map = new ConcurrentHashMap<String, Object>();
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T get(String key) {
// return (T) map.get(key);
// }
//
// @Override
// public void set(String key, Object value) {
// map.put(key, value);
// }
//
// @Override
// public void remove(String key) {
// map.remove(key);
// }
//
// }
//
// Path: src/com/jfinal/weixin/sdk/cache/IAccessTokenCache.java
// public interface IAccessTokenCache {
//
// // 默认超时时间7200秒 5秒用于程序执行误差
// final int DEFAULT_TIME_OUT = 7200 - 5;
//
// <T> T get(String key);
//
// void set(String key, Object value);
//
// void remove(String key);
//
// }
// Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
import com.jfinal.weixin.sdk.cache.DefaultAccessTokenCache;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
package com.jfinal.weixin.sdk.api;
/**
* 将 ApiConfig 绑定到 ThreadLocal 的工具类,以方便在当前线程的各个地方获取 ApiConfig 对象:
* 1:如果控制器继承自 MsgController 该过程是自动的,详细可查看 MsgInterceptor 与之的配合
* 2:如果控制器继承自 ApiController 该过程是自动的,详细可查看 ApiInterceptor 与之的配合
* 3:如果控制器没有继承自 MsgController、ApiController,则需要先手动调用
* ApiConfigKit.setThreadLocalApiConfig(ApiConfig) 来绑定 apiConfig 到线程之上
*/
public class ApiConfigKit {
private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
// 开发模式将输出消息交互 xml 到控制台
private static boolean devMode = false;
public static void setDevMode(boolean devMode) {
ApiConfigKit.devMode = devMode;
}
public static boolean isDevMode() {
return devMode;
}
public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
tl.set(apiConfig);
}
public static void removeThreadLocalApiConfig() {
tl.remove();
}
public static ApiConfig getApiConfig() {
ApiConfig result = tl.get();
if (result == null)
throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
return result;
}
| static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
|
JackFish/jfinal-weixin | test/com/jfinal/weixin/sdk/api/AccessTokenApiTest.java | // Path: src/com/jfinal/weixin/sdk/cache/RedisAccessTokenCache.java
// public class RedisAccessTokenCache implements IAccessTokenCache {
//
// private final String ACCESS_TOKEN_PREFIX = "jfinal_weixin:";
//
// private final Cache cache;
//
// public RedisAccessTokenCache() {
// this.cache = Redis.use();
// }
//
// public RedisAccessTokenCache(String cacheName) {
// this.cache = Redis.use(cacheName);
// }
//
// public RedisAccessTokenCache(Cache cache) {
// this.cache = cache;
// }
//
// @Override
// public <T> T get(String key) {
// return cache.get(ACCESS_TOKEN_PREFIX + key);
// }
//
// @Override
// public void set(String key, Object object) {
// cache.setex(ACCESS_TOKEN_PREFIX + key, DEFAULT_TIME_OUT, object);
// }
//
// @Override
// public void remove(String key) {
// cache.del(ACCESS_TOKEN_PREFIX + key);
// }
//
// }
| import java.io.IOException;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.weixin.sdk.cache.RedisAccessTokenCache;
| package com.jfinal.weixin.sdk.api;
/**
* AccessTokenApi 测试
*/
public class AccessTokenApiTest {
public static String AppID = "wx9803d1188fa5fbda";
public static String AppSecret = "db859c968763c582794e7c3d003c3d87";
public static void init(){
ApiConfig ac = new ApiConfig();
ac.setAppId(AppID);
ac.setAppSecret(AppSecret);
ApiConfigKit.setThreadLocalApiConfig(ac);
}
public static void main(String[] args) throws IOException {
init();
useRedis();
test();
}
public static void useRedis() {
new RedisPlugin("main", "127.0.0.1").start();
| // Path: src/com/jfinal/weixin/sdk/cache/RedisAccessTokenCache.java
// public class RedisAccessTokenCache implements IAccessTokenCache {
//
// private final String ACCESS_TOKEN_PREFIX = "jfinal_weixin:";
//
// private final Cache cache;
//
// public RedisAccessTokenCache() {
// this.cache = Redis.use();
// }
//
// public RedisAccessTokenCache(String cacheName) {
// this.cache = Redis.use(cacheName);
// }
//
// public RedisAccessTokenCache(Cache cache) {
// this.cache = cache;
// }
//
// @Override
// public <T> T get(String key) {
// return cache.get(ACCESS_TOKEN_PREFIX + key);
// }
//
// @Override
// public void set(String key, Object object) {
// cache.setex(ACCESS_TOKEN_PREFIX + key, DEFAULT_TIME_OUT, object);
// }
//
// @Override
// public void remove(String key) {
// cache.del(ACCESS_TOKEN_PREFIX + key);
// }
//
// }
// Path: test/com/jfinal/weixin/sdk/api/AccessTokenApiTest.java
import java.io.IOException;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.weixin.sdk.cache.RedisAccessTokenCache;
package com.jfinal.weixin.sdk.api;
/**
* AccessTokenApi 测试
*/
public class AccessTokenApiTest {
public static String AppID = "wx9803d1188fa5fbda";
public static String AppSecret = "db859c968763c582794e7c3d003c3d87";
public static void init(){
ApiConfig ac = new ApiConfig();
ac.setAppId(AppID);
ac.setAppSecret(AppSecret);
ApiConfigKit.setThreadLocalApiConfig(ac);
}
public static void main(String[] args) throws IOException {
init();
useRedis();
test();
}
public static void useRedis() {
new RedisPlugin("main", "127.0.0.1").start();
| ApiConfigKit.setAccessTokenCache(new RedisAccessTokenCache());
|
JackFish/jfinal-weixin | test/com/jfinal/weixin/sdk/msg/XMLMsgTest.java | // Path: src/com/jfinal/weixin/sdk/msg/in/event/InMenuEvent.java
// public class InMenuEvent extends EventInMsg {
// // 1. 点击菜单拉取消息时的事件推送: CLICK
// public static final String EVENT_INMENU_CLICK = "CLICK";
// // 2. 点击菜单跳转链接时的事件推送: VIEW
// public static final String EVENT_INMENU_VIEW = "VIEW";
// // 3. scancode_push:扫码推事件
// public static final String EVENT_INMENU_SCANCODE_PUSH = "scancode_push";
// // 4. scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
// public static final String EVENT_INMENU_scancode_waitmsg = "scancode_waitmsg";
// // 5. pic_sysphoto:弹出系统拍照发图
// public static final String EVENT_INMENU_PIC_SYSPHOTO = "pic_sysphoto";
// // 6. pic_photo_or_album:弹出拍照或者相册发图,先推送菜单事件,再推送图片消息
// public static final String EVENT_INMENU_PIC_PHOTO_OR_ALBUM = "pic_photo_or_album";
// // 7. pic_weixin:弹出微信相册发图器
// public static final String EVENT_INMENU_PIC_WEIXIN = "pic_weixin";
// // 8. location_select:弹出地理位置选择器
// public static final String EVENT_INMENU_LOCATION_SELECT = "location_select";
// // 9. media_id:下发消息(除文本消息)
// public static final String EVENT_INMENU_MEDIA_ID = "media_id";
// // 10. view_limited:跳转图文消息URL
// public static final String EVENT_INMENU_VIEW_LIMITED = "view_limited";
//
// private String eventKey;
// private ScanCodeInfo scanCodeInfo;
//
// public InMenuEvent(String toUserName, String fromUserName, Integer createTime, String msgType,String event) {
// super(toUserName, fromUserName, createTime, msgType,event);
// }
//
// public String getEventKey() {
// return eventKey;
// }
//
// public void setEventKey(String eventKey) {
// this.eventKey = eventKey;
// }
//
// public ScanCodeInfo getScanCodeInfo() {
// return scanCodeInfo;
// }
//
// public void setScanCodeInfo(ScanCodeInfo scanCodeInfo) {
// this.scanCodeInfo = scanCodeInfo;
// }
//
// }
//
// Path: src/com/jfinal/weixin/sdk/msg/in/event/ScanCodeInfo.java
// public class ScanCodeInfo {
//
// private String ScanType;
// private String ScanResult;
//
// public ScanCodeInfo(String scanType, String scanResult) {
// super();
// ScanType = scanType;
// ScanResult = scanResult;
// }
// public String getScanType() {
// return ScanType;
// }
// public void setScanType(String scanType) {
// ScanType = scanType;
// }
// public String getScanResult() {
// return ScanResult;
// }
// public void setScanResult(String scanResult) {
// ScanResult = scanResult;
// }
//
// }
| import org.junit.Assert;
import org.junit.Test;
import com.jfinal.weixin.sdk.msg.in.InMsg;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.ScanCodeInfo;
| package com.jfinal.weixin.sdk.msg;
public class XMLMsgTest {
@Test
public void test001() {
String xml = "<xml>"
+ "<ToUserName><![CDATA[ToUserName]]></ToUserName>"
+ "<FromUserName><![CDATA[FromUserName]]></FromUserName>"
+ "<CreateTime>1446526359</CreateTime>"
+ "<MsgType><![CDATA[event]]></MsgType>"
+ "<Event><![CDATA[scancode_waitmsg]]></Event>"
+ "<EventKey><![CDATA[2_1]]></EventKey>"
+ "<ScanCodeInfo>"
+ "<ScanType><![CDATA[qrcode]]></ScanType>"
+ "<ScanResult><![CDATA[http://www.jfinal.com]]></ScanResult>"
+ "</ScanCodeInfo>"
+ "</xml>";
InMsg inMsg = InMsgParser.parse(xml);
| // Path: src/com/jfinal/weixin/sdk/msg/in/event/InMenuEvent.java
// public class InMenuEvent extends EventInMsg {
// // 1. 点击菜单拉取消息时的事件推送: CLICK
// public static final String EVENT_INMENU_CLICK = "CLICK";
// // 2. 点击菜单跳转链接时的事件推送: VIEW
// public static final String EVENT_INMENU_VIEW = "VIEW";
// // 3. scancode_push:扫码推事件
// public static final String EVENT_INMENU_SCANCODE_PUSH = "scancode_push";
// // 4. scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
// public static final String EVENT_INMENU_scancode_waitmsg = "scancode_waitmsg";
// // 5. pic_sysphoto:弹出系统拍照发图
// public static final String EVENT_INMENU_PIC_SYSPHOTO = "pic_sysphoto";
// // 6. pic_photo_or_album:弹出拍照或者相册发图,先推送菜单事件,再推送图片消息
// public static final String EVENT_INMENU_PIC_PHOTO_OR_ALBUM = "pic_photo_or_album";
// // 7. pic_weixin:弹出微信相册发图器
// public static final String EVENT_INMENU_PIC_WEIXIN = "pic_weixin";
// // 8. location_select:弹出地理位置选择器
// public static final String EVENT_INMENU_LOCATION_SELECT = "location_select";
// // 9. media_id:下发消息(除文本消息)
// public static final String EVENT_INMENU_MEDIA_ID = "media_id";
// // 10. view_limited:跳转图文消息URL
// public static final String EVENT_INMENU_VIEW_LIMITED = "view_limited";
//
// private String eventKey;
// private ScanCodeInfo scanCodeInfo;
//
// public InMenuEvent(String toUserName, String fromUserName, Integer createTime, String msgType,String event) {
// super(toUserName, fromUserName, createTime, msgType,event);
// }
//
// public String getEventKey() {
// return eventKey;
// }
//
// public void setEventKey(String eventKey) {
// this.eventKey = eventKey;
// }
//
// public ScanCodeInfo getScanCodeInfo() {
// return scanCodeInfo;
// }
//
// public void setScanCodeInfo(ScanCodeInfo scanCodeInfo) {
// this.scanCodeInfo = scanCodeInfo;
// }
//
// }
//
// Path: src/com/jfinal/weixin/sdk/msg/in/event/ScanCodeInfo.java
// public class ScanCodeInfo {
//
// private String ScanType;
// private String ScanResult;
//
// public ScanCodeInfo(String scanType, String scanResult) {
// super();
// ScanType = scanType;
// ScanResult = scanResult;
// }
// public String getScanType() {
// return ScanType;
// }
// public void setScanType(String scanType) {
// ScanType = scanType;
// }
// public String getScanResult() {
// return ScanResult;
// }
// public void setScanResult(String scanResult) {
// ScanResult = scanResult;
// }
//
// }
// Path: test/com/jfinal/weixin/sdk/msg/XMLMsgTest.java
import org.junit.Assert;
import org.junit.Test;
import com.jfinal.weixin.sdk.msg.in.InMsg;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.ScanCodeInfo;
package com.jfinal.weixin.sdk.msg;
public class XMLMsgTest {
@Test
public void test001() {
String xml = "<xml>"
+ "<ToUserName><![CDATA[ToUserName]]></ToUserName>"
+ "<FromUserName><![CDATA[FromUserName]]></FromUserName>"
+ "<CreateTime>1446526359</CreateTime>"
+ "<MsgType><![CDATA[event]]></MsgType>"
+ "<Event><![CDATA[scancode_waitmsg]]></Event>"
+ "<EventKey><![CDATA[2_1]]></EventKey>"
+ "<ScanCodeInfo>"
+ "<ScanType><![CDATA[qrcode]]></ScanType>"
+ "<ScanResult><![CDATA[http://www.jfinal.com]]></ScanResult>"
+ "</ScanCodeInfo>"
+ "</xml>";
InMsg inMsg = InMsgParser.parse(xml);
| Assert.assertTrue(inMsg instanceof InMenuEvent);
|
JackFish/jfinal-weixin | test/com/jfinal/weixin/sdk/msg/XMLMsgTest.java | // Path: src/com/jfinal/weixin/sdk/msg/in/event/InMenuEvent.java
// public class InMenuEvent extends EventInMsg {
// // 1. 点击菜单拉取消息时的事件推送: CLICK
// public static final String EVENT_INMENU_CLICK = "CLICK";
// // 2. 点击菜单跳转链接时的事件推送: VIEW
// public static final String EVENT_INMENU_VIEW = "VIEW";
// // 3. scancode_push:扫码推事件
// public static final String EVENT_INMENU_SCANCODE_PUSH = "scancode_push";
// // 4. scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
// public static final String EVENT_INMENU_scancode_waitmsg = "scancode_waitmsg";
// // 5. pic_sysphoto:弹出系统拍照发图
// public static final String EVENT_INMENU_PIC_SYSPHOTO = "pic_sysphoto";
// // 6. pic_photo_or_album:弹出拍照或者相册发图,先推送菜单事件,再推送图片消息
// public static final String EVENT_INMENU_PIC_PHOTO_OR_ALBUM = "pic_photo_or_album";
// // 7. pic_weixin:弹出微信相册发图器
// public static final String EVENT_INMENU_PIC_WEIXIN = "pic_weixin";
// // 8. location_select:弹出地理位置选择器
// public static final String EVENT_INMENU_LOCATION_SELECT = "location_select";
// // 9. media_id:下发消息(除文本消息)
// public static final String EVENT_INMENU_MEDIA_ID = "media_id";
// // 10. view_limited:跳转图文消息URL
// public static final String EVENT_INMENU_VIEW_LIMITED = "view_limited";
//
// private String eventKey;
// private ScanCodeInfo scanCodeInfo;
//
// public InMenuEvent(String toUserName, String fromUserName, Integer createTime, String msgType,String event) {
// super(toUserName, fromUserName, createTime, msgType,event);
// }
//
// public String getEventKey() {
// return eventKey;
// }
//
// public void setEventKey(String eventKey) {
// this.eventKey = eventKey;
// }
//
// public ScanCodeInfo getScanCodeInfo() {
// return scanCodeInfo;
// }
//
// public void setScanCodeInfo(ScanCodeInfo scanCodeInfo) {
// this.scanCodeInfo = scanCodeInfo;
// }
//
// }
//
// Path: src/com/jfinal/weixin/sdk/msg/in/event/ScanCodeInfo.java
// public class ScanCodeInfo {
//
// private String ScanType;
// private String ScanResult;
//
// public ScanCodeInfo(String scanType, String scanResult) {
// super();
// ScanType = scanType;
// ScanResult = scanResult;
// }
// public String getScanType() {
// return ScanType;
// }
// public void setScanType(String scanType) {
// ScanType = scanType;
// }
// public String getScanResult() {
// return ScanResult;
// }
// public void setScanResult(String scanResult) {
// ScanResult = scanResult;
// }
//
// }
| import org.junit.Assert;
import org.junit.Test;
import com.jfinal.weixin.sdk.msg.in.InMsg;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.ScanCodeInfo;
| package com.jfinal.weixin.sdk.msg;
public class XMLMsgTest {
@Test
public void test001() {
String xml = "<xml>"
+ "<ToUserName><![CDATA[ToUserName]]></ToUserName>"
+ "<FromUserName><![CDATA[FromUserName]]></FromUserName>"
+ "<CreateTime>1446526359</CreateTime>"
+ "<MsgType><![CDATA[event]]></MsgType>"
+ "<Event><![CDATA[scancode_waitmsg]]></Event>"
+ "<EventKey><![CDATA[2_1]]></EventKey>"
+ "<ScanCodeInfo>"
+ "<ScanType><![CDATA[qrcode]]></ScanType>"
+ "<ScanResult><![CDATA[http://www.jfinal.com]]></ScanResult>"
+ "</ScanCodeInfo>"
+ "</xml>";
InMsg inMsg = InMsgParser.parse(xml);
Assert.assertTrue(inMsg instanceof InMenuEvent);
InMenuEvent inMenuEvent = (InMenuEvent) inMsg;
| // Path: src/com/jfinal/weixin/sdk/msg/in/event/InMenuEvent.java
// public class InMenuEvent extends EventInMsg {
// // 1. 点击菜单拉取消息时的事件推送: CLICK
// public static final String EVENT_INMENU_CLICK = "CLICK";
// // 2. 点击菜单跳转链接时的事件推送: VIEW
// public static final String EVENT_INMENU_VIEW = "VIEW";
// // 3. scancode_push:扫码推事件
// public static final String EVENT_INMENU_SCANCODE_PUSH = "scancode_push";
// // 4. scancode_waitmsg:扫码推事件且弹出“消息接收中”提示框
// public static final String EVENT_INMENU_scancode_waitmsg = "scancode_waitmsg";
// // 5. pic_sysphoto:弹出系统拍照发图
// public static final String EVENT_INMENU_PIC_SYSPHOTO = "pic_sysphoto";
// // 6. pic_photo_or_album:弹出拍照或者相册发图,先推送菜单事件,再推送图片消息
// public static final String EVENT_INMENU_PIC_PHOTO_OR_ALBUM = "pic_photo_or_album";
// // 7. pic_weixin:弹出微信相册发图器
// public static final String EVENT_INMENU_PIC_WEIXIN = "pic_weixin";
// // 8. location_select:弹出地理位置选择器
// public static final String EVENT_INMENU_LOCATION_SELECT = "location_select";
// // 9. media_id:下发消息(除文本消息)
// public static final String EVENT_INMENU_MEDIA_ID = "media_id";
// // 10. view_limited:跳转图文消息URL
// public static final String EVENT_INMENU_VIEW_LIMITED = "view_limited";
//
// private String eventKey;
// private ScanCodeInfo scanCodeInfo;
//
// public InMenuEvent(String toUserName, String fromUserName, Integer createTime, String msgType,String event) {
// super(toUserName, fromUserName, createTime, msgType,event);
// }
//
// public String getEventKey() {
// return eventKey;
// }
//
// public void setEventKey(String eventKey) {
// this.eventKey = eventKey;
// }
//
// public ScanCodeInfo getScanCodeInfo() {
// return scanCodeInfo;
// }
//
// public void setScanCodeInfo(ScanCodeInfo scanCodeInfo) {
// this.scanCodeInfo = scanCodeInfo;
// }
//
// }
//
// Path: src/com/jfinal/weixin/sdk/msg/in/event/ScanCodeInfo.java
// public class ScanCodeInfo {
//
// private String ScanType;
// private String ScanResult;
//
// public ScanCodeInfo(String scanType, String scanResult) {
// super();
// ScanType = scanType;
// ScanResult = scanResult;
// }
// public String getScanType() {
// return ScanType;
// }
// public void setScanType(String scanType) {
// ScanType = scanType;
// }
// public String getScanResult() {
// return ScanResult;
// }
// public void setScanResult(String scanResult) {
// ScanResult = scanResult;
// }
//
// }
// Path: test/com/jfinal/weixin/sdk/msg/XMLMsgTest.java
import org.junit.Assert;
import org.junit.Test;
import com.jfinal.weixin.sdk.msg.in.InMsg;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.ScanCodeInfo;
package com.jfinal.weixin.sdk.msg;
public class XMLMsgTest {
@Test
public void test001() {
String xml = "<xml>"
+ "<ToUserName><![CDATA[ToUserName]]></ToUserName>"
+ "<FromUserName><![CDATA[FromUserName]]></FromUserName>"
+ "<CreateTime>1446526359</CreateTime>"
+ "<MsgType><![CDATA[event]]></MsgType>"
+ "<Event><![CDATA[scancode_waitmsg]]></Event>"
+ "<EventKey><![CDATA[2_1]]></EventKey>"
+ "<ScanCodeInfo>"
+ "<ScanType><![CDATA[qrcode]]></ScanType>"
+ "<ScanResult><![CDATA[http://www.jfinal.com]]></ScanResult>"
+ "</ScanCodeInfo>"
+ "</xml>";
InMsg inMsg = InMsgParser.parse(xml);
Assert.assertTrue(inMsg instanceof InMenuEvent);
InMenuEvent inMenuEvent = (InMenuEvent) inMsg;
| ScanCodeInfo scanCodeInfo = inMenuEvent.getScanCodeInfo();
|
JackFish/jfinal-weixin | test/com/jfinal/weixin/sdk/api/MediaApiTest.java | // Path: src/com/jfinal/weixin/sdk/api/MediaApi.java
// public static enum MediaType {
// IMAGE, VOICE, VIDEO, THUMB, NEWS;
//
// // 转化成小写形式
// public String get() {
// return this.name().toLowerCase();
// }
// }
| import java.io.IOException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.jfinal.weixin.sdk.api.MediaApi.MediaType; | package com.jfinal.weixin.sdk.api;
public class MediaApiTest {
@Before
public void setUp() {
AccessTokenApiTest.init();
}
/**
* 测试获取素材总数
*/
@Test
public void testGetMaterialCount() {
ApiResult ar = MediaApi.getMaterialCount();
String json = ar.getJson();
System.out.println("testGetMaterialCount: " + json);
Assert.assertNotNull(json);
}
/**
* 测试获取素材列表
*/
@Test
public void testBatchGetMaterial() { | // Path: src/com/jfinal/weixin/sdk/api/MediaApi.java
// public static enum MediaType {
// IMAGE, VOICE, VIDEO, THUMB, NEWS;
//
// // 转化成小写形式
// public String get() {
// return this.name().toLowerCase();
// }
// }
// Path: test/com/jfinal/weixin/sdk/api/MediaApiTest.java
import java.io.IOException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.jfinal.weixin.sdk.api.MediaApi.MediaType;
package com.jfinal.weixin.sdk.api;
public class MediaApiTest {
@Before
public void setUp() {
AccessTokenApiTest.init();
}
/**
* 测试获取素材总数
*/
@Test
public void testGetMaterialCount() {
ApiResult ar = MediaApi.getMaterialCount();
String json = ar.getJson();
System.out.println("testGetMaterialCount: " + json);
Assert.assertNotNull(json);
}
/**
* 测试获取素材列表
*/
@Test
public void testBatchGetMaterial() { | ApiResult ar = MediaApi.batchGetMaterial(MediaType.IMAGE, 1, 10); |
JackFish/jfinal-weixin | src/com/jfinal/weixin/sdk/kit/MsgEncryptKit.java | // Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
// public class ApiConfigKit {
//
// private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
//
// // 开发模式将输出消息交互 xml 到控制台
// private static boolean devMode = false;
//
// public static void setDevMode(boolean devMode) {
// ApiConfigKit.devMode = devMode;
// }
//
// public static boolean isDevMode() {
// return devMode;
// }
//
// public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
// tl.set(apiConfig);
// }
//
// public static void removeThreadLocalApiConfig() {
// tl.remove();
// }
//
// public static ApiConfig getApiConfig() {
// ApiConfig result = tl.get();
// if (result == null)
// throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
// return result;
// }
//
// static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
//
// public static void setAccessTokenCache(IAccessTokenCache accessTokenCache) {
// ApiConfigKit.accessTokenCache = accessTokenCache;
// }
//
// public static IAccessTokenCache getAccessTokenCache() {
// return ApiConfigKit.accessTokenCache;
// }
// }
| import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.encrypt.WXBizMsgCrypt;
| package com.jfinal.weixin.sdk.kit;
/**
* 对微信平台官方给出的加密解析代码进行再次封装
*
* 异常java.security.InvalidKeyException:illegal Key Size的解决方案:
* 1:在官方网站下载JCE无限制权限策略文件(JDK7的下载地址:
* http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
* 2:下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt
* 3:如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件
* 4:如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件
*
*
* 设置为消息加密模式后 JFinal Action Report 中有如下参数:
* timestamp=1417610658
* encrypt_type=aes
* nonce=132155339
* msg_signature=8ed2a14146c924153743162ab2c0d28eaf30a323
* signature=1a3fad9a528869b1a73faf4c8054b7eeda2463d3
*/
public class MsgEncryptKit {
private static final String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
public static String encrypt(String msg, String timestamp, String nonce) {
try {
| // Path: src/com/jfinal/weixin/sdk/api/ApiConfigKit.java
// public class ApiConfigKit {
//
// private static final ThreadLocal<ApiConfig> tl = new ThreadLocal<ApiConfig>();
//
// // 开发模式将输出消息交互 xml 到控制台
// private static boolean devMode = false;
//
// public static void setDevMode(boolean devMode) {
// ApiConfigKit.devMode = devMode;
// }
//
// public static boolean isDevMode() {
// return devMode;
// }
//
// public static void setThreadLocalApiConfig(ApiConfig apiConfig) {
// tl.set(apiConfig);
// }
//
// public static void removeThreadLocalApiConfig() {
// tl.remove();
// }
//
// public static ApiConfig getApiConfig() {
// ApiConfig result = tl.get();
// if (result == null)
// throw new IllegalStateException("需要事先使用 ApiConfigKit.setThreadLocalApiConfig(apiConfig) 将 ApiConfig对象存入,才可以调用 ApiConfigKit.getApiConfig() 方法");
// return result;
// }
//
// static IAccessTokenCache accessTokenCache = new DefaultAccessTokenCache();
//
// public static void setAccessTokenCache(IAccessTokenCache accessTokenCache) {
// ApiConfigKit.accessTokenCache = accessTokenCache;
// }
//
// public static IAccessTokenCache getAccessTokenCache() {
// return ApiConfigKit.accessTokenCache;
// }
// }
// Path: src/com/jfinal/weixin/sdk/kit/MsgEncryptKit.java
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.encrypt.WXBizMsgCrypt;
package com.jfinal.weixin.sdk.kit;
/**
* 对微信平台官方给出的加密解析代码进行再次封装
*
* 异常java.security.InvalidKeyException:illegal Key Size的解决方案:
* 1:在官方网站下载JCE无限制权限策略文件(JDK7的下载地址:
* http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
* 2:下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt
* 3:如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件
* 4:如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件
*
*
* 设置为消息加密模式后 JFinal Action Report 中有如下参数:
* timestamp=1417610658
* encrypt_type=aes
* nonce=132155339
* msg_signature=8ed2a14146c924153743162ab2c0d28eaf30a323
* signature=1a3fad9a528869b1a73faf4c8054b7eeda2463d3
*/
public class MsgEncryptKit {
private static final String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>";
public static String encrypt(String msg, String timestamp, String nonce) {
try {
| ApiConfig ac = ApiConfigKit.getApiConfig();
|
JackFish/jfinal-weixin | src/com/jfinal/weixin/sdk/api/JsTicketApi.java | // Path: src/com/jfinal/weixin/sdk/cache/IAccessTokenCache.java
// public interface IAccessTokenCache {
//
// // 默认超时时间7200秒 5秒用于程序执行误差
// final int DEFAULT_TIME_OUT = 7200 - 5;
//
// <T> T get(String key);
//
// void set(String key, Object value);
//
// void remove(String key);
//
// }
| import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import com.jfinal.weixin.sdk.kit.ParaMap; | /**
* Copyright (c) 2011-2015, Unas 小强哥 (unas@qq.com).
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.sdk.api;
/**
*
* 生成签名之前必须先了解一下jsapi_ticket,jsapi_ticket是公众号用于调用微信JS接口的临时票据
* https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
*
* 微信卡券接口签名凭证api_ticket
* https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card
*/
public class JsTicketApi {
private static String apiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
| // Path: src/com/jfinal/weixin/sdk/cache/IAccessTokenCache.java
// public interface IAccessTokenCache {
//
// // 默认超时时间7200秒 5秒用于程序执行误差
// final int DEFAULT_TIME_OUT = 7200 - 5;
//
// <T> T get(String key);
//
// void set(String key, Object value);
//
// void remove(String key);
//
// }
// Path: src/com/jfinal/weixin/sdk/api/JsTicketApi.java
import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.cache.IAccessTokenCache;
import com.jfinal.weixin.sdk.kit.ParaMap;
/**
* Copyright (c) 2011-2015, Unas 小强哥 (unas@qq.com).
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.sdk.api;
/**
*
* 生成签名之前必须先了解一下jsapi_ticket,jsapi_ticket是公众号用于调用微信JS接口的临时票据
* https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
*
* 微信卡券接口签名凭证api_ticket
* https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card
*/
public class JsTicketApi {
private static String apiUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
| static IAccessTokenCache accessTokenCache = ApiConfigKit.getAccessTokenCache(); |
JackFish/jfinal-weixin | src/com/jfinal/weixin/sdk/kit/PaymentKit.java | // Path: src/com/jfinal/weixin/sdk/utils/IOUtils.java
// public class IOUtils {
// private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
//
// /**
// * closeQuietly
// * @param closeable
// */
// public static void closeQuietly(Closeable closeable) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException ioe) {
// // ignore
// }
// }
//
// /**
// * InputStream to String
// *
// * @param input the <code>InputStream</code> to read from
// * @return the requested String
// * @throws NullPointerException if the input is null
// * @throws IOException if an I/O error occurs
// */
// public static String toString(InputStream input) throws IOException {
// StringBuffer out = new StringBuffer();
// byte[] b = new byte[DEFAULT_BUFFER_SIZE];
// for (int n; (n = input.read(b)) != -1;) {
// out.append(new String(b, 0, n));
// }
// IOUtils.closeQuietly(input);
// return out.toString();
// }
//
// /**
// * InputStream to File
// * @param input the <code>InputStream</code> to read from
// * @param file the File to write
// * @throws IOException
// */
// public static void toFile(InputStream input, File file) throws IOException {
// OutputStream os = new FileOutputStream(file);
// int bytesRead = 0;
// byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
// while ((bytesRead = input.read(buffer, 0, DEFAULT_BUFFER_SIZE)) != -1) {
// os.write(buffer, 0, bytesRead);
// }
// IOUtils.closeQuietly(os);
// IOUtils.closeQuietly(input);
// }
// }
| import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.UUID;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.utils.IOUtils; | SSLContext sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(kms, null, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
URL _url = new URL(url);
conn = (HttpsURLConnection) _url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
conn.connect();
out = conn.getOutputStream();
out.write(data.getBytes(CHARSET));
out.flush();
inputStream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line).append("\n");
}
return sb.toString();
} catch (Exception e) {
throw new RuntimeException(e);
} finally { | // Path: src/com/jfinal/weixin/sdk/utils/IOUtils.java
// public class IOUtils {
// private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
//
// /**
// * closeQuietly
// * @param closeable
// */
// public static void closeQuietly(Closeable closeable) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException ioe) {
// // ignore
// }
// }
//
// /**
// * InputStream to String
// *
// * @param input the <code>InputStream</code> to read from
// * @return the requested String
// * @throws NullPointerException if the input is null
// * @throws IOException if an I/O error occurs
// */
// public static String toString(InputStream input) throws IOException {
// StringBuffer out = new StringBuffer();
// byte[] b = new byte[DEFAULT_BUFFER_SIZE];
// for (int n; (n = input.read(b)) != -1;) {
// out.append(new String(b, 0, n));
// }
// IOUtils.closeQuietly(input);
// return out.toString();
// }
//
// /**
// * InputStream to File
// * @param input the <code>InputStream</code> to read from
// * @param file the File to write
// * @throws IOException
// */
// public static void toFile(InputStream input, File file) throws IOException {
// OutputStream os = new FileOutputStream(file);
// int bytesRead = 0;
// byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
// while ((bytesRead = input.read(buffer, 0, DEFAULT_BUFFER_SIZE)) != -1) {
// os.write(buffer, 0, bytesRead);
// }
// IOUtils.closeQuietly(os);
// IOUtils.closeQuietly(input);
// }
// }
// Path: src/com/jfinal/weixin/sdk/kit/PaymentKit.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.UUID;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.utils.IOUtils;
SSLContext sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(kms, null, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
URL _url = new URL(url);
conn = (HttpsURLConnection) _url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
conn.connect();
out = conn.getOutputStream();
out.write(data.getBytes(CHARSET));
out.flush();
inputStream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line).append("\n");
}
return sb.toString();
} catch (Exception e) {
throw new RuntimeException(e);
} finally { | IOUtils.closeQuietly(out); |
JackFish/jfinal-weixin | test/com/jfinal/weixin/sdk/api/JsTicketApiTest.java | // Path: src/com/jfinal/weixin/sdk/api/JsTicketApi.java
// public enum JsApiType {
// jsapi, wx_card
// }
| import java.io.IOException;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;
| package com.jfinal.weixin.sdk.api;
public class JsTicketApiTest {
public static void testJsApi() {
| // Path: src/com/jfinal/weixin/sdk/api/JsTicketApi.java
// public enum JsApiType {
// jsapi, wx_card
// }
// Path: test/com/jfinal/weixin/sdk/api/JsTicketApiTest.java
import java.io.IOException;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;
package com.jfinal.weixin.sdk.api;
public class JsTicketApiTest {
public static void testJsApi() {
| System.out.println(JsTicketApi.getTicket(JsApiType.jsapi));
|
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/screens/AbstractPausedScreen.java | // Path: core/src/com/galvarez/ttw/ThingsThatWereGame.java
// public class ThingsThatWereGame extends Game {
//
// public int windowWidth;
//
// public int windowHeight;
//
// public Assets assets;
//
// private World world;
//
// private SpriteBatch batch;
//
// private CustomizeGameMenuScreen customScreen;
//
// private MainMenuScreen menuScreen;
//
// private SessionSettings settings;
//
// public ThingsThatWereGame(int width, int height) {
// /*
// * FIXME If height is greater that real screen height then the menu is
// * incorrectly set until the screen is resized. It appears easily on AC
// * laptop as default resolution is smaller. What happens is probably that
// * the OverworldScreen.stage is resized automatically but the resize()
// * method is not called.
// */
// windowWidth = width;
// windowHeight = height;
// }
//
// @Override
// public void create() {
// assets = new Assets();
// settings = new SessionSettings();
//
// startGame();
// }
//
// private void startGame() {
// world = new World();
// batch = new SpriteBatch();
//
// world.setSystem(new SpriteAnimationSystem());
// world.setSystem(new ScaleAnimationSystem());
// world.setSystem(new ExpiringSystem());
// world.setSystem(new ColorAnimationSystem());
// world.initialize();
//
// // this screen can modify the settings instance
// customScreen = new CustomizeGameMenuScreen(this, world, batch, settings);
// menuScreen = new MainMenuScreen(this, world, batch, customScreen);
// setScreen(menuScreen);
// }
//
// /** Quit current game and goes back to main menu. */
// public void returnToMainMenu() {
// if (getScreen() instanceof OverworldScreen)
// getScreen().dispose();
//
// // simply dispose everything and create anew!
// world.dispose();
// batch.dispose();
// customScreen.dispose();
// menuScreen.dispose();
// startGame();
// }
//
// /** Start a game. */
// public void startGame(boolean resetSettings) {
// OverworldScreen worldScreen = new OverworldScreen(this, batch, world,
// // copy settings because we want to keep for next game only the ones that
// // were customized in dedicated screen
// resetSettings ? new SessionSettings() : new SessionSettings(settings));
// setScreen(worldScreen);
//
// // show tutorial when starting a new game
// worldScreen.tutorialMenu();
// }
//
// @Override
// public void dispose() {
// super.dispose();
// world.dispose();
// }
//
// public void exit() {
// Gdx.app.exit();
// }
//
// }
| import com.artemis.World;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.galvarez.ttw.ThingsThatWereGame; | package com.galvarez.ttw.screens;
public abstract class AbstractPausedScreen<Screen extends AbstractScreen> extends AbstractScreen {
protected final Screen gameScreen;
private final ShapeRenderer renderer;
protected final Stage stage;
protected final Skin skin;
protected boolean canEscape = true;
protected boolean paused = true;
| // Path: core/src/com/galvarez/ttw/ThingsThatWereGame.java
// public class ThingsThatWereGame extends Game {
//
// public int windowWidth;
//
// public int windowHeight;
//
// public Assets assets;
//
// private World world;
//
// private SpriteBatch batch;
//
// private CustomizeGameMenuScreen customScreen;
//
// private MainMenuScreen menuScreen;
//
// private SessionSettings settings;
//
// public ThingsThatWereGame(int width, int height) {
// /*
// * FIXME If height is greater that real screen height then the menu is
// * incorrectly set until the screen is resized. It appears easily on AC
// * laptop as default resolution is smaller. What happens is probably that
// * the OverworldScreen.stage is resized automatically but the resize()
// * method is not called.
// */
// windowWidth = width;
// windowHeight = height;
// }
//
// @Override
// public void create() {
// assets = new Assets();
// settings = new SessionSettings();
//
// startGame();
// }
//
// private void startGame() {
// world = new World();
// batch = new SpriteBatch();
//
// world.setSystem(new SpriteAnimationSystem());
// world.setSystem(new ScaleAnimationSystem());
// world.setSystem(new ExpiringSystem());
// world.setSystem(new ColorAnimationSystem());
// world.initialize();
//
// // this screen can modify the settings instance
// customScreen = new CustomizeGameMenuScreen(this, world, batch, settings);
// menuScreen = new MainMenuScreen(this, world, batch, customScreen);
// setScreen(menuScreen);
// }
//
// /** Quit current game and goes back to main menu. */
// public void returnToMainMenu() {
// if (getScreen() instanceof OverworldScreen)
// getScreen().dispose();
//
// // simply dispose everything and create anew!
// world.dispose();
// batch.dispose();
// customScreen.dispose();
// menuScreen.dispose();
// startGame();
// }
//
// /** Start a game. */
// public void startGame(boolean resetSettings) {
// OverworldScreen worldScreen = new OverworldScreen(this, batch, world,
// // copy settings because we want to keep for next game only the ones that
// // were customized in dedicated screen
// resetSettings ? new SessionSettings() : new SessionSettings(settings));
// setScreen(worldScreen);
//
// // show tutorial when starting a new game
// worldScreen.tutorialMenu();
// }
//
// @Override
// public void dispose() {
// super.dispose();
// world.dispose();
// }
//
// public void exit() {
// Gdx.app.exit();
// }
//
// }
// Path: core/src/com/galvarez/ttw/screens/AbstractPausedScreen.java
import com.artemis.World;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.galvarez.ttw.ThingsThatWereGame;
package com.galvarez.ttw.screens;
public abstract class AbstractPausedScreen<Screen extends AbstractScreen> extends AbstractScreen {
protected final Screen gameScreen;
private final ShapeRenderer renderer;
protected final Stage stage;
protected final Skin skin;
protected boolean canEscape = true;
protected boolean paused = true;
| public AbstractPausedScreen(ThingsThatWereGame game, World world, SpriteBatch batch, Screen gameScreen) { |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/components/ArmyCommand.java | // Path: core/src/com/galvarez/ttw/model/map/Terrain.java
// public enum Terrain {
//
// DEEP_WATER("deep water", Color.NAVY, 50, false),
//
// SHALLOW_WATER("shallow water", Color.BLUE, 30, false),
//
// DESERT("desert", Color.YELLOW, 50, false),
//
// PLAIN("plain", Color.GREEN, 10, true),
//
// GRASSLAND("grassland", new Color(0, 0.5f, 0, 1), 15, true),
//
// FOREST("forest", Color.OLIVE, 30, true),
//
// HILLS("hills", Color.ORANGE, 30, true),
//
// MOUNTAIN("mountain", Color.MAROON, 50, false),
//
// ARCTIC("arctic", Color.WHITE, 100, false);
//
// private final Color color;
//
// private final int moveCost;
//
// private final String desc;
//
// private final boolean canStart;
//
// private Terrain(String desc, Color color, int moveCost, boolean canStart) {
// this.desc = desc;
// this.moveCost = moveCost;
// this.color = color;
// this.canStart = canStart;
// }
//
// public Color getColor() {
// return color;
// }
//
// public boolean moveBlock() {
// return false;
// }
//
// public boolean canStart() {
// return canStart;
// }
//
// public int moveCost() {
// return moveCost;
// }
//
// public int getTexture() {
// return ordinal();
// }
//
// public String getDesc() {
// return desc;
// }
//
// }
| import java.util.EnumSet;
import java.util.Set;
import com.artemis.Component;
import com.galvarez.ttw.model.map.Terrain; | package com.galvarez.ttw.model.components;
public final class ArmyCommand extends Component {
private static final int INITIAL_MILITARY_POWER = 10;
| // Path: core/src/com/galvarez/ttw/model/map/Terrain.java
// public enum Terrain {
//
// DEEP_WATER("deep water", Color.NAVY, 50, false),
//
// SHALLOW_WATER("shallow water", Color.BLUE, 30, false),
//
// DESERT("desert", Color.YELLOW, 50, false),
//
// PLAIN("plain", Color.GREEN, 10, true),
//
// GRASSLAND("grassland", new Color(0, 0.5f, 0, 1), 15, true),
//
// FOREST("forest", Color.OLIVE, 30, true),
//
// HILLS("hills", Color.ORANGE, 30, true),
//
// MOUNTAIN("mountain", Color.MAROON, 50, false),
//
// ARCTIC("arctic", Color.WHITE, 100, false);
//
// private final Color color;
//
// private final int moveCost;
//
// private final String desc;
//
// private final boolean canStart;
//
// private Terrain(String desc, Color color, int moveCost, boolean canStart) {
// this.desc = desc;
// this.moveCost = moveCost;
// this.color = color;
// this.canStart = canStart;
// }
//
// public Color getColor() {
// return color;
// }
//
// public boolean moveBlock() {
// return false;
// }
//
// public boolean canStart() {
// return canStart;
// }
//
// public int moveCost() {
// return moveCost;
// }
//
// public int getTexture() {
// return ordinal();
// }
//
// public String getDesc() {
// return desc;
// }
//
// }
// Path: core/src/com/galvarez/ttw/model/components/ArmyCommand.java
import java.util.EnumSet;
import java.util.Set;
import com.artemis.Component;
import com.galvarez.ttw.model.map.Terrain;
package com.galvarez.ttw.model.components;
public final class ArmyCommand extends Component {
private static final int INITIAL_MILITARY_POWER = 10;
| public final Set<Terrain> forbiddenTiles = EnumSet.of(Terrain.SHALLOW_WATER, Terrain.DEEP_WATER, Terrain.ARCTIC); |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/PoliciesSystem.java | // Path: core/src/com/galvarez/ttw/model/components/Discoveries.java
// public final class Discoveries extends Component {
//
// public final Set<Discovery> done = new HashSet<>();
//
// /** Increase to speed progress up. */
// public int progressPerTurn = 1;
//
// /** Contains possibles discoveries when one is expected. */
// public Map<Faction, Research> nextPossible;
//
// public Research last;
//
// public Discoveries() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/components/Policies.java
// public final class Policies extends Component {
//
// public final Map<Policy, Discovery> policies = new EnumMap<>(Policy.class);
//
// /**
// * Stability percentage, decrease when changing policies, increase with time
// * to stability max value.
// */
// public int stability = 15;
//
// public int stabilityMax = 15;
//
// public int stabilityGrowth = 1;
//
// public Policies() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Policy.java
// public enum Policy {
//
// FOOD("Our people prefer eating "),
//
// WEAPON("When fighting, our people use "),
//
// MOVE("We go farther and better by "),
//
// TERRAIN("Our preferred terrain is "),
//
// RELATION("Our preferred relation is "),
//
// VALUE("Our most honored value is "),
//
// ART("Our most excellent art is "),
//
// GOVERNMENT("We are governed by "),
//
// JOBS("Our people are mostly ");
//
// public final String msg;
//
// private Policy(String msg) {
// this.msg = msg;
// }
//
// public static final Policy get(String name) {
// try {
// return Policy.valueOf(name);
// } catch (IllegalArgumentException e) {
// return null;
// }
// }
//
// }
| import static java.lang.Math.min;
import static java.util.stream.Collectors.toList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.annotations.Wire;
import com.artemis.utils.ImmutableBag;
import com.galvarez.ttw.model.components.Discoveries;
import com.galvarez.ttw.model.components.Policies;
import com.galvarez.ttw.model.data.Discovery;
import com.galvarez.ttw.model.data.Policy; | package com.galvarez.ttw.model;
/**
* For every empire, handle policies changes.
* <p>
* When changing a policy, the stability decreases. It increases slowly over
* time.
* </p>
*
* @author Guillaume Alvarez
*/
@Wire
public final class PoliciesSystem extends EntitySystem {
private static final int STABILITY_LOSS_WHEN_SWITCHING = 20;
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(PoliciesSystem.class);
| // Path: core/src/com/galvarez/ttw/model/components/Discoveries.java
// public final class Discoveries extends Component {
//
// public final Set<Discovery> done = new HashSet<>();
//
// /** Increase to speed progress up. */
// public int progressPerTurn = 1;
//
// /** Contains possibles discoveries when one is expected. */
// public Map<Faction, Research> nextPossible;
//
// public Research last;
//
// public Discoveries() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/components/Policies.java
// public final class Policies extends Component {
//
// public final Map<Policy, Discovery> policies = new EnumMap<>(Policy.class);
//
// /**
// * Stability percentage, decrease when changing policies, increase with time
// * to stability max value.
// */
// public int stability = 15;
//
// public int stabilityMax = 15;
//
// public int stabilityGrowth = 1;
//
// public Policies() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Policy.java
// public enum Policy {
//
// FOOD("Our people prefer eating "),
//
// WEAPON("When fighting, our people use "),
//
// MOVE("We go farther and better by "),
//
// TERRAIN("Our preferred terrain is "),
//
// RELATION("Our preferred relation is "),
//
// VALUE("Our most honored value is "),
//
// ART("Our most excellent art is "),
//
// GOVERNMENT("We are governed by "),
//
// JOBS("Our people are mostly ");
//
// public final String msg;
//
// private Policy(String msg) {
// this.msg = msg;
// }
//
// public static final Policy get(String name) {
// try {
// return Policy.valueOf(name);
// } catch (IllegalArgumentException e) {
// return null;
// }
// }
//
// }
// Path: core/src/com/galvarez/ttw/model/PoliciesSystem.java
import static java.lang.Math.min;
import static java.util.stream.Collectors.toList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.annotations.Wire;
import com.artemis.utils.ImmutableBag;
import com.galvarez.ttw.model.components.Discoveries;
import com.galvarez.ttw.model.components.Policies;
import com.galvarez.ttw.model.data.Discovery;
import com.galvarez.ttw.model.data.Policy;
package com.galvarez.ttw.model;
/**
* For every empire, handle policies changes.
* <p>
* When changing a policy, the stability decreases. It increases slowly over
* time.
* </p>
*
* @author Guillaume Alvarez
*/
@Wire
public final class PoliciesSystem extends EntitySystem {
private static final int STABILITY_LOSS_WHEN_SWITCHING = 20;
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(PoliciesSystem.class);
| private ComponentMapper<Policies> policies; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/PoliciesSystem.java | // Path: core/src/com/galvarez/ttw/model/components/Discoveries.java
// public final class Discoveries extends Component {
//
// public final Set<Discovery> done = new HashSet<>();
//
// /** Increase to speed progress up. */
// public int progressPerTurn = 1;
//
// /** Contains possibles discoveries when one is expected. */
// public Map<Faction, Research> nextPossible;
//
// public Research last;
//
// public Discoveries() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/components/Policies.java
// public final class Policies extends Component {
//
// public final Map<Policy, Discovery> policies = new EnumMap<>(Policy.class);
//
// /**
// * Stability percentage, decrease when changing policies, increase with time
// * to stability max value.
// */
// public int stability = 15;
//
// public int stabilityMax = 15;
//
// public int stabilityGrowth = 1;
//
// public Policies() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Policy.java
// public enum Policy {
//
// FOOD("Our people prefer eating "),
//
// WEAPON("When fighting, our people use "),
//
// MOVE("We go farther and better by "),
//
// TERRAIN("Our preferred terrain is "),
//
// RELATION("Our preferred relation is "),
//
// VALUE("Our most honored value is "),
//
// ART("Our most excellent art is "),
//
// GOVERNMENT("We are governed by "),
//
// JOBS("Our people are mostly ");
//
// public final String msg;
//
// private Policy(String msg) {
// this.msg = msg;
// }
//
// public static final Policy get(String name) {
// try {
// return Policy.valueOf(name);
// } catch (IllegalArgumentException e) {
// return null;
// }
// }
//
// }
| import static java.lang.Math.min;
import static java.util.stream.Collectors.toList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.annotations.Wire;
import com.artemis.utils.ImmutableBag;
import com.galvarez.ttw.model.components.Discoveries;
import com.galvarez.ttw.model.components.Policies;
import com.galvarez.ttw.model.data.Discovery;
import com.galvarez.ttw.model.data.Policy; | package com.galvarez.ttw.model;
/**
* For every empire, handle policies changes.
* <p>
* When changing a policy, the stability decreases. It increases slowly over
* time.
* </p>
*
* @author Guillaume Alvarez
*/
@Wire
public final class PoliciesSystem extends EntitySystem {
private static final int STABILITY_LOSS_WHEN_SWITCHING = 20;
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(PoliciesSystem.class);
private ComponentMapper<Policies> policies;
| // Path: core/src/com/galvarez/ttw/model/components/Discoveries.java
// public final class Discoveries extends Component {
//
// public final Set<Discovery> done = new HashSet<>();
//
// /** Increase to speed progress up. */
// public int progressPerTurn = 1;
//
// /** Contains possibles discoveries when one is expected. */
// public Map<Faction, Research> nextPossible;
//
// public Research last;
//
// public Discoveries() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/components/Policies.java
// public final class Policies extends Component {
//
// public final Map<Policy, Discovery> policies = new EnumMap<>(Policy.class);
//
// /**
// * Stability percentage, decrease when changing policies, increase with time
// * to stability max value.
// */
// public int stability = 15;
//
// public int stabilityMax = 15;
//
// public int stabilityGrowth = 1;
//
// public Policies() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Policy.java
// public enum Policy {
//
// FOOD("Our people prefer eating "),
//
// WEAPON("When fighting, our people use "),
//
// MOVE("We go farther and better by "),
//
// TERRAIN("Our preferred terrain is "),
//
// RELATION("Our preferred relation is "),
//
// VALUE("Our most honored value is "),
//
// ART("Our most excellent art is "),
//
// GOVERNMENT("We are governed by "),
//
// JOBS("Our people are mostly ");
//
// public final String msg;
//
// private Policy(String msg) {
// this.msg = msg;
// }
//
// public static final Policy get(String name) {
// try {
// return Policy.valueOf(name);
// } catch (IllegalArgumentException e) {
// return null;
// }
// }
//
// }
// Path: core/src/com/galvarez/ttw/model/PoliciesSystem.java
import static java.lang.Math.min;
import static java.util.stream.Collectors.toList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.annotations.Wire;
import com.artemis.utils.ImmutableBag;
import com.galvarez.ttw.model.components.Discoveries;
import com.galvarez.ttw.model.components.Policies;
import com.galvarez.ttw.model.data.Discovery;
import com.galvarez.ttw.model.data.Policy;
package com.galvarez.ttw.model;
/**
* For every empire, handle policies changes.
* <p>
* When changing a policy, the stability decreases. It increases slowly over
* time.
* </p>
*
* @author Guillaume Alvarez
*/
@Wire
public final class PoliciesSystem extends EntitySystem {
private static final int STABILITY_LOSS_WHEN_SWITCHING = 20;
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(PoliciesSystem.class);
private ComponentMapper<Policies> policies;
| private ComponentMapper<Discoveries> discoveries; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/rendering/ScaleAnimationSystem.java | // Path: core/src/com/galvarez/ttw/rendering/components/ScaleAnimation.java
// public final class ScaleAnimation extends PooledComponent {
//
// public float min, max, speed;
//
// public boolean repeat, active;
//
// public ScaleAnimation() {
// }
//
// @Override
// public void reset() {
// this.speed = 0f;
// this.min = 0f;
// this.max = 100f;
// this.repeat = false;
// this.active = true;
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
| import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.rendering.components.ScaleAnimation;
import com.galvarez.ttw.rendering.components.Sprite;
| package com.galvarez.ttw.rendering;
@Wire
public final class ScaleAnimationSystem extends EntityProcessingSystem {
| // Path: core/src/com/galvarez/ttw/rendering/components/ScaleAnimation.java
// public final class ScaleAnimation extends PooledComponent {
//
// public float min, max, speed;
//
// public boolean repeat, active;
//
// public ScaleAnimation() {
// }
//
// @Override
// public void reset() {
// this.speed = 0f;
// this.min = 0f;
// this.max = 100f;
// this.repeat = false;
// this.active = true;
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
// Path: core/src/com/galvarez/ttw/rendering/ScaleAnimationSystem.java
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.rendering.components.ScaleAnimation;
import com.galvarez.ttw.rendering.components.Sprite;
package com.galvarez.ttw.rendering;
@Wire
public final class ScaleAnimationSystem extends EntityProcessingSystem {
| private ComponentMapper<ScaleAnimation> sa;
|
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/rendering/ScaleAnimationSystem.java | // Path: core/src/com/galvarez/ttw/rendering/components/ScaleAnimation.java
// public final class ScaleAnimation extends PooledComponent {
//
// public float min, max, speed;
//
// public boolean repeat, active;
//
// public ScaleAnimation() {
// }
//
// @Override
// public void reset() {
// this.speed = 0f;
// this.min = 0f;
// this.max = 100f;
// this.repeat = false;
// this.active = true;
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
| import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.rendering.components.ScaleAnimation;
import com.galvarez.ttw.rendering.components.Sprite;
| package com.galvarez.ttw.rendering;
@Wire
public final class ScaleAnimationSystem extends EntityProcessingSystem {
private ComponentMapper<ScaleAnimation> sa;
| // Path: core/src/com/galvarez/ttw/rendering/components/ScaleAnimation.java
// public final class ScaleAnimation extends PooledComponent {
//
// public float min, max, speed;
//
// public boolean repeat, active;
//
// public ScaleAnimation() {
// }
//
// @Override
// public void reset() {
// this.speed = 0f;
// this.min = 0f;
// this.max = 100f;
// this.repeat = false;
// this.active = true;
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
// Path: core/src/com/galvarez/ttw/rendering/ScaleAnimationSystem.java
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.rendering.components.ScaleAnimation;
import com.galvarez.ttw.rendering.components.Sprite;
package com.galvarez.ttw.rendering;
@Wire
public final class ScaleAnimationSystem extends EntityProcessingSystem {
private ComponentMapper<ScaleAnimation> sa;
| private ComponentMapper<Sprite> sm;
|
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/components/Research.java | // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
| import java.util.Collection;
import com.artemis.Component;
import com.badlogic.gdx.utils.ObjectFloatMap;
import com.galvarez.ttw.model.Faction;
import com.galvarez.ttw.model.data.Discovery; | package com.galvarez.ttw.model.components;
public class Research extends Component {
public final Collection<Discovery> previous;
| // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
// Path: core/src/com/galvarez/ttw/model/components/Research.java
import java.util.Collection;
import com.artemis.Component;
import com.badlogic.gdx.utils.ObjectFloatMap;
import com.galvarez.ttw.model.Faction;
import com.galvarez.ttw.model.data.Discovery;
package com.galvarez.ttw.model.components;
public class Research extends Component {
public final Collection<Discovery> previous;
| public final ObjectFloatMap<Faction> factions; |
guillaume-alvarez/ShapeOfThingsThatWere | desktop/src/com/galvarez/ttw/desktop/DesktopLauncher.java | // Path: core/src/com/galvarez/ttw/ThingsThatWereGame.java
// public class ThingsThatWereGame extends Game {
//
// public int windowWidth;
//
// public int windowHeight;
//
// public Assets assets;
//
// private World world;
//
// private SpriteBatch batch;
//
// private CustomizeGameMenuScreen customScreen;
//
// private MainMenuScreen menuScreen;
//
// private SessionSettings settings;
//
// public ThingsThatWereGame(int width, int height) {
// /*
// * FIXME If height is greater that real screen height then the menu is
// * incorrectly set until the screen is resized. It appears easily on AC
// * laptop as default resolution is smaller. What happens is probably that
// * the OverworldScreen.stage is resized automatically but the resize()
// * method is not called.
// */
// windowWidth = width;
// windowHeight = height;
// }
//
// @Override
// public void create() {
// assets = new Assets();
// settings = new SessionSettings();
//
// startGame();
// }
//
// private void startGame() {
// world = new World();
// batch = new SpriteBatch();
//
// world.setSystem(new SpriteAnimationSystem());
// world.setSystem(new ScaleAnimationSystem());
// world.setSystem(new ExpiringSystem());
// world.setSystem(new ColorAnimationSystem());
// world.initialize();
//
// // this screen can modify the settings instance
// customScreen = new CustomizeGameMenuScreen(this, world, batch, settings);
// menuScreen = new MainMenuScreen(this, world, batch, customScreen);
// setScreen(menuScreen);
// }
//
// /** Quit current game and goes back to main menu. */
// public void returnToMainMenu() {
// if (getScreen() instanceof OverworldScreen)
// getScreen().dispose();
//
// // simply dispose everything and create anew!
// world.dispose();
// batch.dispose();
// customScreen.dispose();
// menuScreen.dispose();
// startGame();
// }
//
// /** Start a game. */
// public void startGame(boolean resetSettings) {
// OverworldScreen worldScreen = new OverworldScreen(this, batch, world,
// // copy settings because we want to keep for next game only the ones that
// // were customized in dedicated screen
// resetSettings ? new SessionSettings() : new SessionSettings(settings));
// setScreen(worldScreen);
//
// // show tutorial when starting a new game
// worldScreen.tutorialMenu();
// }
//
// @Override
// public void dispose() {
// super.dispose();
// world.dispose();
// }
//
// public void exit() {
// Gdx.app.exit();
// }
//
// }
| import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.galvarez.ttw.ThingsThatWereGame; | package com.galvarez.ttw.desktop;
public class DesktopLauncher {
private static final int WIDTH = 1024;
private static final int HEIGHT = 800;
public static void main(String[] args) {
// ImagePacker.run();
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.width = WIDTH;
cfg.height = HEIGHT;
cfg.title = "The Shape of Things that Were";
cfg.vSyncEnabled = true;
cfg.resizable = true;
// no audio implemented yet
// for some unknown reason OpenAL init is very long (a few minutes) on some machines
LwjglApplicationConfiguration.disableAudio = true; | // Path: core/src/com/galvarez/ttw/ThingsThatWereGame.java
// public class ThingsThatWereGame extends Game {
//
// public int windowWidth;
//
// public int windowHeight;
//
// public Assets assets;
//
// private World world;
//
// private SpriteBatch batch;
//
// private CustomizeGameMenuScreen customScreen;
//
// private MainMenuScreen menuScreen;
//
// private SessionSettings settings;
//
// public ThingsThatWereGame(int width, int height) {
// /*
// * FIXME If height is greater that real screen height then the menu is
// * incorrectly set until the screen is resized. It appears easily on AC
// * laptop as default resolution is smaller. What happens is probably that
// * the OverworldScreen.stage is resized automatically but the resize()
// * method is not called.
// */
// windowWidth = width;
// windowHeight = height;
// }
//
// @Override
// public void create() {
// assets = new Assets();
// settings = new SessionSettings();
//
// startGame();
// }
//
// private void startGame() {
// world = new World();
// batch = new SpriteBatch();
//
// world.setSystem(new SpriteAnimationSystem());
// world.setSystem(new ScaleAnimationSystem());
// world.setSystem(new ExpiringSystem());
// world.setSystem(new ColorAnimationSystem());
// world.initialize();
//
// // this screen can modify the settings instance
// customScreen = new CustomizeGameMenuScreen(this, world, batch, settings);
// menuScreen = new MainMenuScreen(this, world, batch, customScreen);
// setScreen(menuScreen);
// }
//
// /** Quit current game and goes back to main menu. */
// public void returnToMainMenu() {
// if (getScreen() instanceof OverworldScreen)
// getScreen().dispose();
//
// // simply dispose everything and create anew!
// world.dispose();
// batch.dispose();
// customScreen.dispose();
// menuScreen.dispose();
// startGame();
// }
//
// /** Start a game. */
// public void startGame(boolean resetSettings) {
// OverworldScreen worldScreen = new OverworldScreen(this, batch, world,
// // copy settings because we want to keep for next game only the ones that
// // were customized in dedicated screen
// resetSettings ? new SessionSettings() : new SessionSettings(settings));
// setScreen(worldScreen);
//
// // show tutorial when starting a new game
// worldScreen.tutorialMenu();
// }
//
// @Override
// public void dispose() {
// super.dispose();
// world.dispose();
// }
//
// public void exit() {
// Gdx.app.exit();
// }
//
// }
// Path: desktop/src/com/galvarez/ttw/desktop/DesktopLauncher.java
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.galvarez.ttw.ThingsThatWereGame;
package com.galvarez.ttw.desktop;
public class DesktopLauncher {
private static final int WIDTH = 1024;
private static final int HEIGHT = 800;
public static void main(String[] args) {
// ImagePacker.run();
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.width = WIDTH;
cfg.height = HEIGHT;
cfg.title = "The Shape of Things that Were";
cfg.vSyncEnabled = true;
cfg.resizable = true;
// no audio implemented yet
// for some unknown reason OpenAL init is very long (a few minutes) on some machines
LwjglApplicationConfiguration.disableAudio = true; | new LwjglApplication(new ThingsThatWereGame(WIDTH, HEIGHT), cfg); |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/map/GameMap.java | // Path: core/src/com/galvarez/ttw/model/data/Empire.java
// public final class Empire extends Component {
//
// private static final AtomicInteger COUNTER = new AtomicInteger(0);
//
// public final int id;
//
// public final Color color;
//
// public final Color backColor;
//
// public final Culture culture;
//
// private final boolean computer;
//
// public Empire(Color color, Culture culture, boolean computer) {
// this.id = COUNTER.getAndIncrement();
// this.color = color;
// this.backColor = Colors.contrast(color);
// this.culture = culture;
// this.computer = computer;
// }
//
// public boolean isComputerControlled() {
// return computer;
// }
//
// public Color getColor() {
// return color;
// }
//
// public Culture getCulture() {
// return culture;
// }
//
// public String newCityName() {
// return culture.newCityName();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Empire)
// return id == ((Empire) obj).id;
// else
// return false;
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public String toString() {
// return culture.name + "(ia=" + computer + ")";
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
| import java.util.Collection;
import com.artemis.Entity;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.utils.Array;
import com.galvarez.ttw.model.data.Empire;
import com.galvarez.ttw.utils.MyMath; | package com.galvarez.ttw.model.map;
public final class GameMap {
public final Terrain[][] map;
private final Entity[][] entityByCoord;
private final MapPosition[][] posByCoord;
private final Influence[][] influenceByCoord;
public final int width, height;
/** Represents the whole map as a single image. */
public final Texture texture;
| // Path: core/src/com/galvarez/ttw/model/data/Empire.java
// public final class Empire extends Component {
//
// private static final AtomicInteger COUNTER = new AtomicInteger(0);
//
// public final int id;
//
// public final Color color;
//
// public final Color backColor;
//
// public final Culture culture;
//
// private final boolean computer;
//
// public Empire(Color color, Culture culture, boolean computer) {
// this.id = COUNTER.getAndIncrement();
// this.color = color;
// this.backColor = Colors.contrast(color);
// this.culture = culture;
// this.computer = computer;
// }
//
// public boolean isComputerControlled() {
// return computer;
// }
//
// public Color getColor() {
// return color;
// }
//
// public Culture getCulture() {
// return culture;
// }
//
// public String newCityName() {
// return culture.newCityName();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Empire)
// return id == ((Empire) obj).id;
// else
// return false;
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public String toString() {
// return culture.name + "(ia=" + computer + ")";
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
// Path: core/src/com/galvarez/ttw/model/map/GameMap.java
import java.util.Collection;
import com.artemis.Entity;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.utils.Array;
import com.galvarez.ttw.model.data.Empire;
import com.galvarez.ttw.utils.MyMath;
package com.galvarez.ttw.model.map;
public final class GameMap {
public final Terrain[][] map;
private final Entity[][] entityByCoord;
private final MapPosition[][] posByCoord;
private final Influence[][] influenceByCoord;
public final int width, height;
/** Represents the whole map as a single image. */
public final Texture texture;
| public final Empire[] empires; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/map/GameMap.java | // Path: core/src/com/galvarez/ttw/model/data/Empire.java
// public final class Empire extends Component {
//
// private static final AtomicInteger COUNTER = new AtomicInteger(0);
//
// public final int id;
//
// public final Color color;
//
// public final Color backColor;
//
// public final Culture culture;
//
// private final boolean computer;
//
// public Empire(Color color, Culture culture, boolean computer) {
// this.id = COUNTER.getAndIncrement();
// this.color = color;
// this.backColor = Colors.contrast(color);
// this.culture = culture;
// this.computer = computer;
// }
//
// public boolean isComputerControlled() {
// return computer;
// }
//
// public Color getColor() {
// return color;
// }
//
// public Culture getCulture() {
// return culture;
// }
//
// public String newCityName() {
// return culture.newCityName();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Empire)
// return id == ((Empire) obj).id;
// else
// return false;
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public String toString() {
// return culture.name + "(ia=" + computer + ")";
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
| import java.util.Collection;
import com.artemis.Entity;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.utils.Array;
import com.galvarez.ttw.model.data.Empire;
import com.galvarez.ttw.utils.MyMath; | package com.galvarez.ttw.model.map;
public final class GameMap {
public final Terrain[][] map;
private final Entity[][] entityByCoord;
private final MapPosition[][] posByCoord;
private final Influence[][] influenceByCoord;
public final int width, height;
/** Represents the whole map as a single image. */
public final Texture texture;
public final Empire[] empires;
public GameMap(Terrain[][] map, Collection<Empire> empires) {
this.map = map;
this.empires = empires.toArray(new Empire[0]);
width = map.length;
height = map[0].length;
entityByCoord = new Entity[width][height];
influenceByCoord = new Influence[width][height];
posByCoord = new MapPosition[width][height];
Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
MapPosition pos = posByCoord[x][y] = new MapPosition(x, y);
influenceByCoord[x][y] = new Influence(pos, map[x][y]);
pixmap.setColor(map[x][y].getColor());
pixmap.drawPixel(x, y);
}
}
texture = new Texture(pixmap);
pixmap.dispose();
}
public Entity getEntityAt(int x, int y) {
if (isOnMap(x, y))
return entityByCoord[x][y];
else
return null;
}
public Entity getEntityAt(MapPosition pos) {
return getEntityAt(pos.x, pos.y);
}
public boolean hasEntity(MapPosition pos) {
return getEntityAt(pos) != null;
}
public Terrain getTerrainAt(MapPosition pos) {
return getTerrainAt(pos.x, pos.y);
}
public Terrain getTerrainAt(int x, int y) {
if (isOnMap(x, y))
return map[x][y];
else
throw new IllegalStateException("(" + x + ", " + y + ") is outside map boundaries.");
}
public Influence getInfluenceAt(MapPosition pos) {
return getInfluenceAt(pos.x, pos.y);
}
public Influence getInfluenceAt(int x, int y) {
if (isOnMap(x, y))
return influenceByCoord[x][y];
else
throw new IllegalStateException("(" + x + ", " + y + ") is outside map boundaries.");
}
public boolean isOnMap(MapPosition p) {
return isOnMap(p.x, p.y);
}
public boolean isOnMap(int x, int y) {
return x >= 0 && x < posByCoord.length && y >= 0 && y < posByCoord[0].length;
}
public MapPosition getPositionAt(int x, int y) {
if (isOnMap(x, y))
return posByCoord[x][y];
else
throw new IllegalStateException("(" + x + ", " + y + ") is outside map boundaries.");
}
public void setEntity(Entity e, int x, int y) {
entityByCoord[x][y] = e;
}
public void setEntity(Entity e, MapPosition p) {
setEntity(e, p.x, p.y);
}
public void moveEntity(Entity e, MapPosition from, MapPosition to) {
entityByCoord[from.x][from.y] = null;
entityByCoord[to.x][to.y] = e;
}
public Array<MapPosition> getNeighbors(int x, int y, int n) {
Array<MapPosition> coordinates = new Array<MapPosition>();
int min;
int myrow;
for (int row = y - n; row < y + n + 1; row++) { | // Path: core/src/com/galvarez/ttw/model/data/Empire.java
// public final class Empire extends Component {
//
// private static final AtomicInteger COUNTER = new AtomicInteger(0);
//
// public final int id;
//
// public final Color color;
//
// public final Color backColor;
//
// public final Culture culture;
//
// private final boolean computer;
//
// public Empire(Color color, Culture culture, boolean computer) {
// this.id = COUNTER.getAndIncrement();
// this.color = color;
// this.backColor = Colors.contrast(color);
// this.culture = culture;
// this.computer = computer;
// }
//
// public boolean isComputerControlled() {
// return computer;
// }
//
// public Color getColor() {
// return color;
// }
//
// public Culture getCulture() {
// return culture;
// }
//
// public String newCityName() {
// return culture.newCityName();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Empire)
// return id == ((Empire) obj).id;
// else
// return false;
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public String toString() {
// return culture.name + "(ia=" + computer + ")";
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
// Path: core/src/com/galvarez/ttw/model/map/GameMap.java
import java.util.Collection;
import com.artemis.Entity;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.utils.Array;
import com.galvarez.ttw.model.data.Empire;
import com.galvarez.ttw.utils.MyMath;
package com.galvarez.ttw.model.map;
public final class GameMap {
public final Terrain[][] map;
private final Entity[][] entityByCoord;
private final MapPosition[][] posByCoord;
private final Influence[][] influenceByCoord;
public final int width, height;
/** Represents the whole map as a single image. */
public final Texture texture;
public final Empire[] empires;
public GameMap(Terrain[][] map, Collection<Empire> empires) {
this.map = map;
this.empires = empires.toArray(new Empire[0]);
width = map.length;
height = map[0].length;
entityByCoord = new Entity[width][height];
influenceByCoord = new Influence[width][height];
posByCoord = new MapPosition[width][height];
Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
MapPosition pos = posByCoord[x][y] = new MapPosition(x, y);
influenceByCoord[x][y] = new Influence(pos, map[x][y]);
pixmap.setColor(map[x][y].getColor());
pixmap.drawPixel(x, y);
}
}
texture = new Texture(pixmap);
pixmap.dispose();
}
public Entity getEntityAt(int x, int y) {
if (isOnMap(x, y))
return entityByCoord[x][y];
else
return null;
}
public Entity getEntityAt(MapPosition pos) {
return getEntityAt(pos.x, pos.y);
}
public boolean hasEntity(MapPosition pos) {
return getEntityAt(pos) != null;
}
public Terrain getTerrainAt(MapPosition pos) {
return getTerrainAt(pos.x, pos.y);
}
public Terrain getTerrainAt(int x, int y) {
if (isOnMap(x, y))
return map[x][y];
else
throw new IllegalStateException("(" + x + ", " + y + ") is outside map boundaries.");
}
public Influence getInfluenceAt(MapPosition pos) {
return getInfluenceAt(pos.x, pos.y);
}
public Influence getInfluenceAt(int x, int y) {
if (isOnMap(x, y))
return influenceByCoord[x][y];
else
throw new IllegalStateException("(" + x + ", " + y + ") is outside map boundaries.");
}
public boolean isOnMap(MapPosition p) {
return isOnMap(p.x, p.y);
}
public boolean isOnMap(int x, int y) {
return x >= 0 && x < posByCoord.length && y >= 0 && y < posByCoord[0].length;
}
public MapPosition getPositionAt(int x, int y) {
if (isOnMap(x, y))
return posByCoord[x][y];
else
throw new IllegalStateException("(" + x + ", " + y + ") is outside map boundaries.");
}
public void setEntity(Entity e, int x, int y) {
entityByCoord[x][y] = e;
}
public void setEntity(Entity e, MapPosition p) {
setEntity(e, p.x, p.y);
}
public void moveEntity(Entity e, MapPosition from, MapPosition to) {
entityByCoord[from.x][from.y] = null;
entityByCoord[to.x][to.y] = e;
}
public Array<MapPosition> getNeighbors(int x, int y, int n) {
Array<MapPosition> coordinates = new Array<MapPosition>();
int min;
int myrow;
for (int row = y - n; row < y + n + 1; row++) { | min = MyMath.min(2 * (row - y + n), n, -2 * (row - y - n) + 1); |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/components/Diplomacy.java | // Path: core/src/com/galvarez/ttw/model/DiplomaticSystem.java
// public enum Action {
//
// NO_CHANGE("no change", null, null, allOf(State.class), a -> false),
//
// DECLARE_WAR("declare war", State.WAR, State.WAR, complementOf(of(State.WAR)), a -> true),
//
// MAKE_PEACE("make peace", State.NONE, State.NONE, of(State.WAR), a -> false),
//
// SIGN_TREATY("sign a treaty", State.TREATY, State.TREATY, of(State.WAR, State.NONE, State.TRIBUTE,
// State.PROTECTORATE), a -> a == MAKE_PEACE),
//
// SURRENDER("surrender", State.TRIBUTE, State.PROTECTORATE, of(State.WAR), a -> a == MAKE_PEACE || a == SIGN_TREATY);
//
// public final String str;
//
// public final Set<State> before;
//
// private final State afterMe;
//
// private final State afterYou;
//
// private final Predicate<Action> compatibleWith;
//
// private Action(String str, State afterMe, State afterYou, Set<State> before, Predicate<Action> compatibleWith) {
// this.str = str;
// this.afterMe = afterMe;
// this.afterYou = afterYou;
// this.before = before;
// this.compatibleWith = compatibleWith;
// }
//
// public boolean compatibleWith(Action targetProposal) {
// return targetProposal == this || compatibleWith.test(targetProposal);
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/DiplomaticSystem.java
// public enum State {
// NONE, WAR, TREATY, PROTECTORATE, TRIBUTE;
// }
| import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.artemis.Component;
import com.artemis.Entity;
import com.badlogic.gdx.utils.ObjectIntMap;
import com.galvarez.ttw.model.DiplomaticSystem.Action;
import com.galvarez.ttw.model.DiplomaticSystem.State; | package com.galvarez.ttw.model.components;
public final class Diplomacy extends Component {
public final Map<Entity, State> relations = new HashMap<>();
public final ObjectIntMap<Entity> lastChange = new ObjectIntMap<>();
| // Path: core/src/com/galvarez/ttw/model/DiplomaticSystem.java
// public enum Action {
//
// NO_CHANGE("no change", null, null, allOf(State.class), a -> false),
//
// DECLARE_WAR("declare war", State.WAR, State.WAR, complementOf(of(State.WAR)), a -> true),
//
// MAKE_PEACE("make peace", State.NONE, State.NONE, of(State.WAR), a -> false),
//
// SIGN_TREATY("sign a treaty", State.TREATY, State.TREATY, of(State.WAR, State.NONE, State.TRIBUTE,
// State.PROTECTORATE), a -> a == MAKE_PEACE),
//
// SURRENDER("surrender", State.TRIBUTE, State.PROTECTORATE, of(State.WAR), a -> a == MAKE_PEACE || a == SIGN_TREATY);
//
// public final String str;
//
// public final Set<State> before;
//
// private final State afterMe;
//
// private final State afterYou;
//
// private final Predicate<Action> compatibleWith;
//
// private Action(String str, State afterMe, State afterYou, Set<State> before, Predicate<Action> compatibleWith) {
// this.str = str;
// this.afterMe = afterMe;
// this.afterYou = afterYou;
// this.before = before;
// this.compatibleWith = compatibleWith;
// }
//
// public boolean compatibleWith(Action targetProposal) {
// return targetProposal == this || compatibleWith.test(targetProposal);
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/model/DiplomaticSystem.java
// public enum State {
// NONE, WAR, TREATY, PROTECTORATE, TRIBUTE;
// }
// Path: core/src/com/galvarez/ttw/model/components/Diplomacy.java
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.artemis.Component;
import com.artemis.Entity;
import com.badlogic.gdx.utils.ObjectIntMap;
import com.galvarez.ttw.model.DiplomaticSystem.Action;
import com.galvarez.ttw.model.DiplomaticSystem.State;
package com.galvarez.ttw.model.components;
public final class Diplomacy extends Component {
public final Map<Entity, State> relations = new HashMap<>();
public final ObjectIntMap<Entity> lastChange = new ObjectIntMap<>();
| public final Map<Entity, Action> proposals = new HashMap<>(); |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/components/Destination.java | // Path: core/src/com/galvarez/ttw/model/map/MapPosition.java
// public final class MapPosition extends Component {
//
// public final int x, y;
//
// public MapPosition(int x, int y) {
// this.x = x;
// this.y = y;
// }
//
// @Override
// public int hashCode() {
// return x + y * 31;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof MapPosition) {
// MapPosition p = (MapPosition) obj;
// return x == p.x && y == p.y;
// }
// return false;
// }
//
// @Override
// public String toString() {
// return "(" + x + "," + y + ")";
// }
// }
//
// Path: core/src/com/galvarez/ttw/model/map/Terrain.java
// public enum Terrain {
//
// DEEP_WATER("deep water", Color.NAVY, 50, false),
//
// SHALLOW_WATER("shallow water", Color.BLUE, 30, false),
//
// DESERT("desert", Color.YELLOW, 50, false),
//
// PLAIN("plain", Color.GREEN, 10, true),
//
// GRASSLAND("grassland", new Color(0, 0.5f, 0, 1), 15, true),
//
// FOREST("forest", Color.OLIVE, 30, true),
//
// HILLS("hills", Color.ORANGE, 30, true),
//
// MOUNTAIN("mountain", Color.MAROON, 50, false),
//
// ARCTIC("arctic", Color.WHITE, 100, false);
//
// private final Color color;
//
// private final int moveCost;
//
// private final String desc;
//
// private final boolean canStart;
//
// private Terrain(String desc, Color color, int moveCost, boolean canStart) {
// this.desc = desc;
// this.moveCost = moveCost;
// this.color = color;
// this.canStart = canStart;
// }
//
// public Color getColor() {
// return color;
// }
//
// public boolean moveBlock() {
// return false;
// }
//
// public boolean canStart() {
// return canStart;
// }
//
// public int moveCost() {
// return moveCost;
// }
//
// public int getTexture() {
// return ordinal();
// }
//
// public String getDesc() {
// return desc;
// }
//
// }
| import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import com.artemis.Component;
import com.galvarez.ttw.model.map.MapPosition;
import com.galvarez.ttw.model.map.Terrain; | package com.galvarez.ttw.model.components;
/**
* Store destination (and the path to it) for an entity.
*
* @author Guillaume Alvarez
*/
public final class Destination extends Component {
public final Set<Terrain> forbiddenTiles;
| // Path: core/src/com/galvarez/ttw/model/map/MapPosition.java
// public final class MapPosition extends Component {
//
// public final int x, y;
//
// public MapPosition(int x, int y) {
// this.x = x;
// this.y = y;
// }
//
// @Override
// public int hashCode() {
// return x + y * 31;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof MapPosition) {
// MapPosition p = (MapPosition) obj;
// return x == p.x && y == p.y;
// }
// return false;
// }
//
// @Override
// public String toString() {
// return "(" + x + "," + y + ")";
// }
// }
//
// Path: core/src/com/galvarez/ttw/model/map/Terrain.java
// public enum Terrain {
//
// DEEP_WATER("deep water", Color.NAVY, 50, false),
//
// SHALLOW_WATER("shallow water", Color.BLUE, 30, false),
//
// DESERT("desert", Color.YELLOW, 50, false),
//
// PLAIN("plain", Color.GREEN, 10, true),
//
// GRASSLAND("grassland", new Color(0, 0.5f, 0, 1), 15, true),
//
// FOREST("forest", Color.OLIVE, 30, true),
//
// HILLS("hills", Color.ORANGE, 30, true),
//
// MOUNTAIN("mountain", Color.MAROON, 50, false),
//
// ARCTIC("arctic", Color.WHITE, 100, false);
//
// private final Color color;
//
// private final int moveCost;
//
// private final String desc;
//
// private final boolean canStart;
//
// private Terrain(String desc, Color color, int moveCost, boolean canStart) {
// this.desc = desc;
// this.moveCost = moveCost;
// this.color = color;
// this.canStart = canStart;
// }
//
// public Color getColor() {
// return color;
// }
//
// public boolean moveBlock() {
// return false;
// }
//
// public boolean canStart() {
// return canStart;
// }
//
// public int moveCost() {
// return moveCost;
// }
//
// public int getTexture() {
// return ordinal();
// }
//
// public String getDesc() {
// return desc;
// }
//
// }
// Path: core/src/com/galvarez/ttw/model/components/Destination.java
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import com.artemis.Component;
import com.galvarez.ttw.model.map.MapPosition;
import com.galvarez.ttw.model.map.Terrain;
package com.galvarez.ttw.model.components;
/**
* Store destination (and the path to it) for an entity.
*
* @author Guillaume Alvarez
*/
public final class Destination extends Component {
public final Set<Terrain> forbiddenTiles;
| public MapPosition target; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/rendering/SpriteAnimationSystem.java | // Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/SpriteAnimation.java
// public final class SpriteAnimation extends Component {
//
// public Animation<TextureRegion> animation;
//
// public float stateTime = 0f;
//
// public float frameDuration = 0.1f;
//
// public PlayMode playMode = PlayMode.NORMAL;
//
// public SpriteAnimation() {
// }
//
// public TextureRegion getFrame() {
// return animation.getKeyFrame(stateTime);
// }
//
// }
| import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.galvarez.ttw.rendering.components.Sprite;
import com.galvarez.ttw.rendering.components.SpriteAnimation;
| package com.galvarez.ttw.rendering;
@Wire
public final class SpriteAnimationSystem extends EntityProcessingSystem {
| // Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/SpriteAnimation.java
// public final class SpriteAnimation extends Component {
//
// public Animation<TextureRegion> animation;
//
// public float stateTime = 0f;
//
// public float frameDuration = 0.1f;
//
// public PlayMode playMode = PlayMode.NORMAL;
//
// public SpriteAnimation() {
// }
//
// public TextureRegion getFrame() {
// return animation.getKeyFrame(stateTime);
// }
//
// }
// Path: core/src/com/galvarez/ttw/rendering/SpriteAnimationSystem.java
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.galvarez.ttw.rendering.components.Sprite;
import com.galvarez.ttw.rendering.components.SpriteAnimation;
package com.galvarez.ttw.rendering;
@Wire
public final class SpriteAnimationSystem extends EntityProcessingSystem {
| private ComponentMapper<Sprite> sm;
|
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/rendering/SpriteAnimationSystem.java | // Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/SpriteAnimation.java
// public final class SpriteAnimation extends Component {
//
// public Animation<TextureRegion> animation;
//
// public float stateTime = 0f;
//
// public float frameDuration = 0.1f;
//
// public PlayMode playMode = PlayMode.NORMAL;
//
// public SpriteAnimation() {
// }
//
// public TextureRegion getFrame() {
// return animation.getKeyFrame(stateTime);
// }
//
// }
| import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.galvarez.ttw.rendering.components.Sprite;
import com.galvarez.ttw.rendering.components.SpriteAnimation;
| package com.galvarez.ttw.rendering;
@Wire
public final class SpriteAnimationSystem extends EntityProcessingSystem {
private ComponentMapper<Sprite> sm;
| // Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/SpriteAnimation.java
// public final class SpriteAnimation extends Component {
//
// public Animation<TextureRegion> animation;
//
// public float stateTime = 0f;
//
// public float frameDuration = 0.1f;
//
// public PlayMode playMode = PlayMode.NORMAL;
//
// public SpriteAnimation() {
// }
//
// public TextureRegion getFrame() {
// return animation.getKeyFrame(stateTime);
// }
//
// }
// Path: core/src/com/galvarez/ttw/rendering/SpriteAnimationSystem.java
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.galvarez.ttw.rendering.components.Sprite;
import com.galvarez.ttw.rendering.components.SpriteAnimation;
package com.galvarez.ttw.rendering;
@Wire
public final class SpriteAnimationSystem extends EntityProcessingSystem {
private ComponentMapper<Sprite> sm;
| private ComponentMapper<SpriteAnimation> sam;
|
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/data/Discovery.java | // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
//
// Path: core/src/com/galvarez/ttw/model/map/Terrain.java
// public enum Terrain {
//
// DEEP_WATER("deep water", Color.NAVY, 50, false),
//
// SHALLOW_WATER("shallow water", Color.BLUE, 30, false),
//
// DESERT("desert", Color.YELLOW, 50, false),
//
// PLAIN("plain", Color.GREEN, 10, true),
//
// GRASSLAND("grassland", new Color(0, 0.5f, 0, 1), 15, true),
//
// FOREST("forest", Color.OLIVE, 30, true),
//
// HILLS("hills", Color.ORANGE, 30, true),
//
// MOUNTAIN("mountain", Color.MAROON, 50, false),
//
// ARCTIC("arctic", Color.WHITE, 100, false);
//
// private final Color color;
//
// private final int moveCost;
//
// private final String desc;
//
// private final boolean canStart;
//
// private Terrain(String desc, Color color, int moveCost, boolean canStart) {
// this.desc = desc;
// this.moveCost = moveCost;
// this.color = color;
// this.canStart = canStart;
// }
//
// public Color getColor() {
// return color;
// }
//
// public boolean moveBlock() {
// return false;
// }
//
// public boolean canStart() {
// return canStart;
// }
//
// public int moveCost() {
// return moveCost;
// }
//
// public int getTexture() {
// return ordinal();
// }
//
// public String getDesc() {
// return desc;
// }
//
// }
| import static java.util.stream.Collectors.toSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.ReadOnlySerializer;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.ObjectFloatMap;
import com.galvarez.ttw.model.Faction;
import com.galvarez.ttw.model.map.Terrain; | package com.galvarez.ttw.model.data;
public final class Discovery {
public final String name;
| // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
//
// Path: core/src/com/galvarez/ttw/model/map/Terrain.java
// public enum Terrain {
//
// DEEP_WATER("deep water", Color.NAVY, 50, false),
//
// SHALLOW_WATER("shallow water", Color.BLUE, 30, false),
//
// DESERT("desert", Color.YELLOW, 50, false),
//
// PLAIN("plain", Color.GREEN, 10, true),
//
// GRASSLAND("grassland", new Color(0, 0.5f, 0, 1), 15, true),
//
// FOREST("forest", Color.OLIVE, 30, true),
//
// HILLS("hills", Color.ORANGE, 30, true),
//
// MOUNTAIN("mountain", Color.MAROON, 50, false),
//
// ARCTIC("arctic", Color.WHITE, 100, false);
//
// private final Color color;
//
// private final int moveCost;
//
// private final String desc;
//
// private final boolean canStart;
//
// private Terrain(String desc, Color color, int moveCost, boolean canStart) {
// this.desc = desc;
// this.moveCost = moveCost;
// this.color = color;
// this.canStart = canStart;
// }
//
// public Color getColor() {
// return color;
// }
//
// public boolean moveBlock() {
// return false;
// }
//
// public boolean canStart() {
// return canStart;
// }
//
// public int moveCost() {
// return moveCost;
// }
//
// public int getTexture() {
// return ordinal();
// }
//
// public String getDesc() {
// return desc;
// }
//
// }
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
import static java.util.stream.Collectors.toSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.ReadOnlySerializer;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.ObjectFloatMap;
import com.galvarez.ttw.model.Faction;
import com.galvarez.ttw.model.map.Terrain;
package com.galvarez.ttw.model.data;
public final class Discovery {
public final String name;
| public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class); |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/data/Discovery.java | // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
//
// Path: core/src/com/galvarez/ttw/model/map/Terrain.java
// public enum Terrain {
//
// DEEP_WATER("deep water", Color.NAVY, 50, false),
//
// SHALLOW_WATER("shallow water", Color.BLUE, 30, false),
//
// DESERT("desert", Color.YELLOW, 50, false),
//
// PLAIN("plain", Color.GREEN, 10, true),
//
// GRASSLAND("grassland", new Color(0, 0.5f, 0, 1), 15, true),
//
// FOREST("forest", Color.OLIVE, 30, true),
//
// HILLS("hills", Color.ORANGE, 30, true),
//
// MOUNTAIN("mountain", Color.MAROON, 50, false),
//
// ARCTIC("arctic", Color.WHITE, 100, false);
//
// private final Color color;
//
// private final int moveCost;
//
// private final String desc;
//
// private final boolean canStart;
//
// private Terrain(String desc, Color color, int moveCost, boolean canStart) {
// this.desc = desc;
// this.moveCost = moveCost;
// this.color = color;
// this.canStart = canStart;
// }
//
// public Color getColor() {
// return color;
// }
//
// public boolean moveBlock() {
// return false;
// }
//
// public boolean canStart() {
// return canStart;
// }
//
// public int moveCost() {
// return moveCost;
// }
//
// public int getTexture() {
// return ordinal();
// }
//
// public String getDesc() {
// return desc;
// }
//
// }
| import static java.util.stream.Collectors.toSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.ReadOnlySerializer;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.ObjectFloatMap;
import com.galvarez.ttw.model.Faction;
import com.galvarez.ttw.model.map.Terrain; | package com.galvarez.ttw.model.data;
public final class Discovery {
public final String name;
public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
public final Set<String> groups;
public final Set<Set<String>> previous;
| // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
//
// Path: core/src/com/galvarez/ttw/model/map/Terrain.java
// public enum Terrain {
//
// DEEP_WATER("deep water", Color.NAVY, 50, false),
//
// SHALLOW_WATER("shallow water", Color.BLUE, 30, false),
//
// DESERT("desert", Color.YELLOW, 50, false),
//
// PLAIN("plain", Color.GREEN, 10, true),
//
// GRASSLAND("grassland", new Color(0, 0.5f, 0, 1), 15, true),
//
// FOREST("forest", Color.OLIVE, 30, true),
//
// HILLS("hills", Color.ORANGE, 30, true),
//
// MOUNTAIN("mountain", Color.MAROON, 50, false),
//
// ARCTIC("arctic", Color.WHITE, 100, false);
//
// private final Color color;
//
// private final int moveCost;
//
// private final String desc;
//
// private final boolean canStart;
//
// private Terrain(String desc, Color color, int moveCost, boolean canStart) {
// this.desc = desc;
// this.moveCost = moveCost;
// this.color = color;
// this.canStart = canStart;
// }
//
// public Color getColor() {
// return color;
// }
//
// public boolean moveBlock() {
// return false;
// }
//
// public boolean canStart() {
// return canStart;
// }
//
// public int moveCost() {
// return moveCost;
// }
//
// public int getTexture() {
// return ordinal();
// }
//
// public String getDesc() {
// return desc;
// }
//
// }
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
import static java.util.stream.Collectors.toSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.ReadOnlySerializer;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.ObjectFloatMap;
import com.galvarez.ttw.model.Faction;
import com.galvarez.ttw.model.map.Terrain;
package com.galvarez.ttw.model.data;
public final class Discovery {
public final String name;
public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
public final Set<String> groups;
public final Set<Set<String>> previous;
| public ObjectFloatMap<Faction> factions; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/components/AIControlled.java | // Path: core/src/com/galvarez/ttw/model/map/MapPosition.java
// public final class MapPosition extends Component {
//
// public final int x, y;
//
// public MapPosition(int x, int y) {
// this.x = x;
// this.y = y;
// }
//
// @Override
// public int hashCode() {
// return x + y * 31;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof MapPosition) {
// MapPosition p = (MapPosition) obj;
// return x == p.x && y == p.y;
// }
// return false;
// }
//
// @Override
// public String toString() {
// return "(" + x + "," + y + ")";
// }
// }
| import java.util.ArrayList;
import java.util.List;
import com.artemis.Component;
import com.galvarez.ttw.model.map.MapPosition; | package com.galvarez.ttw.model.components;
public final class AIControlled extends Component {
public int lastMove;
| // Path: core/src/com/galvarez/ttw/model/map/MapPosition.java
// public final class MapPosition extends Component {
//
// public final int x, y;
//
// public MapPosition(int x, int y) {
// this.x = x;
// this.y = y;
// }
//
// @Override
// public int hashCode() {
// return x + y * 31;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof MapPosition) {
// MapPosition p = (MapPosition) obj;
// return x == p.x && y == p.y;
// }
// return false;
// }
//
// @Override
// public String toString() {
// return "(" + x + "," + y + ")";
// }
// }
// Path: core/src/com/galvarez/ttw/model/components/AIControlled.java
import java.util.ArrayList;
import java.util.List;
import com.artemis.Component;
import com.galvarez.ttw.model.map.MapPosition;
package com.galvarez.ttw.model.components;
public final class AIControlled extends Component {
public int lastMove;
| public MapPosition lastPosition; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/utils/DiscoveriesToPlantuml.java | // Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
| import com.badlogic.gdx.utils.Json;
import com.galvarez.ttw.model.data.Discovery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors; | package com.galvarez.ttw.utils;
public final class DiscoveriesToPlantuml {
private static final Logger log = LoggerFactory.getLogger(DiscoveriesToPlantuml.class);
| // Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
// Path: core/src/com/galvarez/ttw/utils/DiscoveriesToPlantuml.java
import com.badlogic.gdx.utils.Json;
import com.galvarez.ttw.model.data.Discovery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
package com.galvarez.ttw.utils;
public final class DiscoveriesToPlantuml {
private static final Logger log = LoggerFactory.getLogger(DiscoveriesToPlantuml.class);
| private static List<Discovery> discoveries() throws IOException { |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/components/Discoveries.java | // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
| import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.artemis.Component;
import com.galvarez.ttw.model.Faction;
import com.galvarez.ttw.model.data.Discovery; | package com.galvarez.ttw.model.components;
public final class Discoveries extends Component {
public final Set<Discovery> done = new HashSet<>();
/** Increase to speed progress up. */
public int progressPerTurn = 1;
/** Contains possibles discoveries when one is expected. */ | // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
//
// Path: core/src/com/galvarez/ttw/model/data/Discovery.java
// public final class Discovery {
//
// public final String name;
//
// public final Set<Terrain> terrains = EnumSet.noneOf(Terrain.class);
//
// public final Set<String> groups;
//
// public final Set<Set<String>> previous;
//
// public ObjectFloatMap<Faction> factions;
//
// /**
// * Indexed by effect name, contains the delta for the corresponding variable.
// * Positive numbers are positive modifiers for the discoverer.
// */
// public final Map<String, Object> effects;
//
// private Discovery(String name, List<List<String>> previous, List<String> groups, List<Terrain> terrains,
// Map<String, Object> effects) {
// this.name = name;
// this.effects = effects != null ? effects : Collections.emptyMap();
// this.previous = previous.stream().filter(l -> !l.isEmpty()).map(l -> set(l)).collect(toSet());
// this.groups = set(groups);
// if (terrains != null)
// this.terrains.addAll(terrains);
// }
//
// @SuppressWarnings("unchecked")
// private static <T> Set<T> set(List<T> list) {
// if (list == null || list.isEmpty())
// return Collections.emptySet();
// if (list.size() == 1)
// return Collections.singleton(list.get(0));
// else if (list instanceof Set)
// return (Set<T>) list;
// else
// return new HashSet<>(list);
// }
//
// public Discovery(String name) {
// this(name, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), null);
// }
//
// public String getName() {
// return name;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// @Override
// public int hashCode() {
// return name.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Discovery)
// return name.equals(((Discovery) obj).name);
// else
// return false;
// }
//
// public static final ReadOnlySerializer<Discovery> SER = new ReadOnlySerializer<Discovery>() {
// @SuppressWarnings("unchecked")
// @Override
// public Discovery read(Json json, JsonValue data, Class type) {
// return new Discovery(data.getString("name"), //
// json.readValue(ArrayList.class, ArrayList.class, data.get("previous")), //
// json.readValue(ArrayList.class, data.get("groups")), //
// json.readValue(ArrayList.class, Terrain.class, data.get("terrains")), //
// json.readValue(HashMap.class, data.get("effects")));
// }
// };
//
// }
// Path: core/src/com/galvarez/ttw/model/components/Discoveries.java
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.artemis.Component;
import com.galvarez.ttw.model.Faction;
import com.galvarez.ttw.model.data.Discovery;
package com.galvarez.ttw.model.components;
public final class Discoveries extends Component {
public final Set<Discovery> done = new HashSet<>();
/** Increase to speed progress up. */
public int progressPerTurn = 1;
/** Contains possibles discoveries when one is expected. */ | public Map<Faction, Research> nextPossible; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/data/Culture.java | // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
| import java.util.EnumMap;
import java.util.Map;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.ReadOnlySerializer;
import com.badlogic.gdx.utils.JsonValue;
import com.galvarez.ttw.model.Faction; | package com.galvarez.ttw.model.data;
// TODO do not allow modification after loading
public final class Culture {
public final String name;
public final Array<String> cities;
private int citiesIndex = -1;
| // Path: core/src/com/galvarez/ttw/model/Faction.java
// public enum Faction {
//
// MILITARY, ECONOMIC, CULTURAL;
//
// }
// Path: core/src/com/galvarez/ttw/model/data/Culture.java
import java.util.EnumMap;
import java.util.Map;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.ReadOnlySerializer;
import com.badlogic.gdx.utils.JsonValue;
import com.galvarez.ttw.model.Faction;
package com.galvarez.ttw.model.data;
// TODO do not allow modification after loading
public final class Culture {
public final String name;
public final Array<String> cities;
private int citiesIndex = -1;
| public final Map<Faction, Integer> ai; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/rendering/ColorAnimationSystem.java | // Path: core/src/com/galvarez/ttw/rendering/components/ColorAnimation.java
// public final class ColorAnimation extends PooledComponent {
//
// public float redMin, redMax, redSpeed;
//
// public float greenMin, greenMax, greenSpeed;
//
// public float blueMin, blueMax, blueSpeed;
//
// public float alphaMin, alphaMax, alphaSpeed;
//
// public boolean redAnimate, greenAnimate, blueAnimate, alphaAnimate, repeat;
//
// public ColorAnimation() {
// }
//
// @Override
// protected void reset() {
// redMin = greenMin = blueMin = alphaMin = 0f;
// redMax = greenMax = blueMax = alphaMax = 1f;
// redSpeed = greenSpeed = blueSpeed = alphaSpeed = 1f;
// redAnimate = greenAnimate = blueAnimate = alphaAnimate = repeat = false;
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
| import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.rendering.components.ColorAnimation;
import com.galvarez.ttw.rendering.components.Sprite;
| package com.galvarez.ttw.rendering;
@Wire
public final class ColorAnimationSystem extends EntityProcessingSystem {
| // Path: core/src/com/galvarez/ttw/rendering/components/ColorAnimation.java
// public final class ColorAnimation extends PooledComponent {
//
// public float redMin, redMax, redSpeed;
//
// public float greenMin, greenMax, greenSpeed;
//
// public float blueMin, blueMax, blueSpeed;
//
// public float alphaMin, alphaMax, alphaSpeed;
//
// public boolean redAnimate, greenAnimate, blueAnimate, alphaAnimate, repeat;
//
// public ColorAnimation() {
// }
//
// @Override
// protected void reset() {
// redMin = greenMin = blueMin = alphaMin = 0f;
// redMax = greenMax = blueMax = alphaMax = 1f;
// redSpeed = greenSpeed = blueSpeed = alphaSpeed = 1f;
// redAnimate = greenAnimate = blueAnimate = alphaAnimate = repeat = false;
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
// Path: core/src/com/galvarez/ttw/rendering/ColorAnimationSystem.java
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.rendering.components.ColorAnimation;
import com.galvarez.ttw.rendering.components.Sprite;
package com.galvarez.ttw.rendering;
@Wire
public final class ColorAnimationSystem extends EntityProcessingSystem {
| private ComponentMapper<ColorAnimation> cam;
|
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/rendering/ColorAnimationSystem.java | // Path: core/src/com/galvarez/ttw/rendering/components/ColorAnimation.java
// public final class ColorAnimation extends PooledComponent {
//
// public float redMin, redMax, redSpeed;
//
// public float greenMin, greenMax, greenSpeed;
//
// public float blueMin, blueMax, blueSpeed;
//
// public float alphaMin, alphaMax, alphaSpeed;
//
// public boolean redAnimate, greenAnimate, blueAnimate, alphaAnimate, repeat;
//
// public ColorAnimation() {
// }
//
// @Override
// protected void reset() {
// redMin = greenMin = blueMin = alphaMin = 0f;
// redMax = greenMax = blueMax = alphaMax = 1f;
// redSpeed = greenSpeed = blueSpeed = alphaSpeed = 1f;
// redAnimate = greenAnimate = blueAnimate = alphaAnimate = repeat = false;
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
| import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.rendering.components.ColorAnimation;
import com.galvarez.ttw.rendering.components.Sprite;
| package com.galvarez.ttw.rendering;
@Wire
public final class ColorAnimationSystem extends EntityProcessingSystem {
private ComponentMapper<ColorAnimation> cam;
| // Path: core/src/com/galvarez/ttw/rendering/components/ColorAnimation.java
// public final class ColorAnimation extends PooledComponent {
//
// public float redMin, redMax, redSpeed;
//
// public float greenMin, greenMax, greenSpeed;
//
// public float blueMin, blueMax, blueSpeed;
//
// public float alphaMin, alphaMax, alphaSpeed;
//
// public boolean redAnimate, greenAnimate, blueAnimate, alphaAnimate, repeat;
//
// public ColorAnimation() {
// }
//
// @Override
// protected void reset() {
// redMin = greenMin = blueMin = alphaMin = 0f;
// redMax = greenMax = blueMax = alphaMax = 1f;
// redSpeed = greenSpeed = blueSpeed = alphaSpeed = 1f;
// redAnimate = greenAnimate = blueAnimate = alphaAnimate = repeat = false;
// }
//
// }
//
// Path: core/src/com/galvarez/ttw/rendering/components/Sprite.java
// public final class Sprite extends Component {
//
// public enum Layer {
// DEFAULT, BACKGROUND, ACTORS_1, ACTORS_2, ACTORS_3, PARTICLES;
//
// public int getLayerId() {
// return ordinal();
// }
// }
//
// public Color color = Color.WHITE;
//
// public TextureRegion region;
//
// public String name;
//
// public float scaleX, scaleY = 1f;
//
// public float rotation = 0f;
//
// public int x, y, width, height;
//
// public Layer layer = Layer.DEFAULT;
//
// public int index;
//
// public Sprite() {
// }
//
// }
// Path: core/src/com/galvarez/ttw/rendering/ColorAnimationSystem.java
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.rendering.components.ColorAnimation;
import com.galvarez.ttw.rendering.components.Sprite;
package com.galvarez.ttw.rendering;
@Wire
public final class ColorAnimationSystem extends EntityProcessingSystem {
private ComponentMapper<ColorAnimation> cam;
| private ComponentMapper<Sprite> sm;
|
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/EventsSystem.java | // Path: core/src/com/galvarez/ttw/model/components/EventsCount.java
// public class EventsCount extends Component {
//
// public final ObjectIntMap<EventHandler> scores = new ObjectIntMap<>();
//
// public final ObjectIntMap<EventHandler> increment = new ObjectIntMap<>();
//
// public final ObjectIntMap<EventHandler> display = new ObjectIntMap<>();
//
// public final Map<EventHandler, String> reasons = new HashMap<>();
//
// public EventsCount() {
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.annotations.Wire;
import com.artemis.utils.ImmutableBag;
import com.galvarez.ttw.model.components.EventsCount; | package com.galvarez.ttw.model;
@Wire
public final class EventsSystem extends EntitySystem {
public interface EventHandler {
/** Get the score progress toward next event of this type. */
int getProgress(Entity e);
/** Get the reason for this event. */
String getReason(Entity e);
/**
* Execute the event on the entity.
*
* @return true if it could execute the event (false if some system
* condition prevented it)
*/
boolean execute(Entity e);
/** A pretty printing name for the event. */
String getType();
}
| // Path: core/src/com/galvarez/ttw/model/components/EventsCount.java
// public class EventsCount extends Component {
//
// public final ObjectIntMap<EventHandler> scores = new ObjectIntMap<>();
//
// public final ObjectIntMap<EventHandler> increment = new ObjectIntMap<>();
//
// public final ObjectIntMap<EventHandler> display = new ObjectIntMap<>();
//
// public final Map<EventHandler, String> reasons = new HashMap<>();
//
// public EventsCount() {
// }
//
// }
// Path: core/src/com/galvarez/ttw/model/EventsSystem.java
import java.util.ArrayList;
import java.util.List;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.annotations.Wire;
import com.artemis.utils.ImmutableBag;
import com.galvarez.ttw.model.components.EventsCount;
package com.galvarez.ttw.model;
@Wire
public final class EventsSystem extends EntitySystem {
public interface EventHandler {
/** Get the score progress toward next event of this type. */
int getProgress(Entity e);
/** Get the reason for this event. */
String getReason(Entity e);
/**
* Execute the event on the entity.
*
* @return true if it could execute the event (false if some system
* condition prevented it)
*/
boolean execute(Entity e);
/** A pretty printing name for the event. */
String getType();
}
| private ComponentMapper<EventsCount> counts; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/utils/Colors.java | // Path: core/src/com/galvarez/ttw/model/data/Empire.java
// public final class Empire extends Component {
//
// private static final AtomicInteger COUNTER = new AtomicInteger(0);
//
// public final int id;
//
// public final Color color;
//
// public final Color backColor;
//
// public final Culture culture;
//
// private final boolean computer;
//
// public Empire(Color color, Culture culture, boolean computer) {
// this.id = COUNTER.getAndIncrement();
// this.color = color;
// this.backColor = Colors.contrast(color);
// this.culture = culture;
// this.computer = computer;
// }
//
// public boolean isComputerControlled() {
// return computer;
// }
//
// public Color getColor() {
// return color;
// }
//
// public Culture getCulture() {
// return culture;
// }
//
// public String newCityName() {
// return culture.newCityName();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Empire)
// return id == ((Empire) obj).id;
// else
// return false;
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public String toString() {
// return culture.name + "(ia=" + computer + ")";
// }
//
// }
| import com.artemis.Entity;
import com.badlogic.gdx.graphics.Color;
import com.galvarez.ttw.model.data.Empire; | package com.galvarez.ttw.utils;
/**
* Utilities for colors.
*
* @author Guillaume Alvarez
*/
public final class Colors {
private Colors() {
}
/**
* Compute the most contrasting black or white color.
*
* @see http://www.w3.org/TR/AERT#color-contrast
* @see http://24ways.org/2010/calculating-color-contrast/
* @see http://en.wikipedia.org/wiki/YIQ
*/
@SuppressWarnings("javadoc")
public static Color contrast(Color c) {
float yiq = ((c.r * 256 * 299f) + (c.g * 256 * 587f) + (c.b * 256 * 114f)) / 1000f;
return (yiq >= 128f) ? Color.BLACK : Color.WHITE;
}
public static String markup(Entity empire) { | // Path: core/src/com/galvarez/ttw/model/data/Empire.java
// public final class Empire extends Component {
//
// private static final AtomicInteger COUNTER = new AtomicInteger(0);
//
// public final int id;
//
// public final Color color;
//
// public final Color backColor;
//
// public final Culture culture;
//
// private final boolean computer;
//
// public Empire(Color color, Culture culture, boolean computer) {
// this.id = COUNTER.getAndIncrement();
// this.color = color;
// this.backColor = Colors.contrast(color);
// this.culture = culture;
// this.computer = computer;
// }
//
// public boolean isComputerControlled() {
// return computer;
// }
//
// public Color getColor() {
// return color;
// }
//
// public Culture getCulture() {
// return culture;
// }
//
// public String newCityName() {
// return culture.newCityName();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this)
// return true;
// else if (obj instanceof Empire)
// return id == ((Empire) obj).id;
// else
// return false;
// }
//
// @Override
// public int hashCode() {
// return id;
// }
//
// @Override
// public String toString() {
// return culture.name + "(ia=" + computer + ")";
// }
//
// }
// Path: core/src/com/galvarez/ttw/utils/Colors.java
import com.artemis.Entity;
import com.badlogic.gdx.graphics.Color;
import com.galvarez.ttw.model.data.Empire;
package com.galvarez.ttw.utils;
/**
* Utilities for colors.
*
* @author Guillaume Alvarez
*/
public final class Colors {
private Colors() {
}
/**
* Compute the most contrasting black or white color.
*
* @see http://www.w3.org/TR/AERT#color-contrast
* @see http://24ways.org/2010/calculating-color-contrast/
* @see http://en.wikipedia.org/wiki/YIQ
*/
@SuppressWarnings("javadoc")
public static Color contrast(Color c) {
float yiq = ((c.r * 256 * 299f) + (c.g * 256 * 587f) + (c.b * 256 * 114f)) / 1000f;
return (yiq >= 128f) ? Color.BLACK : Color.WHITE;
}
public static String markup(Entity empire) { | return markup(empire.getComponent(Empire.class).color); |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/map/MidpointDisplacement.java | // Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
| import com.badlogic.gdx.math.MathUtils;
import com.galvarez.ttw.utils.MyMath; | package com.galvarez.ttw.model.map;
public class MidpointDisplacement {
public float smoothness;
public MidpointDisplacement() {
// Smoothness controls how smooth the resultant terrain is.
// Higher = smoother
smoothness = 2f;
}
public float[][] getMap2(int n, int wmult, int hmult) {
// get the dimensions of the map | // Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
// Path: core/src/com/galvarez/ttw/model/map/MidpointDisplacement.java
import com.badlogic.gdx.math.MathUtils;
import com.galvarez.ttw.utils.MyMath;
package com.galvarez.ttw.model.map;
public class MidpointDisplacement {
public float smoothness;
public MidpointDisplacement() {
// Smoothness controls how smooth the resultant terrain is.
// Higher = smoother
smoothness = 2f;
}
public float[][] getMap2(int n, int wmult, int hmult) {
// get the dimensions of the map | int power = MyMath.pow(2, n); |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/data/Empire.java | // Path: core/src/com/galvarez/ttw/utils/Colors.java
// public final class Colors {
//
// private Colors() {
// }
//
// /**
// * Compute the most contrasting black or white color.
// *
// * @see http://www.w3.org/TR/AERT#color-contrast
// * @see http://24ways.org/2010/calculating-color-contrast/
// * @see http://en.wikipedia.org/wiki/YIQ
// */
// @SuppressWarnings("javadoc")
// public static Color contrast(Color c) {
// float yiq = ((c.r * 256 * 299f) + (c.g * 256 * 587f) + (c.b * 256 * 114f)) / 1000f;
// return (yiq >= 128f) ? Color.BLACK : Color.WHITE;
//
// }
//
// public static String markup(Entity empire) {
// return markup(empire.getComponent(Empire.class).color);
// }
//
// public static String markup(Color c) {
// return "[#" + c.toString().toUpperCase() + "]";
// }
//
// }
| import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import com.artemis.Component;
import com.badlogic.gdx.graphics.Color;
import com.galvarez.ttw.utils.Colors; | package com.galvarez.ttw.model.data;
/**
* Represent an empire (and a player) in the game.
* <p>
* It can be used as a key in a {@link Map}.
*
* @author Guillaume Alvarez
*/
public final class Empire extends Component {
private static final AtomicInteger COUNTER = new AtomicInteger(0);
public final int id;
public final Color color;
public final Color backColor;
public final Culture culture;
private final boolean computer;
public Empire(Color color, Culture culture, boolean computer) {
this.id = COUNTER.getAndIncrement();
this.color = color; | // Path: core/src/com/galvarez/ttw/utils/Colors.java
// public final class Colors {
//
// private Colors() {
// }
//
// /**
// * Compute the most contrasting black or white color.
// *
// * @see http://www.w3.org/TR/AERT#color-contrast
// * @see http://24ways.org/2010/calculating-color-contrast/
// * @see http://en.wikipedia.org/wiki/YIQ
// */
// @SuppressWarnings("javadoc")
// public static Color contrast(Color c) {
// float yiq = ((c.r * 256 * 299f) + (c.g * 256 * 587f) + (c.b * 256 * 114f)) / 1000f;
// return (yiq >= 128f) ? Color.BLACK : Color.WHITE;
//
// }
//
// public static String markup(Entity empire) {
// return markup(empire.getComponent(Empire.class).color);
// }
//
// public static String markup(Color c) {
// return "[#" + c.toString().toUpperCase() + "]";
// }
//
// }
// Path: core/src/com/galvarez/ttw/model/data/Empire.java
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import com.artemis.Component;
import com.badlogic.gdx.graphics.Color;
import com.galvarez.ttw.utils.Colors;
package com.galvarez.ttw.model.data;
/**
* Represent an empire (and a player) in the game.
* <p>
* It can be used as a key in a {@link Map}.
*
* @author Guillaume Alvarez
*/
public final class Empire extends Component {
private static final AtomicInteger COUNTER = new AtomicInteger(0);
public final int id;
public final Color color;
public final Color backColor;
public final Culture culture;
private final boolean computer;
public Empire(Color color, Culture culture, boolean computer) {
this.id = COUNTER.getAndIncrement();
this.color = color; | this.backColor = Colors.contrast(color); |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/rendering/NotificationsSystem.java | // Path: core/src/com/galvarez/ttw/utils/Assets.java
// public final class Assets implements Disposable {
//
// public static final String FONTS_ROMANICA_TTF = "fonts/Romanica.ttf";
// public static final String UISKIN_JSON = "uiskin/uiskin.json";
// private final Skin skin;
//
// public enum Icon {
// DISCOVERY("discovery-bulb"),
// DIPLOMACY("diplomacy-handshake"),
// BUILDINGS("buildings-hammer"),
// REVOLT("revolt-clenched-fist"),
// FLAG("finish-flag"),
// MILITARY("military-swords"),
// DISEASE("disease-skull"),
// END_TURN("empty-hourglass");
//
// private final String name;
//
// Icon(String name) {
// this.name = name;
// }
// }
//
// private final AssetManager manager;
//
// private final EnumMap<Icon, Drawable> drawables = new EnumMap<>(Icon.class);
//
// private final EnumMap<Icon, TextureRegion> regions = new EnumMap<>(Icon.class);
//
// private final Map<String, BitmapFont> fonts = new HashMap<>();
//
// public Assets() {
// manager = loadAssets();
//
// ObjectMap<String, Object> fonts = new ObjectMap<>();
// fonts.put("default-font", getFont(16));
// fonts.put("colored-font", getFont(16, true));
// manager.load(UISKIN_JSON, Skin.class, new SkinLoader.SkinParameter(fonts));
// manager.finishLoading();
// skin = manager.get(UISKIN_JSON);
//
// for (Icon icon : Icon.values())
// addIcon(icon, icon.name);
// }
//
// private static AssetManager loadAssets() {
// AssetManager manager = new AssetManager();
// manager.finishLoading();
// return manager;
// }
//
//
// private void addIcon(Icon type, String name) {
// drawables.put(type, skin.getDrawable(name));
// regions.put(type, skin.getRegion(name));
// }
//
// public BitmapFont getFont(int size) {
// return getFont(size, false);
// }
//
// public BitmapFont getFont(int size, boolean markupEnabled) {
// String key = "romanica-" + size + "-" + markupEnabled;
// synchronized (fonts) {
// BitmapFont font = fonts.get(key);
// if (font == null) {
// fonts.put(key, font = createFont(size, markupEnabled));
// }
// return font;
// }
// }
//
// private static BitmapFont createFont(int size, boolean markupEnabled) {
// FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/romanica.ttf"));
// FreeTypeFontParameter parameter = new FreeTypeFontParameter();
// try {
// parameter.size = size;
// BitmapFont font = generator.generateFont(parameter);
// font.getData().markupEnabled = markupEnabled;
// return font;
// } finally {
// generator.dispose(); // don't forget to dispose to avoid memory leaks!
// }
// }
//
// public Drawable getDrawable(Icon type) {
// return drawables.get(type);
// }
//
// public TextureRegion getTexture(Icon type) {
// return regions.get(type);
// }
//
// public Skin getSkin() {
// return skin;
// }
//
//
// @Override
// public void dispose() {
// manager.dispose();
// }
// }
| import com.artemis.annotations.Wire;
import com.artemis.systems.VoidEntitySystem;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.galvarez.ttw.utils.Assets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static java.lang.String.format; | package com.galvarez.ttw.rendering;
/**
* Store notifications until processed.
*
* @author Guillaume Alvarez
*/
@Wire
public final class NotificationsSystem extends VoidEntitySystem {
private static final Comparator<Notification> INFO_FIRST = new Comparator<Notification>() {
@Override
public int compare(Notification o1, Notification o2) {
if (o1.requiresAction()) {
if (o2.requiresAction())
return o1.msg.compareTo(o2.msg);
else
return 1;
} else {
if (o2.requiresAction()) return -1;
else
return o1.msg.compareTo(o2.msg);
}
}
};
/** Notifications registered for next turn. */
private final List<Notification> notifications = new ArrayList<>();
/** Notifications for current turn. */
private final List<Notification> current = new ArrayList<>();
| // Path: core/src/com/galvarez/ttw/utils/Assets.java
// public final class Assets implements Disposable {
//
// public static final String FONTS_ROMANICA_TTF = "fonts/Romanica.ttf";
// public static final String UISKIN_JSON = "uiskin/uiskin.json";
// private final Skin skin;
//
// public enum Icon {
// DISCOVERY("discovery-bulb"),
// DIPLOMACY("diplomacy-handshake"),
// BUILDINGS("buildings-hammer"),
// REVOLT("revolt-clenched-fist"),
// FLAG("finish-flag"),
// MILITARY("military-swords"),
// DISEASE("disease-skull"),
// END_TURN("empty-hourglass");
//
// private final String name;
//
// Icon(String name) {
// this.name = name;
// }
// }
//
// private final AssetManager manager;
//
// private final EnumMap<Icon, Drawable> drawables = new EnumMap<>(Icon.class);
//
// private final EnumMap<Icon, TextureRegion> regions = new EnumMap<>(Icon.class);
//
// private final Map<String, BitmapFont> fonts = new HashMap<>();
//
// public Assets() {
// manager = loadAssets();
//
// ObjectMap<String, Object> fonts = new ObjectMap<>();
// fonts.put("default-font", getFont(16));
// fonts.put("colored-font", getFont(16, true));
// manager.load(UISKIN_JSON, Skin.class, new SkinLoader.SkinParameter(fonts));
// manager.finishLoading();
// skin = manager.get(UISKIN_JSON);
//
// for (Icon icon : Icon.values())
// addIcon(icon, icon.name);
// }
//
// private static AssetManager loadAssets() {
// AssetManager manager = new AssetManager();
// manager.finishLoading();
// return manager;
// }
//
//
// private void addIcon(Icon type, String name) {
// drawables.put(type, skin.getDrawable(name));
// regions.put(type, skin.getRegion(name));
// }
//
// public BitmapFont getFont(int size) {
// return getFont(size, false);
// }
//
// public BitmapFont getFont(int size, boolean markupEnabled) {
// String key = "romanica-" + size + "-" + markupEnabled;
// synchronized (fonts) {
// BitmapFont font = fonts.get(key);
// if (font == null) {
// fonts.put(key, font = createFont(size, markupEnabled));
// }
// return font;
// }
// }
//
// private static BitmapFont createFont(int size, boolean markupEnabled) {
// FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/romanica.ttf"));
// FreeTypeFontParameter parameter = new FreeTypeFontParameter();
// try {
// parameter.size = size;
// BitmapFont font = generator.generateFont(parameter);
// font.getData().markupEnabled = markupEnabled;
// return font;
// } finally {
// generator.dispose(); // don't forget to dispose to avoid memory leaks!
// }
// }
//
// public Drawable getDrawable(Icon type) {
// return drawables.get(type);
// }
//
// public TextureRegion getTexture(Icon type) {
// return regions.get(type);
// }
//
// public Skin getSkin() {
// return skin;
// }
//
//
// @Override
// public void dispose() {
// manager.dispose();
// }
// }
// Path: core/src/com/galvarez/ttw/rendering/NotificationsSystem.java
import com.artemis.annotations.Wire;
import com.artemis.systems.VoidEntitySystem;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.galvarez.ttw.utils.Assets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import static java.lang.String.format;
package com.galvarez.ttw.rendering;
/**
* Store notifications until processed.
*
* @author Guillaume Alvarez
*/
@Wire
public final class NotificationsSystem extends VoidEntitySystem {
private static final Comparator<Notification> INFO_FIRST = new Comparator<Notification>() {
@Override
public int compare(Notification o1, Notification o2) {
if (o1.requiresAction()) {
if (o2.requiresAction())
return o1.msg.compareTo(o2.msg);
else
return 1;
} else {
if (o2.requiresAction()) return -1;
else
return o1.msg.compareTo(o2.msg);
}
}
};
/** Notifications registered for next turn. */
private final List<Notification> notifications = new ArrayList<>();
/** Notifications for current turn. */
private final List<Notification> current = new ArrayList<>();
| private final Assets icons; |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/map/MapTools.java | // Path: core/src/com/galvarez/ttw/utils/FloatPair.java
// public final class FloatPair {
//
// public final float x, y;
//
// public FloatPair(float x, float y) {
// this.x = x;
// this.y = y;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FloatPair)
// return equals((FloatPair) obj);
// return false;
// }
//
// public boolean equals(FloatPair p) {
// return x == p.x && y == p.y;
// }
//
// @Override
// public String toString() {
// return "(" + x + "," + y + ")";
// }
// }
//
// Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
| import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector3;
import com.galvarez.ttw.utils.FloatPair;
import com.galvarez.ttw.utils.MyMath; | TOP_RIGHT {
@Override
public MapPosition getNeighbor(int x, int y) {
return new MapPosition(x + 1, y + (x % 2));
}
};
abstract public MapPosition getNeighbor(int x, int y);
public final MapPosition getNeighbor(MapPosition pos) {
return getNeighbor(pos.x, pos.y);
}
}
public static int distance(MapPosition p0, MapPosition p1) {
int x0 = p0.x;
int y0 = p0.y;
int x1 = p1.x;
int y1 = p1.y;
int dx = Math.abs(x1 - x0);
int dy = Math.abs(y1 - y0);
// The distance can be tricky, because of how the columns are shifted.
// Different cases must be considered, because the dx and dy above
// are not sufficient to determine distance.
if ((dx) % 2 == 0) {
// distance from even->even or odd->odd column
// important to know since evens and odds are offset | // Path: core/src/com/galvarez/ttw/utils/FloatPair.java
// public final class FloatPair {
//
// public final float x, y;
//
// public FloatPair(float x, float y) {
// this.x = x;
// this.y = y;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FloatPair)
// return equals((FloatPair) obj);
// return false;
// }
//
// public boolean equals(FloatPair p) {
// return x == p.x && y == p.y;
// }
//
// @Override
// public String toString() {
// return "(" + x + "," + y + ")";
// }
// }
//
// Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
// Path: core/src/com/galvarez/ttw/model/map/MapTools.java
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector3;
import com.galvarez.ttw.utils.FloatPair;
import com.galvarez.ttw.utils.MyMath;
TOP_RIGHT {
@Override
public MapPosition getNeighbor(int x, int y) {
return new MapPosition(x + 1, y + (x % 2));
}
};
abstract public MapPosition getNeighbor(int x, int y);
public final MapPosition getNeighbor(MapPosition pos) {
return getNeighbor(pos.x, pos.y);
}
}
public static int distance(MapPosition p0, MapPosition p1) {
int x0 = p0.x;
int y0 = p0.y;
int x1 = p1.x;
int y1 = p1.y;
int dx = Math.abs(x1 - x0);
int dy = Math.abs(y1 - y0);
// The distance can be tricky, because of how the columns are shifted.
// Different cases must be considered, because the dx and dy above
// are not sufficient to determine distance.
if ((dx) % 2 == 0) {
// distance from even->even or odd->odd column
// important to know since evens and odds are offset | return MyMath.max(dx, dx / 2 + dy); |
guillaume-alvarez/ShapeOfThingsThatWere | core/src/com/galvarez/ttw/model/map/MapTools.java | // Path: core/src/com/galvarez/ttw/utils/FloatPair.java
// public final class FloatPair {
//
// public final float x, y;
//
// public FloatPair(float x, float y) {
// this.x = x;
// this.y = y;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FloatPair)
// return equals((FloatPair) obj);
// return false;
// }
//
// public boolean equals(FloatPair p) {
// return x == p.x && y == p.y;
// }
//
// @Override
// public String toString() {
// return "(" + x + "," + y + ")";
// }
// }
//
// Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
| import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector3;
import com.galvarez.ttw.utils.FloatPair;
import com.galvarez.ttw.utils.MyMath; | if ((dx) % 2 == 0) {
// distance from even->even or odd->odd column
// important to know since evens and odds are offset
return MyMath.max(dx, dx / 2 + dy);
}
// Otherwise the distance must be even->odd
else if (((x0 % 2 == 0) && (y0 > y1)) || ((x1 % 2 == 0) && (y1 > y0))) {
// even on top
return MyMath.max(dx, (dx - 1) / 2 + dy);
}
// otherwise odd must be on top
return MyMath.max(dx, (dx + 1) / 2 + dy);
}
public static MapPosition window2world(float x, float y, OrthographicCamera camera) {
Vector3 pos = new Vector3(x, y, 0);
camera.unproject(pos);
int posx = (int) ((pos.x - 6f) / col_multiple);
int posy = (int) ((pos.y - (float) row_multiple * (posx % 2) / 2) / row_multiple);
return new MapPosition(posx, posy);
}
public static MapPosition libgdx2world(float x, float y) {
Vector3 pos = new Vector3(x, y, 0);
int posx = (int) ((pos.x - 6f) / col_multiple);
int posy = (int) ((pos.y - (float) row_multiple * (posx % 2) / 2) / row_multiple);
return new MapPosition(posx, posy);
}
| // Path: core/src/com/galvarez/ttw/utils/FloatPair.java
// public final class FloatPair {
//
// public final float x, y;
//
// public FloatPair(float x, float y) {
// this.x = x;
// this.y = y;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof FloatPair)
// return equals((FloatPair) obj);
// return false;
// }
//
// public boolean equals(FloatPair p) {
// return x == p.x && y == p.y;
// }
//
// @Override
// public String toString() {
// return "(" + x + "," + y + ")";
// }
// }
//
// Path: core/src/com/galvarez/ttw/utils/MyMath.java
// public class MyMath {
// public static int min(int a, int b) {
// if (a < b) return a;
// return b;
// }
//
// public static int min(int a, int b, int c) {
// if (min(a,b) < c) return min(a,b);
// return c;
// }
//
// public static int max(int a, int b) {
// if (a > b) return a;
// return b;
// }
//
// public static int pow(int a, int b) {
// if (b > 1) return a*pow(a,b-1);
// else return a;
// }
// }
// Path: core/src/com/galvarez/ttw/model/map/MapTools.java
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector3;
import com.galvarez.ttw.utils.FloatPair;
import com.galvarez.ttw.utils.MyMath;
if ((dx) % 2 == 0) {
// distance from even->even or odd->odd column
// important to know since evens and odds are offset
return MyMath.max(dx, dx / 2 + dy);
}
// Otherwise the distance must be even->odd
else if (((x0 % 2 == 0) && (y0 > y1)) || ((x1 % 2 == 0) && (y1 > y0))) {
// even on top
return MyMath.max(dx, (dx - 1) / 2 + dy);
}
// otherwise odd must be on top
return MyMath.max(dx, (dx + 1) / 2 + dy);
}
public static MapPosition window2world(float x, float y, OrthographicCamera camera) {
Vector3 pos = new Vector3(x, y, 0);
camera.unproject(pos);
int posx = (int) ((pos.x - 6f) / col_multiple);
int posy = (int) ((pos.y - (float) row_multiple * (posx % 2) / 2) / row_multiple);
return new MapPosition(posx, posy);
}
public static MapPosition libgdx2world(float x, float y) {
Vector3 pos = new Vector3(x, y, 0);
int posx = (int) ((pos.x - 6f) / col_multiple);
int posy = (int) ((pos.y - (float) row_multiple * (posx % 2) / 2) / row_multiple);
return new MapPosition(posx, posy);
}
| public static FloatPair world2window(float x, float y) { |
mojohaus/appassembler | appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/merge/DaemonMerger.java | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
| import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Daemon; | package org.codehaus.mojo.appassembler.daemon.merge;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
*/
public interface DaemonMerger
{
/**
* The role of the merger.
*/
String ROLE = DaemonMerger.class.getName();
/**
* Merge two Daemons into a single one.
*
* @param dominant {@link Daemon}
* @param recessive {@link Daemon}
* @return The merged Daemon instance.
* @throws DaemonGeneratorException in case of an error.
*/
Daemon mergeDaemons( Daemon dominant, Daemon recessive ) | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
// Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/merge/DaemonMerger.java
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Daemon;
package org.codehaus.mojo.appassembler.daemon.merge;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
*/
public interface DaemonMerger
{
/**
* The role of the merger.
*/
String ROLE = DaemonMerger.class.getName();
/**
* Merge two Daemons into a single one.
*
* @param dominant {@link Daemon}
* @param recessive {@link Daemon}
* @return The merged Daemon instance.
* @throws DaemonGeneratorException in case of an error.
*/
Daemon mergeDaemons( Daemon dominant, Daemon recessive ) | throws DaemonGeneratorException; |
mojohaus/appassembler | appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/script/DefaultScriptGenerator.java | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Daemon;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.util.ArchiveEntryUtils;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.InterpolationFilterReader; | package org.codehaus.mojo.appassembler.daemon.script;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
* @plexus.component
*/
public class DefaultScriptGenerator
extends AbstractLogEnabled
implements ScriptGenerator
{
private static final String DEFAULT_LICENSE_HEADER = "default-license-header.txt";
private boolean isDefaultLicenseHeaderRequested( Daemon daemon )
{
if ( daemon.getLicenseHeaderFile() == null )
{
return true;
}
if ( daemon.getLicenseHeaderFile().trim().length() > 0 )
{
return false;
}
return false;
}
private String getLicenseHeader( Platform platform, Daemon daemon ) | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
// Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/script/DefaultScriptGenerator.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Daemon;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.util.ArchiveEntryUtils;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.InterpolationFilterReader;
package org.codehaus.mojo.appassembler.daemon.script;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
* @plexus.component
*/
public class DefaultScriptGenerator
extends AbstractLogEnabled
implements ScriptGenerator
{
private static final String DEFAULT_LICENSE_HEADER = "default-license-header.txt";
private boolean isDefaultLicenseHeaderRequested( Daemon daemon )
{
if ( daemon.getLicenseHeaderFile() == null )
{
return true;
}
if ( daemon.getLicenseHeaderFile().trim().length() > 0 )
{
return false;
}
return false;
}
private String getLicenseHeader( Platform platform, Daemon daemon ) | throws DaemonGeneratorException |
mojohaus/appassembler | appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DefaultDaemonGeneratorService.java | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/merge/DaemonMerger.java
// public interface DaemonMerger
// {
// /**
// * The role of the merger.
// */
// String ROLE = DaemonMerger.class.getName();
//
// /**
// * Merge two Daemons into a single one.
// *
// * @param dominant {@link Daemon}
// * @param recessive {@link Daemon}
// * @return The merged Daemon instance.
// * @throws DaemonGeneratorException in case of an error.
// */
// Daemon mergeDaemons( Daemon dominant, Daemon recessive )
// throws DaemonGeneratorException;
// }
| import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.project.MavenProject;
import org.codehaus.mojo.appassembler.daemon.merge.DaemonMerger;
import org.codehaus.mojo.appassembler.model.Daemon;
import org.codehaus.mojo.appassembler.model.io.stax.AppassemblerModelStaxReader;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import javax.xml.stream.XMLStreamException; | package org.codehaus.mojo.appassembler.daemon;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
* @plexus.component
*/
public class DefaultDaemonGeneratorService
extends AbstractLogEnabled
implements DaemonGeneratorService
{
/**
* @plexus.requirement role="org.codehaus.mojo.appassembler.daemon.DaemonGenerator"
*/
private Map generators;
/**
* @plexus.requirement
*/ | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/merge/DaemonMerger.java
// public interface DaemonMerger
// {
// /**
// * The role of the merger.
// */
// String ROLE = DaemonMerger.class.getName();
//
// /**
// * Merge two Daemons into a single one.
// *
// * @param dominant {@link Daemon}
// * @param recessive {@link Daemon}
// * @return The merged Daemon instance.
// * @throws DaemonGeneratorException in case of an error.
// */
// Daemon mergeDaemons( Daemon dominant, Daemon recessive )
// throws DaemonGeneratorException;
// }
// Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DefaultDaemonGeneratorService.java
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.project.MavenProject;
import org.codehaus.mojo.appassembler.daemon.merge.DaemonMerger;
import org.codehaus.mojo.appassembler.model.Daemon;
import org.codehaus.mojo.appassembler.model.io.stax.AppassemblerModelStaxReader;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import javax.xml.stream.XMLStreamException;
package org.codehaus.mojo.appassembler.daemon;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygvis@inamo.no">Trygve Laugstøl</a>
* @plexus.component
*/
public class DefaultDaemonGeneratorService
extends AbstractLogEnabled
implements DaemonGeneratorService
{
/**
* @plexus.requirement role="org.codehaus.mojo.appassembler.daemon.DaemonGenerator"
*/
private Map generators;
/**
* @plexus.requirement
*/ | private DaemonMerger daemonMerger; |
mojohaus/appassembler | appassembler-maven-plugin/src/test/java/org/codehaus/mojo/appassembler/daemon/jsw/JavaServiceWrapperDaemonGeneratorTest.java | // Path: appassembler-maven-plugin/src/test/java/org/codehaus/mojo/appassembler/daemon/AbstractDaemonGeneratorTest.java
// public abstract class AbstractDaemonGeneratorTest
// extends PlexusTestCase
// {
// private static String appassemblerVersion;
//
// public void runTest( String generatorId, String pom, String descriptor, String outputPath )
// throws Exception
// {
// File outputDir = getTestFile( outputPath );
//
// DaemonGenerator generator = (DaemonGenerator) lookup( DaemonGenerator.ROLE, generatorId );
//
// // -----------------------------------------------------------------------
// // Build the MavenProject instance
// // -----------------------------------------------------------------------
//
// MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE );
//
// MavenSettingsBuilder settingsBuilder = (MavenSettingsBuilder) lookup( MavenSettingsBuilder.ROLE );
// Settings settings = settingsBuilder.buildSettings();
//
// ArtifactRepositoryFactory artifactRepositoryFactory =
// (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.ROLE );
//
// String localRepoUrl = new File( settings.getLocalRepository() ).toURL().toExternalForm();
//
// ArtifactRepository localRepository =
// artifactRepositoryFactory.createDeploymentArtifactRepository( "local", localRepoUrl,
// new DefaultRepositoryLayout(), false );
//
// ProfileManager profileManager = new DefaultProfileManager( getContainer() );
//
// File tempPom = createFilteredFile( pom );
//
// MavenProject project = projectBuilder.buildWithDependencies( tempPom, localRepository, profileManager );
//
// // -----------------------------------------------------------------------
// // Clean the output directory
// // -----------------------------------------------------------------------
//
// FileUtils.deleteDirectory( outputDir );
// FileUtils.forceMkdir( outputDir );
//
// // -----------------------------------------------------------------------
// //
// // -----------------------------------------------------------------------
//
// DaemonGeneratorService daemonGeneratorService = (DaemonGeneratorService) lookup( DaemonGeneratorService.ROLE );
//
// Daemon model = daemonGeneratorService.loadModel( getTestFile( descriptor ) );
//
// generator.generate( new DaemonGenerationRequest( model, project, localRepository, outputDir, "bin" ) );
// }
//
// protected File createFilteredFile( String file )
// throws IOException, FileNotFoundException, DaemonGeneratorException, XmlPullParserException
// {
// String version = getAppAssemblerBooterVersion();
// Properties context = new Properties();
// context.setProperty( "appassembler.version", version );
//
// File tempPom = File.createTempFile( "appassembler", "tmp" );
// tempPom.deleteOnExit();
//
// InterpolationFilterReader reader =
// new InterpolationFilterReader( new FileReader( getTestFile( file ) ), context, "@", "@" );
// FileWriter out = null;
//
// try
// {
// out = new FileWriter( tempPom );
//
// IOUtil.copy( reader, out );
// }
// catch ( IOException e )
// {
// throw new DaemonGeneratorException( "Error writing output file: " + tempPom.getAbsolutePath(), e );
// }
// finally
// {
// IOUtil.close( reader );
// IOUtil.close( out );
// }
// return tempPom;
// }
//
// private static String getAppAssemblerBooterVersion()
// throws IOException, XmlPullParserException
// {
// if ( appassemblerVersion == null )
// {
// MavenXpp3Reader reader = new MavenXpp3Reader();
// FileReader fileReader = new FileReader( getTestFile( "pom.xml" ) );
// try
// {
// appassemblerVersion = reader.read( fileReader ).getParent().getVersion();
// }
// finally
// {
// IOUtil.close( fileReader );
// }
// }
// return appassemblerVersion;
// }
//
// protected static String normalizeLineTerminators( String input )
// {
// return ( input != null ) ? input.replaceAll( "(\r\n)|(\r)", "\n" ) : null;
// }
// }
//
// Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
| import java.io.File;
import java.io.IOException;
import org.codehaus.mojo.appassembler.daemon.AbstractDaemonGeneratorTest;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils; | }
public void testGenerationWithGoodExternalDeltaPack()
throws Exception
{
runTest( "jsw", "src/test/resources/project-10/pom.xml", "src/test/resources/project-10/descriptor.xml",
"target/output-10-jsw" );
File jswDir = getTestFile( "target/output-10-jsw/app" );
// just enough to prove we see the external files
assertFileExists( jswDir, "lib/wrapper.jar" );
assertFileExists( jswDir, "lib/libwrapper-aix-ppc-32.a" );
assertFileExists( jswDir, "lib/libwrapper-aix-ppc-64.a" );
// just enough to prove we see the external files
assertFileExists( jswDir, "bin/wrapper-aix-ppc-32" );
assertFileExists( jswDir, "bin/wrapper-aix-ppc-64" );
}
public void testGenerationWithBadExternalDeltaPack()
throws Exception
{
try
{
runTest( "jsw", "src/test/resources/project-10/pom.xml", "src/test/resources/project-11/descriptor.xml",
"target/output-11-jsw" );
fail( "Invalid external delta pack passed thru!!." );
} | // Path: appassembler-maven-plugin/src/test/java/org/codehaus/mojo/appassembler/daemon/AbstractDaemonGeneratorTest.java
// public abstract class AbstractDaemonGeneratorTest
// extends PlexusTestCase
// {
// private static String appassemblerVersion;
//
// public void runTest( String generatorId, String pom, String descriptor, String outputPath )
// throws Exception
// {
// File outputDir = getTestFile( outputPath );
//
// DaemonGenerator generator = (DaemonGenerator) lookup( DaemonGenerator.ROLE, generatorId );
//
// // -----------------------------------------------------------------------
// // Build the MavenProject instance
// // -----------------------------------------------------------------------
//
// MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE );
//
// MavenSettingsBuilder settingsBuilder = (MavenSettingsBuilder) lookup( MavenSettingsBuilder.ROLE );
// Settings settings = settingsBuilder.buildSettings();
//
// ArtifactRepositoryFactory artifactRepositoryFactory =
// (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.ROLE );
//
// String localRepoUrl = new File( settings.getLocalRepository() ).toURL().toExternalForm();
//
// ArtifactRepository localRepository =
// artifactRepositoryFactory.createDeploymentArtifactRepository( "local", localRepoUrl,
// new DefaultRepositoryLayout(), false );
//
// ProfileManager profileManager = new DefaultProfileManager( getContainer() );
//
// File tempPom = createFilteredFile( pom );
//
// MavenProject project = projectBuilder.buildWithDependencies( tempPom, localRepository, profileManager );
//
// // -----------------------------------------------------------------------
// // Clean the output directory
// // -----------------------------------------------------------------------
//
// FileUtils.deleteDirectory( outputDir );
// FileUtils.forceMkdir( outputDir );
//
// // -----------------------------------------------------------------------
// //
// // -----------------------------------------------------------------------
//
// DaemonGeneratorService daemonGeneratorService = (DaemonGeneratorService) lookup( DaemonGeneratorService.ROLE );
//
// Daemon model = daemonGeneratorService.loadModel( getTestFile( descriptor ) );
//
// generator.generate( new DaemonGenerationRequest( model, project, localRepository, outputDir, "bin" ) );
// }
//
// protected File createFilteredFile( String file )
// throws IOException, FileNotFoundException, DaemonGeneratorException, XmlPullParserException
// {
// String version = getAppAssemblerBooterVersion();
// Properties context = new Properties();
// context.setProperty( "appassembler.version", version );
//
// File tempPom = File.createTempFile( "appassembler", "tmp" );
// tempPom.deleteOnExit();
//
// InterpolationFilterReader reader =
// new InterpolationFilterReader( new FileReader( getTestFile( file ) ), context, "@", "@" );
// FileWriter out = null;
//
// try
// {
// out = new FileWriter( tempPom );
//
// IOUtil.copy( reader, out );
// }
// catch ( IOException e )
// {
// throw new DaemonGeneratorException( "Error writing output file: " + tempPom.getAbsolutePath(), e );
// }
// finally
// {
// IOUtil.close( reader );
// IOUtil.close( out );
// }
// return tempPom;
// }
//
// private static String getAppAssemblerBooterVersion()
// throws IOException, XmlPullParserException
// {
// if ( appassemblerVersion == null )
// {
// MavenXpp3Reader reader = new MavenXpp3Reader();
// FileReader fileReader = new FileReader( getTestFile( "pom.xml" ) );
// try
// {
// appassemblerVersion = reader.read( fileReader ).getParent().getVersion();
// }
// finally
// {
// IOUtil.close( fileReader );
// }
// }
// return appassemblerVersion;
// }
//
// protected static String normalizeLineTerminators( String input )
// {
// return ( input != null ) ? input.replaceAll( "(\r\n)|(\r)", "\n" ) : null;
// }
// }
//
// Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
// Path: appassembler-maven-plugin/src/test/java/org/codehaus/mojo/appassembler/daemon/jsw/JavaServiceWrapperDaemonGeneratorTest.java
import java.io.File;
import java.io.IOException;
import org.codehaus.mojo.appassembler.daemon.AbstractDaemonGeneratorTest;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
}
public void testGenerationWithGoodExternalDeltaPack()
throws Exception
{
runTest( "jsw", "src/test/resources/project-10/pom.xml", "src/test/resources/project-10/descriptor.xml",
"target/output-10-jsw" );
File jswDir = getTestFile( "target/output-10-jsw/app" );
// just enough to prove we see the external files
assertFileExists( jswDir, "lib/wrapper.jar" );
assertFileExists( jswDir, "lib/libwrapper-aix-ppc-32.a" );
assertFileExists( jswDir, "lib/libwrapper-aix-ppc-64.a" );
// just enough to prove we see the external files
assertFileExists( jswDir, "bin/wrapper-aix-ppc-32" );
assertFileExists( jswDir, "bin/wrapper-aix-ppc-64" );
}
public void testGenerationWithBadExternalDeltaPack()
throws Exception
{
try
{
runTest( "jsw", "src/test/resources/project-10/pom.xml", "src/test/resources/project-11/descriptor.xml",
"target/output-11-jsw" );
fail( "Invalid external delta pack passed thru!!." );
} | catch ( DaemonGeneratorException e ) |
mojohaus/appassembler | appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/merge/DefaultDaemonMerger.java | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
| import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.StringUtils;
import java.util.List;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Classpath;
import org.codehaus.mojo.appassembler.model.Daemon;
import org.codehaus.mojo.appassembler.model.JvmSettings; | package org.codehaus.mojo.appassembler.daemon.merge;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
* @plexus.component
*/
public class DefaultDaemonMerger
extends AbstractLogEnabled
implements DaemonMerger
{
// -----------------------------------------------------------------------
// DaemonMerger Implementation
// -----------------------------------------------------------------------
public Daemon mergeDaemons( Daemon dominant, Daemon recessive ) | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
// Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/merge/DefaultDaemonMerger.java
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.StringUtils;
import java.util.List;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Classpath;
import org.codehaus.mojo.appassembler.model.Daemon;
import org.codehaus.mojo.appassembler.model.JvmSettings;
package org.codehaus.mojo.appassembler.daemon.merge;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
* @plexus.component
*/
public class DefaultDaemonMerger
extends AbstractLogEnabled
implements DaemonMerger
{
// -----------------------------------------------------------------------
// DaemonMerger Implementation
// -----------------------------------------------------------------------
public Daemon mergeDaemons( Daemon dominant, Daemon recessive ) | throws DaemonGeneratorException |
mojohaus/appassembler | appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/script/Platform.java | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
| import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.ClasspathElement;
import org.codehaus.mojo.appassembler.model.Daemon;
import org.codehaus.mojo.appassembler.model.Dependency;
import org.codehaus.mojo.appassembler.model.Directory;
import org.codehaus.mojo.appassembler.model.JvmSettings;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.InterpolationFilterReader;
import org.codehaus.plexus.util.StringUtils; | package org.codehaus.mojo.appassembler.daemon.script;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
*/
public class Platform
{
/**
* Unix as Platform name.
*/
public static final String UNIX_NAME = "unix";
/**
* Windows Platform name.
*/
public static final String WINDOWS_NAME = "windows";
private static final Map<String, Platform> ALL_PLATFORMS;
private static final String DEFAULT_UNIX_BIN_FILE_EXTENSION = "";
private static final String DEFAULT_WINDOWS_BIN_FILE_EXTENSION = ".bat";
private String binFileExtension;
private String name;
private boolean isWindows;
// -----------------------------------------------------------------------
// Static
// -----------------------------------------------------------------------
static
{
ALL_PLATFORMS = new HashMap<String, Platform>();
addPlatform( new Platform( UNIX_NAME, false, DEFAULT_UNIX_BIN_FILE_EXTENSION ) );
addPlatform( new Platform( WINDOWS_NAME, true, DEFAULT_WINDOWS_BIN_FILE_EXTENSION ) );
}
private static Platform addPlatform( Platform platform )
{
ALL_PLATFORMS.put( platform.name, platform );
return platform;
}
/**
* Get an instance of the named platform.
*
* @param platformName The name of the wished platform.
* @return Instance of the platform.
* @throws DaemonGeneratorException in case of an wrong platformname.
*/
public static Platform getInstance( String platformName ) | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
// Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/script/Platform.java
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.ClasspathElement;
import org.codehaus.mojo.appassembler.model.Daemon;
import org.codehaus.mojo.appassembler.model.Dependency;
import org.codehaus.mojo.appassembler.model.Directory;
import org.codehaus.mojo.appassembler.model.JvmSettings;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.InterpolationFilterReader;
import org.codehaus.plexus.util.StringUtils;
package org.codehaus.mojo.appassembler.daemon.script;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
*/
public class Platform
{
/**
* Unix as Platform name.
*/
public static final String UNIX_NAME = "unix";
/**
* Windows Platform name.
*/
public static final String WINDOWS_NAME = "windows";
private static final Map<String, Platform> ALL_PLATFORMS;
private static final String DEFAULT_UNIX_BIN_FILE_EXTENSION = "";
private static final String DEFAULT_WINDOWS_BIN_FILE_EXTENSION = ".bat";
private String binFileExtension;
private String name;
private boolean isWindows;
// -----------------------------------------------------------------------
// Static
// -----------------------------------------------------------------------
static
{
ALL_PLATFORMS = new HashMap<String, Platform>();
addPlatform( new Platform( UNIX_NAME, false, DEFAULT_UNIX_BIN_FILE_EXTENSION ) );
addPlatform( new Platform( WINDOWS_NAME, true, DEFAULT_WINDOWS_BIN_FILE_EXTENSION ) );
}
private static Platform addPlatform( Platform platform )
{
ALL_PLATFORMS.put( platform.name, platform );
return platform;
}
/**
* Get an instance of the named platform.
*
* @param platformName The name of the wished platform.
* @return Instance of the platform.
* @throws DaemonGeneratorException in case of an wrong platformname.
*/
public static Platform getInstance( String platformName ) | throws DaemonGeneratorException |
mojohaus/appassembler | appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/util/DependencyFactory.java | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
| import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Dependency;
import org.codehaus.plexus.interpolation.InterpolationException;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.mapping.MappingUtils; | * Used by AssembleMojo and JavaServiceWrapperDaemonGenerator.
* @param artifact {@link Artifact}
* @param layout {@link ArtifactRepositoryLayout}
* @param useTimestampInSnapshotFileName timestamp or not.
* @param outputFileNameMapping The name mapping.
* @return the dependency.
*/
public static Dependency create(Artifact artifact, ArtifactRepositoryLayout layout,
boolean useTimestampInSnapshotFileName, String outputFileNameMapping)
{
Dependency dependency = create( artifact, layout, outputFileNameMapping );
if ( artifact.isSnapshot() && !useTimestampInSnapshotFileName )
{
dependency.setRelativePath( ArtifactUtils.pathBaseVersionOf( layout, artifact ) );
}
return dependency;
}
/**
* Used by AbstractBooterDaemonGenerator.
* @param project {@link MavenProject}
* @param id The id.
* @param layout {@link ArtifactRepositoryLayout}
* @param outputFileNameMapping The name mapping.
* @return the dependency.
*/
public static Dependency create( MavenProject project, String id, ArtifactRepositoryLayout layout,
String outputFileNameMapping ) | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
// Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/util/DependencyFactory.java
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Dependency;
import org.codehaus.plexus.interpolation.InterpolationException;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.mapping.MappingUtils;
* Used by AssembleMojo and JavaServiceWrapperDaemonGenerator.
* @param artifact {@link Artifact}
* @param layout {@link ArtifactRepositoryLayout}
* @param useTimestampInSnapshotFileName timestamp or not.
* @param outputFileNameMapping The name mapping.
* @return the dependency.
*/
public static Dependency create(Artifact artifact, ArtifactRepositoryLayout layout,
boolean useTimestampInSnapshotFileName, String outputFileNameMapping)
{
Dependency dependency = create( artifact, layout, outputFileNameMapping );
if ( artifact.isSnapshot() && !useTimestampInSnapshotFileName )
{
dependency.setRelativePath( ArtifactUtils.pathBaseVersionOf( layout, artifact ) );
}
return dependency;
}
/**
* Used by AbstractBooterDaemonGenerator.
* @param project {@link MavenProject}
* @param id The id.
* @param layout {@link ArtifactRepositoryLayout}
* @param outputFileNameMapping The name mapping.
* @return the dependency.
*/
public static Dependency create( MavenProject project, String id, ArtifactRepositoryLayout layout,
String outputFileNameMapping ) | throws DaemonGeneratorException |
mojohaus/appassembler | appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/script/ScriptGenerator.java | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
| import java.io.File;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Daemon; | package org.codehaus.mojo.appassembler.daemon.script;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
*/
public interface ScriptGenerator
{
/**
* Define the role.
*/
String ROLE = ScriptGenerator.class.getName();
/**
* Generate the binary script based on platform, daemon into the given outputDirectory and the binFolder.
*
* @param platform The platform.
* @param daemon The Daemon.
* @param outputDirectory The output folder where the script will be generated into.
* @param binFolder The bin folder which will be appended to the outputDirectory.
* @throws DaemonGeneratorException in case of an error.
*/
void createBinScript( String platform, Daemon daemon, File outputDirectory, String binFolder ) | // Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/DaemonGeneratorException.java
// public class DaemonGeneratorException
// extends Exception
// {
// /**
// *
// */
// private static final long serialVersionUID = 6989317744526360832L;
//
// /**
// * Exception with message.
// *
// * @param message The message for the execption.
// */
// public DaemonGeneratorException( String message )
// {
// super( message );
// }
//
// /**
// * The exception with an appropriate message and the cause of the failure.
// *
// * @param message The message to show.
// * @param cause The root cause.
// */
// public DaemonGeneratorException( String message, Throwable cause )
// {
// super( message, cause );
// }
// }
// Path: appassembler-maven-plugin/src/main/java/org/codehaus/mojo/appassembler/daemon/script/ScriptGenerator.java
import java.io.File;
import org.codehaus.mojo.appassembler.daemon.DaemonGeneratorException;
import org.codehaus.mojo.appassembler.model.Daemon;
package org.codehaus.mojo.appassembler.daemon.script;
/*
* The MIT License
*
* Copyright (c) 2006-2012, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author <a href="mailto:trygve.laugstol@objectware.no">Trygve Laugstøl</a>
*/
public interface ScriptGenerator
{
/**
* Define the role.
*/
String ROLE = ScriptGenerator.class.getName();
/**
* Generate the binary script based on platform, daemon into the given outputDirectory and the binFolder.
*
* @param platform The platform.
* @param daemon The Daemon.
* @param outputDirectory The output folder where the script will be generated into.
* @param binFolder The bin folder which will be appended to the outputDirectory.
* @throws DaemonGeneratorException in case of an error.
*/
void createBinScript( String platform, Daemon daemon, File outputDirectory, String binFolder ) | throws DaemonGeneratorException; |
mokszr/ultimate-geojson | ugeojson-builder/src/main/java/org/ugeojson/builder/geometry/MultiPolygonBuilder.java | // Path: ugeojson-builder/src/main/java/org/ugeojson/builder/common/BuilderConstants.java
// public interface BuilderConstants {
//
// public static final String OPEN_BRACKET = "[";
// public static final String CLOSE_BRACKET = "]";
// public static final String OPEN_CURLY_BRACE = "{";
// public static final String CLOSE_CURLY_BRACE = "}";
//
// public static final String COMMA_SPACE = ", ";
// public static final String COMMA = ",";
// public static final String SPACE = " ";
// public static final String COMMA_NEWLINE = ",\n";
// public static final String NEWLINE = "\n";
// public static final String DOUBLE_QUOTE = "\"";
// public static final String NULL_VALUE = "null";
// public static final String TAB_SPACE = " ";
// public static final String EMPTY = "";
//
// public static final String TYPE_SPACE = "\"type\": ";
// public static final String COORDINATES_SPACE = "\"coordinates\": ";
// public static final String GEOMETRIES_SPACE = "\"geometries\": ";
// public static final String GEOMETRY_SPACE = "\"geometry\": ";
// public static final String PROPERTIES_SPACE = "\"properties\": ";
// public static final String ID_SPACE = "\"id\": ";
// public static final String FEATURES_SPACE = "\"features\": ";
// public static final String BBOX_SPACE = "\"bbox\": ";
// }
//
// Path: ugeojson-model/src/main/java/org/ugeojson/model/GeoJSONObjectTypeEnum.java
// public enum GeoJSONObjectTypeEnum {
//
// Point(PointDto.class), MultiPoint(MultiPointDto.class), LineString(LineStringDto.class), MultiLineString(
// MultiLineStringDto.class), Polygon(PolygonDto.class), MultiPolygon(
// MultiPolygonDto.class), GeometryCollection(GeometryCollectionDto.class), Feature(
// FeatureDto.class), FeatureCollection(FeatureCollectionDto.class);
//
// private final Class dtoClass;
//
// private GeoJSONObjectTypeEnum(Class dtoClass) {
// this.dtoClass = dtoClass;
// }
//
// public Class getDtoClass() {
// return dtoClass;
// }
// }
//
// Path: ugeojson-model/src/main/java/org/ugeojson/model/geometry/LineStringDto.java
// public class LineStringDto extends GeometryDto {
//
// private static final long serialVersionUID = 1L;
//
// private List<PositionDto> positions;
//
// public LineStringDto(){
// }
//
// public LineStringDto(List<PositionDto> positions){
// this.positions = new ArrayList<>();
// for (PositionDto positionDto : positions) {
// this.positions.add(new PositionDto(positionDto));
// }
// }
//
// public List<PositionDto> getPositions() {
// return positions;
// }
//
// public void setPositions(List<PositionDto> positions) {
// this.positions = positions;
// }
//
// @Override
// public GeoJSONObjectTypeEnum getGeoJSONObjectType() {
// return GeoJSONObjectTypeEnum.LineString;
// }
// }
//
// Path: ugeojson-model/src/main/java/org/ugeojson/model/geometry/MultiPolygonDto.java
// public class MultiPolygonDto extends GeometryDto {
//
// private static final long serialVersionUID = 1L;
//
// private List<PolygonDto> polygons;
//
// public List<PolygonDto> getPolygons() {
// return polygons;
// }
//
// public void setPolygons(List<PolygonDto> polygons) {
// this.polygons = polygons;
// }
//
// @Override
// public GeoJSONObjectTypeEnum getGeoJSONObjectType() {
// return GeoJSONObjectTypeEnum.MultiPolygon;
// }
// }
//
// Path: ugeojson-model/src/main/java/org/ugeojson/model/geometry/PolygonDto.java
// public class PolygonDto extends GeometryDto {
//
// private static final long serialVersionUID = 1L;
//
// private List<LineStringDto> linearRings;
//
// @Override
// public GeoJSONObjectTypeEnum getGeoJSONObjectType() {
// return GeoJSONObjectTypeEnum.Polygon;
// }
//
// public List<LineStringDto> getLinearRings() {
// return linearRings;
// }
//
// public void setLinearRings(List<LineStringDto> linearRings) {
// this.linearRings = linearRings;
// }
//
// }
| import java.util.List;
import org.ugeojson.builder.common.BuilderConstants;
import org.ugeojson.model.GeoJSONObjectTypeEnum;
import org.ugeojson.model.geometry.LineStringDto;
import org.ugeojson.model.geometry.MultiPolygonDto;
import org.ugeojson.model.geometry.PolygonDto; | package org.ugeojson.builder.geometry;
/**
* @author moksuzer
*
*/
public class MultiPolygonBuilder extends GeometryBuilder<MultiPolygonDto> {
private static final MultiPolygonBuilder INSTANCE = new MultiPolygonBuilder();
public static MultiPolygonBuilder getInstance() {
return INSTANCE;
}
private MultiPolygonBuilder() {
}
/*
* (non-Javadoc)
*
* @see
* org.ugeojson.builder.geometry.GeometryBuilder#toGeometryGeoJSON(com
* .erumi.ugeojson.model.geometry.GeometryDto)
*/
@Override
public String toGeoJSON(MultiPolygonDto multiPolygon) {
if (multiPolygon == null || multiPolygon.getPolygons() == null || multiPolygon.getPolygons().isEmpty()) { | // Path: ugeojson-builder/src/main/java/org/ugeojson/builder/common/BuilderConstants.java
// public interface BuilderConstants {
//
// public static final String OPEN_BRACKET = "[";
// public static final String CLOSE_BRACKET = "]";
// public static final String OPEN_CURLY_BRACE = "{";
// public static final String CLOSE_CURLY_BRACE = "}";
//
// public static final String COMMA_SPACE = ", ";
// public static final String COMMA = ",";
// public static final String SPACE = " ";
// public static final String COMMA_NEWLINE = ",\n";
// public static final String NEWLINE = "\n";
// public static final String DOUBLE_QUOTE = "\"";
// public static final String NULL_VALUE = "null";
// public static final String TAB_SPACE = " ";
// public static final String EMPTY = "";
//
// public static final String TYPE_SPACE = "\"type\": ";
// public static final String COORDINATES_SPACE = "\"coordinates\": ";
// public static final String GEOMETRIES_SPACE = "\"geometries\": ";
// public static final String GEOMETRY_SPACE = "\"geometry\": ";
// public static final String PROPERTIES_SPACE = "\"properties\": ";
// public static final String ID_SPACE = "\"id\": ";
// public static final String FEATURES_SPACE = "\"features\": ";
// public static final String BBOX_SPACE = "\"bbox\": ";
// }
//
// Path: ugeojson-model/src/main/java/org/ugeojson/model/GeoJSONObjectTypeEnum.java
// public enum GeoJSONObjectTypeEnum {
//
// Point(PointDto.class), MultiPoint(MultiPointDto.class), LineString(LineStringDto.class), MultiLineString(
// MultiLineStringDto.class), Polygon(PolygonDto.class), MultiPolygon(
// MultiPolygonDto.class), GeometryCollection(GeometryCollectionDto.class), Feature(
// FeatureDto.class), FeatureCollection(FeatureCollectionDto.class);
//
// private final Class dtoClass;
//
// private GeoJSONObjectTypeEnum(Class dtoClass) {
// this.dtoClass = dtoClass;
// }
//
// public Class getDtoClass() {
// return dtoClass;
// }
// }
//
// Path: ugeojson-model/src/main/java/org/ugeojson/model/geometry/LineStringDto.java
// public class LineStringDto extends GeometryDto {
//
// private static final long serialVersionUID = 1L;
//
// private List<PositionDto> positions;
//
// public LineStringDto(){
// }
//
// public LineStringDto(List<PositionDto> positions){
// this.positions = new ArrayList<>();
// for (PositionDto positionDto : positions) {
// this.positions.add(new PositionDto(positionDto));
// }
// }
//
// public List<PositionDto> getPositions() {
// return positions;
// }
//
// public void setPositions(List<PositionDto> positions) {
// this.positions = positions;
// }
//
// @Override
// public GeoJSONObjectTypeEnum getGeoJSONObjectType() {
// return GeoJSONObjectTypeEnum.LineString;
// }
// }
//
// Path: ugeojson-model/src/main/java/org/ugeojson/model/geometry/MultiPolygonDto.java
// public class MultiPolygonDto extends GeometryDto {
//
// private static final long serialVersionUID = 1L;
//
// private List<PolygonDto> polygons;
//
// public List<PolygonDto> getPolygons() {
// return polygons;
// }
//
// public void setPolygons(List<PolygonDto> polygons) {
// this.polygons = polygons;
// }
//
// @Override
// public GeoJSONObjectTypeEnum getGeoJSONObjectType() {
// return GeoJSONObjectTypeEnum.MultiPolygon;
// }
// }
//
// Path: ugeojson-model/src/main/java/org/ugeojson/model/geometry/PolygonDto.java
// public class PolygonDto extends GeometryDto {
//
// private static final long serialVersionUID = 1L;
//
// private List<LineStringDto> linearRings;
//
// @Override
// public GeoJSONObjectTypeEnum getGeoJSONObjectType() {
// return GeoJSONObjectTypeEnum.Polygon;
// }
//
// public List<LineStringDto> getLinearRings() {
// return linearRings;
// }
//
// public void setLinearRings(List<LineStringDto> linearRings) {
// this.linearRings = linearRings;
// }
//
// }
// Path: ugeojson-builder/src/main/java/org/ugeojson/builder/geometry/MultiPolygonBuilder.java
import java.util.List;
import org.ugeojson.builder.common.BuilderConstants;
import org.ugeojson.model.GeoJSONObjectTypeEnum;
import org.ugeojson.model.geometry.LineStringDto;
import org.ugeojson.model.geometry.MultiPolygonDto;
import org.ugeojson.model.geometry.PolygonDto;
package org.ugeojson.builder.geometry;
/**
* @author moksuzer
*
*/
public class MultiPolygonBuilder extends GeometryBuilder<MultiPolygonDto> {
private static final MultiPolygonBuilder INSTANCE = new MultiPolygonBuilder();
public static MultiPolygonBuilder getInstance() {
return INSTANCE;
}
private MultiPolygonBuilder() {
}
/*
* (non-Javadoc)
*
* @see
* org.ugeojson.builder.geometry.GeometryBuilder#toGeometryGeoJSON(com
* .erumi.ugeojson.model.geometry.GeometryDto)
*/
@Override
public String toGeoJSON(MultiPolygonDto multiPolygon) {
if (multiPolygon == null || multiPolygon.getPolygons() == null || multiPolygon.getPolygons().isEmpty()) { | return BuilderConstants.NULL_VALUE; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.