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
AnujaK/restfiddle
src/main/java/com/restfiddle/controller/rest/EntitySessionController.java
// Path: src/main/java/com/restfiddle/service/auth/EntityAuthService.java // @Service // public class EntityAuthService { // // private static final String ENTITY_AUTH = "EntityAuth"; // private static final String UNAUTHORIZED = "unauthorized"; // private static final String SUCCESS = "success"; // // @Autowired // private MongoTemplate mongoTemplate; // // public DBObject authenticate(JSONObject userDTO, String projectId) throws Exception{ // // DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_User"); // // BasicDBObject query = new BasicDBObject(); // query.append("username", userDTO.get("username")); // // DBObject user = dbCollection.findOne(query); // if(user == null){ // throw new Exception("User not found"); // } // // BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); // BasicDBObject auth; // if(encoder.matches((String)userDTO.get("password"),(String)user.get("password"))){ // auth = new BasicDBObject(); // auth.append("user", new DBRef(projectId+"_User",user.get( "_id" ))).append("expireAt", new Date(System.currentTimeMillis() + 3600 * 1000)); // auth.put("projectId", projectId); // // DBCollection dbCollectionAuth = mongoTemplate.getCollection(ENTITY_AUTH); // dbCollectionAuth.insert(auth); // }else{ // throw new Exception("Invalid password"); // } // // return auth; // } // // public boolean logout(String llt){ // // DBCollection dbCollection = mongoTemplate.getCollection(ENTITY_AUTH); // // BasicDBObject queryObject = new BasicDBObject(); // queryObject.append("_id", new ObjectId(llt)); // WriteResult result = dbCollection.remove(queryObject); // // return result.getN() == 1; // } // // public JSONObject authorize(String projectId, String authToken, String... roles) { // // JSONObject response = new JSONObject(); // if(authToken == null){ // return response.put(SUCCESS, false).put("msg", UNAUTHORIZED); // } // // List<String> roleList = Arrays.asList(roles); // // DBCollection dbCollection = mongoTemplate.getCollection(ENTITY_AUTH); // // BasicDBObject queryObject = new BasicDBObject(); // queryObject.append("_id", new ObjectId(authToken)); // // DBObject authData = dbCollection.findOne(queryObject); // // if(authData != null && projectId.equals(authData.get("projectId"))) { // DBRef userRef = (DBRef)authData.get("user"); // DBObject user = mongoTemplate.getCollection(userRef.getCollectionName()).findOne(userRef.getId()); // // DBObject roleObj = null; // if(user.containsField("role")){ // DBRef roleRef = (DBRef)user.get("role"); // roleObj = mongoTemplate.getCollection(roleRef.getCollectionName()).findOne(roleRef.getId()); // } // // if((roleObj != null && roleList.contains(roleObj.get("name"))) || roleList.contains("USER")){ // response.put(SUCCESS, true); // response.put("user", userRef); // // authData.put("expireAt", new Date(System.currentTimeMillis() + 3600 * 1000)); // dbCollection.save(authData); // } else { // response.put(SUCCESS, false).put("msg", UNAUTHORIZED); // } // } else { // response.put(SUCCESS, false).put("msg", UNAUTHORIZED); // } // // return response; // } // }
import java.util.Map; import org.bson.types.ObjectId; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.DBRef; import com.restfiddle.service.auth.EntityAuthService;
/* * Copyright 2015 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @Transactional public class EntitySessionController { Logger logger = LoggerFactory.getLogger(EntitySessionController.class); @Autowired private MongoTemplate mongoTemplate; @Autowired
// Path: src/main/java/com/restfiddle/service/auth/EntityAuthService.java // @Service // public class EntityAuthService { // // private static final String ENTITY_AUTH = "EntityAuth"; // private static final String UNAUTHORIZED = "unauthorized"; // private static final String SUCCESS = "success"; // // @Autowired // private MongoTemplate mongoTemplate; // // public DBObject authenticate(JSONObject userDTO, String projectId) throws Exception{ // // DBCollection dbCollection = mongoTemplate.getCollection(projectId+"_User"); // // BasicDBObject query = new BasicDBObject(); // query.append("username", userDTO.get("username")); // // DBObject user = dbCollection.findOne(query); // if(user == null){ // throw new Exception("User not found"); // } // // BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); // BasicDBObject auth; // if(encoder.matches((String)userDTO.get("password"),(String)user.get("password"))){ // auth = new BasicDBObject(); // auth.append("user", new DBRef(projectId+"_User",user.get( "_id" ))).append("expireAt", new Date(System.currentTimeMillis() + 3600 * 1000)); // auth.put("projectId", projectId); // // DBCollection dbCollectionAuth = mongoTemplate.getCollection(ENTITY_AUTH); // dbCollectionAuth.insert(auth); // }else{ // throw new Exception("Invalid password"); // } // // return auth; // } // // public boolean logout(String llt){ // // DBCollection dbCollection = mongoTemplate.getCollection(ENTITY_AUTH); // // BasicDBObject queryObject = new BasicDBObject(); // queryObject.append("_id", new ObjectId(llt)); // WriteResult result = dbCollection.remove(queryObject); // // return result.getN() == 1; // } // // public JSONObject authorize(String projectId, String authToken, String... roles) { // // JSONObject response = new JSONObject(); // if(authToken == null){ // return response.put(SUCCESS, false).put("msg", UNAUTHORIZED); // } // // List<String> roleList = Arrays.asList(roles); // // DBCollection dbCollection = mongoTemplate.getCollection(ENTITY_AUTH); // // BasicDBObject queryObject = new BasicDBObject(); // queryObject.append("_id", new ObjectId(authToken)); // // DBObject authData = dbCollection.findOne(queryObject); // // if(authData != null && projectId.equals(authData.get("projectId"))) { // DBRef userRef = (DBRef)authData.get("user"); // DBObject user = mongoTemplate.getCollection(userRef.getCollectionName()).findOne(userRef.getId()); // // DBObject roleObj = null; // if(user.containsField("role")){ // DBRef roleRef = (DBRef)user.get("role"); // roleObj = mongoTemplate.getCollection(roleRef.getCollectionName()).findOne(roleRef.getId()); // } // // if((roleObj != null && roleList.contains(roleObj.get("name"))) || roleList.contains("USER")){ // response.put(SUCCESS, true); // response.put("user", userRef); // // authData.put("expireAt", new Date(System.currentTimeMillis() + 3600 * 1000)); // dbCollection.save(authData); // } else { // response.put(SUCCESS, false).put("msg", UNAUTHORIZED); // } // } else { // response.put(SUCCESS, false).put("msg", UNAUTHORIZED); // } // // return response; // } // } // Path: src/main/java/com/restfiddle/controller/rest/EntitySessionController.java import java.util.Map; import org.bson.types.ObjectId; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.DBRef; import com.restfiddle.service.auth.EntityAuthService; /* * Copyright 2015 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @Transactional public class EntitySessionController { Logger logger = LoggerFactory.getLogger(EntitySessionController.class); @Autowired private MongoTemplate mongoTemplate; @Autowired
private EntityAuthService authService;
AnujaK/restfiddle
src/main/java/com/restfiddle/controller/rest/GenerateApiController.java
// Path: src/main/java/com/restfiddle/dao/NodeRepository.java // public interface NodeRepository extends RfRepository<BaseNode, String> { // // @Query("{ 'parentId' : ?0 }") // public List<BaseNode> getChildren(String nodeId); // // @Query("{ 'projectId' : ?0 }") // public List<BaseNode> findNodesFromAProject(String projectId); // // @Query("{ 'projectId' : ?0 ,$or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public List<BaseNode> searchNodesFromAProject(String projectId, String search); // // @Query("{ 'projectId' : ?0 , nodeType : {$exists:false}, name : { $regex : ?1, $options: 'i' }} }") // public List<BaseNode> findRequestsFromAProject(String projectId, String search); // // @Query("{'workspaceId' : ?0, 'starred' : true , name : { $regex : ?1, $options: 'i'}}") // public Page<BaseNode> findStarredNodes(String workspaceId, String search, Pageable pageable); // // @Query("{ 'tags' : ?0 }") // public Page<BaseNode> findTaggedNodes(String tagId, Pageable pageable); // // @Query("{ 'tags' : ?0 , $or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public Page<BaseNode> searchTaggedNodes(String tagId, String search, Pageable pageable); // // @Query("{ 'workspaceId' : ?0, 'nodeType' : 'PROJECT', name : { $regex : ?1, $options: 'i'}}") // public List<BaseNode> findProjectsfromAWorkspace(String workspaceId, String search); // }
import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.transaction.annotation.Transactional; 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.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.restfiddle.dao.GenericEntityDataRepository; import com.restfiddle.dao.GenericEntityRepository; import com.restfiddle.dao.NodeRepository; import com.restfiddle.dto.ConversationDTO; import com.restfiddle.dto.NodeDTO; import com.restfiddle.dto.RfRequestDTO; import com.restfiddle.dto.StatusResponse; import com.restfiddle.entity.BaseNode; import com.restfiddle.entity.GenericEntity; import com.restfiddle.entity.GenericEntityField;
/* * Copyright 2015 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @Transactional public class GenerateApiController { private static final String ENTITIES = "/entities/"; private static final String API = "/api/"; Logger logger = LoggerFactory.getLogger(GenerateApiController.class); @Value("${application.host-uri}") private String hostUri; @Autowired private NodeController nodeController; @Autowired
// Path: src/main/java/com/restfiddle/dao/NodeRepository.java // public interface NodeRepository extends RfRepository<BaseNode, String> { // // @Query("{ 'parentId' : ?0 }") // public List<BaseNode> getChildren(String nodeId); // // @Query("{ 'projectId' : ?0 }") // public List<BaseNode> findNodesFromAProject(String projectId); // // @Query("{ 'projectId' : ?0 ,$or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public List<BaseNode> searchNodesFromAProject(String projectId, String search); // // @Query("{ 'projectId' : ?0 , nodeType : {$exists:false}, name : { $regex : ?1, $options: 'i' }} }") // public List<BaseNode> findRequestsFromAProject(String projectId, String search); // // @Query("{'workspaceId' : ?0, 'starred' : true , name : { $regex : ?1, $options: 'i'}}") // public Page<BaseNode> findStarredNodes(String workspaceId, String search, Pageable pageable); // // @Query("{ 'tags' : ?0 }") // public Page<BaseNode> findTaggedNodes(String tagId, Pageable pageable); // // @Query("{ 'tags' : ?0 , $or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public Page<BaseNode> searchTaggedNodes(String tagId, String search, Pageable pageable); // // @Query("{ 'workspaceId' : ?0, 'nodeType' : 'PROJECT', name : { $regex : ?1, $options: 'i'}}") // public List<BaseNode> findProjectsfromAWorkspace(String workspaceId, String search); // } // Path: src/main/java/com/restfiddle/controller/rest/GenerateApiController.java import java.util.Date; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.transaction.annotation.Transactional; 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.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.restfiddle.dao.GenericEntityDataRepository; import com.restfiddle.dao.GenericEntityRepository; import com.restfiddle.dao.NodeRepository; import com.restfiddle.dto.ConversationDTO; import com.restfiddle.dto.NodeDTO; import com.restfiddle.dto.RfRequestDTO; import com.restfiddle.dto.StatusResponse; import com.restfiddle.entity.BaseNode; import com.restfiddle.entity.GenericEntity; import com.restfiddle.entity.GenericEntityField; /* * Copyright 2015 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @Transactional public class GenerateApiController { private static final String ENTITIES = "/entities/"; private static final String API = "/api/"; Logger logger = LoggerFactory.getLogger(GenerateApiController.class); @Value("${application.host-uri}") private String hostUri; @Autowired private NodeController nodeController; @Autowired
private NodeRepository nodeRepository;
AnujaK/restfiddle
src/main/java/com/restfiddle/dao/util/TreeNodeBuilder.java
// Path: src/main/java/com/restfiddle/entity/User.java // public class User extends NamedEntity implements UserDetails { // private static final long serialVersionUID = 1L; // // @Column(nullable = false) // @Length(max = 255) // private String password; // // @Column(nullable = false) // @Length(max = 255) // private String email; // // @ManyToOne // private Team team; // // @ManyToOne // private Tenant tenant; // // public String getEmail() { // return email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // // TODO Auto-generated method stub // return null; // } // // @Override // public String getUsername() { // return super.getName(); // } // // @Override // public boolean isAccountNonExpired() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isAccountNonLocked() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isCredentialsNonExpired() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isEnabled() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public String toString() { // return "User [email=" + email + "]"; // } // // public Team getTeam() { // return team; // } // // public void setTeam(Team team) { // this.team = team; // } // // public Tenant getTenant() { // return tenant; // } // // public void setTenant(Tenant tenant) { // this.tenant = tenant; // } // // }
import java.util.Date; import com.restfiddle.entity.User; import com.restfiddle.util.TreeNode;
/* * Copyright 2014 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.dao.util; public class TreeNodeBuilder { private TreeNodeBuilder() {}
// Path: src/main/java/com/restfiddle/entity/User.java // public class User extends NamedEntity implements UserDetails { // private static final long serialVersionUID = 1L; // // @Column(nullable = false) // @Length(max = 255) // private String password; // // @Column(nullable = false) // @Length(max = 255) // private String email; // // @ManyToOne // private Team team; // // @ManyToOne // private Tenant tenant; // // public String getEmail() { // return email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // // TODO Auto-generated method stub // return null; // } // // @Override // public String getUsername() { // return super.getName(); // } // // @Override // public boolean isAccountNonExpired() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isAccountNonLocked() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isCredentialsNonExpired() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isEnabled() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public String toString() { // return "User [email=" + email + "]"; // } // // public Team getTeam() { // return team; // } // // public void setTeam(Team team) { // this.team = team; // } // // public Tenant getTenant() { // return tenant; // } // // public void setTenant(Tenant tenant) { // this.tenant = tenant; // } // // } // Path: src/main/java/com/restfiddle/dao/util/TreeNodeBuilder.java import java.util.Date; import com.restfiddle.entity.User; import com.restfiddle.util.TreeNode; /* * Copyright 2014 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.dao.util; public class TreeNodeBuilder { private TreeNodeBuilder() {}
public static TreeNode createTreeNode(String nodeId, String nodeName, String nodeDesc, String workspaceId, String parentId, Long position, String nodeType, Boolean starred, String method, Date lastModifiedDate, User lastModifiedBy) {
AnujaK/restfiddle
src/main/java/com/restfiddle/controller/rest/sample/SampleWebController.java
// Path: src/main/java/com/restfiddle/entity/User.java // public class User extends NamedEntity implements UserDetails { // private static final long serialVersionUID = 1L; // // @Column(nullable = false) // @Length(max = 255) // private String password; // // @Column(nullable = false) // @Length(max = 255) // private String email; // // @ManyToOne // private Team team; // // @ManyToOne // private Tenant tenant; // // public String getEmail() { // return email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // // TODO Auto-generated method stub // return null; // } // // @Override // public String getUsername() { // return super.getName(); // } // // @Override // public boolean isAccountNonExpired() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isAccountNonLocked() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isCredentialsNonExpired() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isEnabled() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public String toString() { // return "User [email=" + email + "]"; // } // // public Team getTeam() { // return team; // } // // public void setTeam(Team team) { // this.team = team; // } // // public Tenant getTenant() { // return tenant; // } // // public void setTenant(Tenant tenant) { // this.tenant = tenant; // } // // }
import java.util.Date; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.restfiddle.entity.User;
/* * Copyright 2014 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest.sample; @Controller @EnableAutoConfiguration @ComponentScan public class SampleWebController { @Value("${application.message:REST Fiddle}") private String message = "REST Fiddle"; private static final String TEMPLATE = "Hello, %s!"; @RequestMapping("/web") public String home(Map<String, Object> model) { model.put("time", new Date()); model.put("message", this.message); return "welcome"; } @RequestMapping("/data") public @ResponseBody
// Path: src/main/java/com/restfiddle/entity/User.java // public class User extends NamedEntity implements UserDetails { // private static final long serialVersionUID = 1L; // // @Column(nullable = false) // @Length(max = 255) // private String password; // // @Column(nullable = false) // @Length(max = 255) // private String email; // // @ManyToOne // private Team team; // // @ManyToOne // private Tenant tenant; // // public String getEmail() { // return email; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // // TODO Auto-generated method stub // return null; // } // // @Override // public String getUsername() { // return super.getName(); // } // // @Override // public boolean isAccountNonExpired() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isAccountNonLocked() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isCredentialsNonExpired() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public boolean isEnabled() { // return StatusType.ACTIVE.toString().equals(super.getStatus()); // } // // @Override // public String toString() { // return "User [email=" + email + "]"; // } // // public Team getTeam() { // return team; // } // // public void setTeam(Team team) { // this.team = team; // } // // public Tenant getTenant() { // return tenant; // } // // public void setTenant(Tenant tenant) { // this.tenant = tenant; // } // // } // Path: src/main/java/com/restfiddle/controller/rest/sample/SampleWebController.java import java.util.Date; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.restfiddle.entity.User; /* * Copyright 2014 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest.sample; @Controller @EnableAutoConfiguration @ComponentScan public class SampleWebController { @Value("${application.message:REST Fiddle}") private String message = "REST Fiddle"; private static final String TEMPLATE = "Hello, %s!"; @RequestMapping("/web") public String home(Map<String, Object> model) { model.put("time", new Date()); model.put("message", this.message); return "welcome"; } @RequestMapping("/data") public @ResponseBody
User sayHello(@RequestParam(value = "name", required = false, defaultValue = "JSON") String name) {
AnujaK/restfiddle
src/main/java/com/restfiddle/controller/rest/ImportController.java
// Path: src/main/java/com/restfiddle/dao/NodeRepository.java // public interface NodeRepository extends RfRepository<BaseNode, String> { // // @Query("{ 'parentId' : ?0 }") // public List<BaseNode> getChildren(String nodeId); // // @Query("{ 'projectId' : ?0 }") // public List<BaseNode> findNodesFromAProject(String projectId); // // @Query("{ 'projectId' : ?0 ,$or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public List<BaseNode> searchNodesFromAProject(String projectId, String search); // // @Query("{ 'projectId' : ?0 , nodeType : {$exists:false}, name : { $regex : ?1, $options: 'i' }} }") // public List<BaseNode> findRequestsFromAProject(String projectId, String search); // // @Query("{'workspaceId' : ?0, 'starred' : true , name : { $regex : ?1, $options: 'i'}}") // public Page<BaseNode> findStarredNodes(String workspaceId, String search, Pageable pageable); // // @Query("{ 'tags' : ?0 }") // public Page<BaseNode> findTaggedNodes(String tagId, Pageable pageable); // // @Query("{ 'tags' : ?0 , $or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public Page<BaseNode> searchTaggedNodes(String tagId, String search, Pageable pageable); // // @Query("{ 'workspaceId' : ?0, 'nodeType' : 'PROJECT', name : { $regex : ?1, $options: 'i'}}") // public List<BaseNode> findProjectsfromAWorkspace(String workspaceId, String search); // }
import io.swagger.models.HttpMethod; import io.swagger.models.Info; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; import io.swagger.models.parameters.Parameter; import io.swagger.parser.SwaggerParser; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.databind.ObjectMapper; import com.restfiddle.constant.NodeType; import com.restfiddle.dao.NodeRepository; import com.restfiddle.dto.ConversationDTO; import com.restfiddle.dto.FormDataDTO; import com.restfiddle.dto.NodeDTO; import com.restfiddle.dto.RfHeaderDTO; import com.restfiddle.dto.RfRequestDTO; import com.restfiddle.entity.BaseNode; import com.restfiddle.entity.Project; import com.restfiddle.util.TreeNode;
/* * Copyright 2015 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @Transactional public class ImportController { Logger logger = LoggerFactory.getLogger(ImportController.class); @Autowired private NodeController nodeController; @Autowired private ConversationController conversationController; @Autowired private ProjectController projectController; @Autowired
// Path: src/main/java/com/restfiddle/dao/NodeRepository.java // public interface NodeRepository extends RfRepository<BaseNode, String> { // // @Query("{ 'parentId' : ?0 }") // public List<BaseNode> getChildren(String nodeId); // // @Query("{ 'projectId' : ?0 }") // public List<BaseNode> findNodesFromAProject(String projectId); // // @Query("{ 'projectId' : ?0 ,$or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public List<BaseNode> searchNodesFromAProject(String projectId, String search); // // @Query("{ 'projectId' : ?0 , nodeType : {$exists:false}, name : { $regex : ?1, $options: 'i' }} }") // public List<BaseNode> findRequestsFromAProject(String projectId, String search); // // @Query("{'workspaceId' : ?0, 'starred' : true , name : { $regex : ?1, $options: 'i'}}") // public Page<BaseNode> findStarredNodes(String workspaceId, String search, Pageable pageable); // // @Query("{ 'tags' : ?0 }") // public Page<BaseNode> findTaggedNodes(String tagId, Pageable pageable); // // @Query("{ 'tags' : ?0 , $or : [{name : { $regex : ?1, $options: 'i' }},{ nodeType : {$exists: true}}]}") // public Page<BaseNode> searchTaggedNodes(String tagId, String search, Pageable pageable); // // @Query("{ 'workspaceId' : ?0, 'nodeType' : 'PROJECT', name : { $regex : ?1, $options: 'i'}}") // public List<BaseNode> findProjectsfromAWorkspace(String workspaceId, String search); // } // Path: src/main/java/com/restfiddle/controller/rest/ImportController.java import io.swagger.models.HttpMethod; import io.swagger.models.Info; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; import io.swagger.models.parameters.Parameter; import io.swagger.parser.SwaggerParser; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.fasterxml.jackson.databind.ObjectMapper; import com.restfiddle.constant.NodeType; import com.restfiddle.dao.NodeRepository; import com.restfiddle.dto.ConversationDTO; import com.restfiddle.dto.FormDataDTO; import com.restfiddle.dto.NodeDTO; import com.restfiddle.dto.RfHeaderDTO; import com.restfiddle.dto.RfRequestDTO; import com.restfiddle.entity.BaseNode; import com.restfiddle.entity.Project; import com.restfiddle.util.TreeNode; /* * Copyright 2015 Ranjan Kumar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.restfiddle.controller.rest; @RestController @Transactional public class ImportController { Logger logger = LoggerFactory.getLogger(ImportController.class); @Autowired private NodeController nodeController; @Autowired private ConversationController conversationController; @Autowired private ProjectController projectController; @Autowired
private NodeRepository nodeRepository;
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/adapter/ProfileSpinnerAdapter.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/Profile.java // public class Profile { // // public static final long NO_ID = -1; // // private long mId = NO_ID; // private String mName = ""; // private String mPrivateKey = RandomPrivateKeyGenerator.generate(); // private int mPasswordLength = Constants.DEFAULT_PASSWORD_LENGTH; // private int mColorIndex = 0; // private PasswordType mPasswordType = PasswordType.ALPHANUMERIC_AND_SPECIAL_CHARS; // // /** // * Constructor // */ // public Profile() { // } // // /** // * Constructor // * // * @param id the ID // */ // public Profile(long id) { // mId = id; // } // // /** // * Constructor // * // * @param id the ID // * @param name the name // * @param privateKey the private key // * @param passwordLength the password length // * @param passwordType the password type // * @param colorIndex the color index // */ // public Profile(long id, String name, String privateKey, int passwordLength, // PasswordType passwordType, int colorIndex) { // mId = id; // mName = name; // mPrivateKey = privateKey; // mPasswordLength = passwordLength; // mPasswordType = passwordType; // mColorIndex = colorIndex; // } // // @Override // public boolean equals(Object o) { // boolean equals = false; // if (o instanceof Profile) { // equals = ((Profile) o).getId() == mId; // } // return equals; // } // // @Override // public int hashCode() { // return (int) mId; // } // // /** // * Get the profile ID // * // * @return the profile ID // */ // public long getId() { // return mId; // } // // /** // * Get the profile name // * // * @return the profile name // */ // public String getName() { // return mName; // } // // /** // * Set the profile name // * // * @param name the name // */ // public void setName(String name) { // mName = name; // } // // /** // * Get the private key // * // * @return the private key // */ // public String getPrivateKey() { // return mPrivateKey; // } // // /** // * Get the password length // * // * @return the password length // */ // public int getPasswordLength() { // return mPasswordLength; // } // // /** // * Get the password type // * // * @return the password type // */ // public PasswordType getPasswordType() { // return mPasswordType; // } // // /** // * Get the color index // * // * @return the color index // */ // public int getColorIndex() { // return mColorIndex; // } // }
import java.util.List; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Typeface; import android.support.annotation.LayoutRes; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.reddyetwo.hashmypass.app.data.Profile;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.adapter; /** * Adapter for spinners containing the list of {@link com.reddyetwo.hashmypass.app.data.Profile} */ public class ProfileSpinnerAdapter implements SpinnerAdapter { /** * Tag to identify the dropdown view */ private static final String TAG_VIEW_DROPDOWN = "SpinnerDropdown"; /** * Tag to identify the not-dropdown view, which shows the selected item */ private static final String TAG_VIEW_NOT_DROPDOWN = "SpinnerNotDropdown"; /** * Themed context */ private final Context mThemedContext; /** * List of profiles */
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/Profile.java // public class Profile { // // public static final long NO_ID = -1; // // private long mId = NO_ID; // private String mName = ""; // private String mPrivateKey = RandomPrivateKeyGenerator.generate(); // private int mPasswordLength = Constants.DEFAULT_PASSWORD_LENGTH; // private int mColorIndex = 0; // private PasswordType mPasswordType = PasswordType.ALPHANUMERIC_AND_SPECIAL_CHARS; // // /** // * Constructor // */ // public Profile() { // } // // /** // * Constructor // * // * @param id the ID // */ // public Profile(long id) { // mId = id; // } // // /** // * Constructor // * // * @param id the ID // * @param name the name // * @param privateKey the private key // * @param passwordLength the password length // * @param passwordType the password type // * @param colorIndex the color index // */ // public Profile(long id, String name, String privateKey, int passwordLength, // PasswordType passwordType, int colorIndex) { // mId = id; // mName = name; // mPrivateKey = privateKey; // mPasswordLength = passwordLength; // mPasswordType = passwordType; // mColorIndex = colorIndex; // } // // @Override // public boolean equals(Object o) { // boolean equals = false; // if (o instanceof Profile) { // equals = ((Profile) o).getId() == mId; // } // return equals; // } // // @Override // public int hashCode() { // return (int) mId; // } // // /** // * Get the profile ID // * // * @return the profile ID // */ // public long getId() { // return mId; // } // // /** // * Get the profile name // * // * @return the profile name // */ // public String getName() { // return mName; // } // // /** // * Set the profile name // * // * @param name the name // */ // public void setName(String name) { // mName = name; // } // // /** // * Get the private key // * // * @return the private key // */ // public String getPrivateKey() { // return mPrivateKey; // } // // /** // * Get the password length // * // * @return the password length // */ // public int getPasswordLength() { // return mPasswordLength; // } // // /** // * Get the password type // * // * @return the password type // */ // public PasswordType getPasswordType() { // return mPasswordType; // } // // /** // * Get the color index // * // * @return the color index // */ // public int getColorIndex() { // return mColorIndex; // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/adapter/ProfileSpinnerAdapter.java import java.util.List; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Typeface; import android.support.annotation.LayoutRes; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.reddyetwo.hashmypass.app.data.Profile; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.adapter; /** * Adapter for spinners containing the list of {@link com.reddyetwo.hashmypass.app.data.Profile} */ public class ProfileSpinnerAdapter implements SpinnerAdapter { /** * Tag to identify the dropdown view */ private static final String TAG_VIEW_DROPDOWN = "SpinnerDropdown"; /** * Tag to identify the not-dropdown view, which shows the selected item */ private static final String TAG_VIEW_NOT_DROPDOWN = "SpinnerNotDropdown"; /** * Themed context */ private final Context mThemedContext; /** * List of profiles */
private final List<Profile> mProfiles;
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/dialog/AboutDialog.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/PackageUtils.java // public class PackageUtils { // // private PackageUtils() { // // } // // /** // * Get the application version name // * // * @param context the {@link android.content.Context} instance // * @return the version name // */ // public static String getVersionName(Context context) { // String versionName = ""; // try { // versionName = context.getPackageManager() // .getPackageInfo(context.getPackageName(), 0).versionName; // } catch (PackageManager.NameNotFoundException e) { // Log.e(TwikApplication.LOG_TAG, "Package not found: " + e); // } // return versionName; // } // }
import android.widget.TextView; import com.reddyetwo.hashmypass.app.R; import com.reddyetwo.hashmypass.app.util.PackageUtils; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.FragmentManager; import android.content.DialogInterface; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.View;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.dialog; /** * About Dialog */ public class AboutDialog extends DialogFragment { /** * Tag to identify the {@link android.app.DialogFragment} */ private static final String FRAGMENT_DIALOG_TAG = "dialog_about"; /** * Constructor */ public AboutDialog() { } /** * Show the dialog * * @param activity the {@link android.app.Activity} instance */ public static void showAbout(Activity activity) { // Ensure that the dialog is not shown several times simultaneously FragmentManager fm = activity.getFragmentManager(); if (fm.findFragmentByTag(FRAGMENT_DIALOG_TAG) == null) { new AboutDialog().show(fm, FRAGMENT_DIALOG_TAG); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View rootView = View.inflate(getActivity(), R.layout.dialog_about, null); TextView nameView = (TextView) rootView.findViewById(R.id.app_name); nameView.setText(getString(R.string.app_name)); String bodyText = String.format(getResources().getString(R.string.about_body),
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/PackageUtils.java // public class PackageUtils { // // private PackageUtils() { // // } // // /** // * Get the application version name // * // * @param context the {@link android.content.Context} instance // * @return the version name // */ // public static String getVersionName(Context context) { // String versionName = ""; // try { // versionName = context.getPackageManager() // .getPackageInfo(context.getPackageName(), 0).versionName; // } catch (PackageManager.NameNotFoundException e) { // Log.e(TwikApplication.LOG_TAG, "Package not found: " + e); // } // return versionName; // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/dialog/AboutDialog.java import android.widget.TextView; import com.reddyetwo.hashmypass.app.R; import com.reddyetwo.hashmypass.app.util.PackageUtils; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.FragmentManager; import android.content.DialogInterface; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.View; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.dialog; /** * About Dialog */ public class AboutDialog extends DialogFragment { /** * Tag to identify the {@link android.app.DialogFragment} */ private static final String FRAGMENT_DIALOG_TAG = "dialog_about"; /** * Constructor */ public AboutDialog() { } /** * Show the dialog * * @param activity the {@link android.app.Activity} instance */ public static void showAbout(Activity activity) { // Ensure that the dialog is not shown several times simultaneously FragmentManager fm = activity.getFragmentManager(); if (fm.findFragmentByTag(FRAGMENT_DIALOG_TAG) == null) { new AboutDialog().show(fm, FRAGMENT_DIALOG_TAG); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View rootView = View.inflate(getActivity(), R.layout.dialog_about, null); TextView nameView = (TextView) rootView.findViewById(R.id.app_name); nameView.setText(getString(R.string.app_name)); String bodyText = String.format(getResources().getString(R.string.about_body),
PackageUtils.getVersionName(getActivity()));
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/hash/PasswordHasher.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java // public class TwikApplication extends Application { // // public static final String LOG_TAG = "TWIK"; // private char[] mCachedMasterKey; // private boolean mTutorialDismissed = false; // private static TwikApplication mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // LeakCanary.install(this); // } // // /** // * Return the Singleton instance of the {@link android.app.Application} // * @return the Singleton instance of the {@link android.app.Application} // */ // public static TwikApplication getInstance() { // return mInstance; // } // // /** // * Get the tutorial dismissed flag. // * // * @return true if the tutorial has been dismissed, false otherwise. // */ // public boolean getTutorialDismissed() { // return mTutorialDismissed; // } // // /** // * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. // * // * @param tutorialDismissed the flag value // */ // public void setTutorialDismissed(boolean tutorialDismissed) { // mTutorialDismissed = tutorialDismissed; // } // // /** // * Get the cached master key // * // * @return the cached master key // */ // public char[] getCachedMasterKey() { // if (mCachedMasterKey == null || Preferences.getRememberMasterKeyMins(this) == 0) { // mCachedMasterKey = new char[]{}; // } // return mCachedMasterKey; // } // // /** // * Wipe the cached master key // */ // public void wipeCachedMasterKey() { // if (mCachedMasterKey != null) { // Arrays.fill(mCachedMasterKey, ' '); // mCachedMasterKey = null; // } // } // // /** // * Save master key to cache if enabled by user // * // * @param masterKey the master key // */ // public void cacheMasterKey(char[] masterKey) { // if (Preferences.getRememberMasterKeyMins(this) > 0) { // mCachedMasterKey = Arrays.copyOf(masterKey, masterKey.length); // } // } // } // // Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/PasswordType.java // public enum PasswordType { // ALPHANUMERIC_AND_SPECIAL_CHARS, // ALPHANUMERIC, // NUMERIC // } // // Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/SecurePassword.java // public class SecurePassword { // // private SecurePassword() { // // } // // /** // * Get the password stored in an {@link android.text.Editable} object // * // * @param s the {@link android.text.Editable} instance // * @return the password // */ // public static char[] getPassword(Editable s) { // int length = s.length(); // char[] password = new char[length]; // for (int i = 0; i < length; i++) { // password[i] = s.charAt(i); // } // return password; // } // // /** // * Convert a password stored as a char array to a byte array // * // * @param chars the password as a char array // * @return the password as a byte array // */ // public static byte[] toBytes(char[] chars) { // CharBuffer charBuffer = CharBuffer.wrap(chars); // ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer); // byte[] bytes = // Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()); // // // Clear sensitive data // Arrays.fill(charBuffer.array(), '\u0000'); // Arrays.fill(byteBuffer.array(), (byte) 0); // return bytes; // } // }
import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; import android.util.Log; import com.reddyetwo.hashmypass.app.TwikApplication; import com.reddyetwo.hashmypass.app.data.PasswordType; import com.reddyetwo.hashmypass.app.util.SecurePassword;
/* * Copyright 2014 Red Dye No. 2 * Copyright (C) 2011-2013 TG Byte Software GmbH * Copyright (C) 2009-2011 Thilo-Alexander Ginkel. * Copyright (C) 2010-2014 Eric Woodruff * Copyright (C) 2006-2010 Steve Cooper * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.hash; /** * Generator of hashed passwords */ public class PasswordHasher { /** * Keyed-hash message authentication code (HMAC) used */ private static final String HMAC_SHA1 = "HmacSHA1"; /** * Message digest used to calculate key digest */ private static final String DIGEST_MD5 = "MD5"; private static final int INJECT_RESERVED = 4; private static final int INJECT_NUMBER_OF_NUMERIC_CHARS = 10; private static final int INJECT_NUMBER_OF_SPECIAL_CHARS = 15; private static final int INJECT_NUMBER_OF_ALPHA_CHARS = 26; private static final int INJECT_OFFSET_NUMERIC = 0; private static final int INJECT_OFFSET_SPECIAL = 1; private static final int INJECT_OFFSET_ALPHA_UPPERCASE = 2; private static final int INJECT_OFFSET_ALPHA_LOWERCASE = 3; private static final int INTERMEDIATE_HASH_SIZE = 24; private PasswordHasher() { }
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java // public class TwikApplication extends Application { // // public static final String LOG_TAG = "TWIK"; // private char[] mCachedMasterKey; // private boolean mTutorialDismissed = false; // private static TwikApplication mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // LeakCanary.install(this); // } // // /** // * Return the Singleton instance of the {@link android.app.Application} // * @return the Singleton instance of the {@link android.app.Application} // */ // public static TwikApplication getInstance() { // return mInstance; // } // // /** // * Get the tutorial dismissed flag. // * // * @return true if the tutorial has been dismissed, false otherwise. // */ // public boolean getTutorialDismissed() { // return mTutorialDismissed; // } // // /** // * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. // * // * @param tutorialDismissed the flag value // */ // public void setTutorialDismissed(boolean tutorialDismissed) { // mTutorialDismissed = tutorialDismissed; // } // // /** // * Get the cached master key // * // * @return the cached master key // */ // public char[] getCachedMasterKey() { // if (mCachedMasterKey == null || Preferences.getRememberMasterKeyMins(this) == 0) { // mCachedMasterKey = new char[]{}; // } // return mCachedMasterKey; // } // // /** // * Wipe the cached master key // */ // public void wipeCachedMasterKey() { // if (mCachedMasterKey != null) { // Arrays.fill(mCachedMasterKey, ' '); // mCachedMasterKey = null; // } // } // // /** // * Save master key to cache if enabled by user // * // * @param masterKey the master key // */ // public void cacheMasterKey(char[] masterKey) { // if (Preferences.getRememberMasterKeyMins(this) > 0) { // mCachedMasterKey = Arrays.copyOf(masterKey, masterKey.length); // } // } // } // // Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/PasswordType.java // public enum PasswordType { // ALPHANUMERIC_AND_SPECIAL_CHARS, // ALPHANUMERIC, // NUMERIC // } // // Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/SecurePassword.java // public class SecurePassword { // // private SecurePassword() { // // } // // /** // * Get the password stored in an {@link android.text.Editable} object // * // * @param s the {@link android.text.Editable} instance // * @return the password // */ // public static char[] getPassword(Editable s) { // int length = s.length(); // char[] password = new char[length]; // for (int i = 0; i < length; i++) { // password[i] = s.charAt(i); // } // return password; // } // // /** // * Convert a password stored as a char array to a byte array // * // * @param chars the password as a char array // * @return the password as a byte array // */ // public static byte[] toBytes(char[] chars) { // CharBuffer charBuffer = CharBuffer.wrap(chars); // ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer); // byte[] bytes = // Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()); // // // Clear sensitive data // Arrays.fill(charBuffer.array(), '\u0000'); // Arrays.fill(byteBuffer.array(), (byte) 0); // return bytes; // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/hash/PasswordHasher.java import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; import android.util.Log; import com.reddyetwo.hashmypass.app.TwikApplication; import com.reddyetwo.hashmypass.app.data.PasswordType; import com.reddyetwo.hashmypass.app.util.SecurePassword; /* * Copyright 2014 Red Dye No. 2 * Copyright (C) 2011-2013 TG Byte Software GmbH * Copyright (C) 2009-2011 Thilo-Alexander Ginkel. * Copyright (C) 2010-2014 Eric Woodruff * Copyright (C) 2006-2010 Steve Cooper * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.hash; /** * Generator of hashed passwords */ public class PasswordHasher { /** * Keyed-hash message authentication code (HMAC) used */ private static final String HMAC_SHA1 = "HmacSHA1"; /** * Message digest used to calculate key digest */ private static final String DIGEST_MD5 = "MD5"; private static final int INJECT_RESERVED = 4; private static final int INJECT_NUMBER_OF_NUMERIC_CHARS = 10; private static final int INJECT_NUMBER_OF_SPECIAL_CHARS = 15; private static final int INJECT_NUMBER_OF_ALPHA_CHARS = 26; private static final int INJECT_OFFSET_NUMERIC = 0; private static final int INJECT_OFFSET_SPECIAL = 1; private static final int INJECT_OFFSET_ALPHA_UPPERCASE = 2; private static final int INJECT_OFFSET_ALPHA_LOWERCASE = 3; private static final int INTERMEDIATE_HASH_SIZE = 24; private PasswordHasher() { }
private static String hashKey(String tag, char[] key, int length, PasswordType type) {
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/Preferences.java // public class Preferences { // // // Shared preferences name // public static final String PREFS_NAME = "MyPreferences"; // // // Preferences keys // private static final String PREFS_KEY_LAST_PROFILE = "LastProfile"; // private static final String PREFS_KEY_TUTORIAL_PAGE = "tutorialPage"; // private static final String PREFS_KEY_TAG_ORDER = "tagOrder"; // // private Preferences() { // } // // /** // * Get the time the master key is remembered for // * // * @param context the context // * @return the time // */ // public static int getRememberMasterKeyMins(Context context) { // return Integer.decode(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getString(context.getString(R.string.settings_key_remember_master_key), // context.getString(R.string.settings_default_remember_master_key))); // } // // /** // * Get the preference which enables/disables copying generated passwords to clipboard // * // * @param context the context // * @return the preference value // */ // public static boolean getCopyToClipboard(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getBoolean(context.getString(R.string.settings_key_copy_to_clipboard), // context.getResources() // .getBoolean(R.bool.settings_default_copy_to_clipboard)); // } // // /** // * Get the last shown tutorial page // * // * @param context the context // * @return the page number // */ // public static int getTutorialPage(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getInt(PREFS_KEY_TUTORIAL_PAGE, 0); // } // // /** // * Set the last shown tutorial page // * // * @param context the context // * @param tutorialPage the tutorial page // */ // public static void setTutorialPage(Context context, int tutorialPage) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putInt(PREFS_KEY_TUTORIAL_PAGE, tutorialPage).apply(); // } // // /** // * Get the tag order preference // * // * @param context the context // * @return the tag order // */ // public static int getTagOrder(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getInt(PREFS_KEY_TAG_ORDER, // context.getResources().getInteger(R.integer.settings_default_tag_order)); // } // // /** // * Set the tag order preference // * // * @param context the context // * @param tagOrder the tag order // */ // public static void setTagOrder(Context context, int tagOrder) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putInt(PREFS_KEY_TAG_ORDER, tagOrder).apply(); // } // // /** // * Get the last used profile ID // * // * @param context the context // * @return the last used profile ID or -1 if not defined // */ // public static long getLastProfile(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getLong(PREFS_KEY_LAST_PROFILE, -1); // } // // /** // * Set the last used profile ID // * // * @param context the context // * @param profileId the profile ID // */ // public static void setLastProfile(Context context, long profileId) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putLong(PREFS_KEY_LAST_PROFILE, profileId).apply(); // } // }
import com.reddyetwo.hashmypass.app.data.Preferences; import com.squareup.leakcanary.LeakCanary; import java.util.Arrays; import android.app.Application;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app; /** * Class extending {@link android.app.Application} which contains data which can be accessed * from any application Activity */ public class TwikApplication extends Application { public static final String LOG_TAG = "TWIK"; private char[] mCachedMasterKey; private boolean mTutorialDismissed = false; private static TwikApplication mInstance; @Override public void onCreate() { super.onCreate(); mInstance = this; LeakCanary.install(this); } /** * Return the Singleton instance of the {@link android.app.Application} * @return the Singleton instance of the {@link android.app.Application} */ public static TwikApplication getInstance() { return mInstance; } /** * Get the tutorial dismissed flag. * * @return true if the tutorial has been dismissed, false otherwise. */ public boolean getTutorialDismissed() { return mTutorialDismissed; } /** * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. * * @param tutorialDismissed the flag value */ public void setTutorialDismissed(boolean tutorialDismissed) { mTutorialDismissed = tutorialDismissed; } /** * Get the cached master key * * @return the cached master key */ public char[] getCachedMasterKey() {
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/Preferences.java // public class Preferences { // // // Shared preferences name // public static final String PREFS_NAME = "MyPreferences"; // // // Preferences keys // private static final String PREFS_KEY_LAST_PROFILE = "LastProfile"; // private static final String PREFS_KEY_TUTORIAL_PAGE = "tutorialPage"; // private static final String PREFS_KEY_TAG_ORDER = "tagOrder"; // // private Preferences() { // } // // /** // * Get the time the master key is remembered for // * // * @param context the context // * @return the time // */ // public static int getRememberMasterKeyMins(Context context) { // return Integer.decode(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getString(context.getString(R.string.settings_key_remember_master_key), // context.getString(R.string.settings_default_remember_master_key))); // } // // /** // * Get the preference which enables/disables copying generated passwords to clipboard // * // * @param context the context // * @return the preference value // */ // public static boolean getCopyToClipboard(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getBoolean(context.getString(R.string.settings_key_copy_to_clipboard), // context.getResources() // .getBoolean(R.bool.settings_default_copy_to_clipboard)); // } // // /** // * Get the last shown tutorial page // * // * @param context the context // * @return the page number // */ // public static int getTutorialPage(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getInt(PREFS_KEY_TUTORIAL_PAGE, 0); // } // // /** // * Set the last shown tutorial page // * // * @param context the context // * @param tutorialPage the tutorial page // */ // public static void setTutorialPage(Context context, int tutorialPage) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putInt(PREFS_KEY_TUTORIAL_PAGE, tutorialPage).apply(); // } // // /** // * Get the tag order preference // * // * @param context the context // * @return the tag order // */ // public static int getTagOrder(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getInt(PREFS_KEY_TAG_ORDER, // context.getResources().getInteger(R.integer.settings_default_tag_order)); // } // // /** // * Set the tag order preference // * // * @param context the context // * @param tagOrder the tag order // */ // public static void setTagOrder(Context context, int tagOrder) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putInt(PREFS_KEY_TAG_ORDER, tagOrder).apply(); // } // // /** // * Get the last used profile ID // * // * @param context the context // * @return the last used profile ID or -1 if not defined // */ // public static long getLastProfile(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getLong(PREFS_KEY_LAST_PROFILE, -1); // } // // /** // * Set the last used profile ID // * // * @param context the context // * @param profileId the profile ID // */ // public static void setLastProfile(Context context, long profileId) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putLong(PREFS_KEY_LAST_PROFILE, profileId).apply(); // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java import com.reddyetwo.hashmypass.app.data.Preferences; import com.squareup.leakcanary.LeakCanary; import java.util.Arrays; import android.app.Application; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app; /** * Class extending {@link android.app.Application} which contains data which can be accessed * from any application Activity */ public class TwikApplication extends Application { public static final String LOG_TAG = "TWIK"; private char[] mCachedMasterKey; private boolean mTutorialDismissed = false; private static TwikApplication mInstance; @Override public void onCreate() { super.onCreate(); mInstance = this; LeakCanary.install(this); } /** * Return the Singleton instance of the {@link android.app.Application} * @return the Singleton instance of the {@link android.app.Application} */ public static TwikApplication getInstance() { return mInstance; } /** * Get the tutorial dismissed flag. * * @return true if the tutorial has been dismissed, false otherwise. */ public boolean getTutorialDismissed() { return mTutorialDismissed; } /** * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. * * @param tutorialDismissed the flag value */ public void setTutorialDismissed(boolean tutorialDismissed) { mTutorialDismissed = tutorialDismissed; } /** * Get the cached master key * * @return the cached master key */ public char[] getCachedMasterKey() {
if (mCachedMasterKey == null || Preferences.getRememberMasterKeyMins(this) == 0) {
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/data/Profile.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/Constants.java // public class Constants { // // public static final String FONT_MONOSPACE = "UbuntuMono-Regular.ttf"; // public static final int MIN_PASSWORD_LENGTH = 4; // public static final int MAX_PASSWORD_LENGTH = 26; // public static final int DEFAULT_PASSWORD_LENGTH = 8; // // private Constants() { // // } // // } // // Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/RandomPrivateKeyGenerator.java // public class RandomPrivateKeyGenerator { // // private static final int[] SUBGROUPS_LENGTH = {8, 4, 4, 4, 12}; // private static final char SUBGROUP_SEPARATOR = '-'; // private static final String ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // // private RandomPrivateKeyGenerator() { // // } // // /** // * Generate a random private key // * // * @return the random private key // */ // public static String generate() { // SecureRandom sr = new SecureRandom(); // String key = ""; // int allowedCharsLength = ALLOWED_CHARS.length(); // // for (int i = 0; i < SUBGROUPS_LENGTH.length; i++) { // for (int j = 0; j < SUBGROUPS_LENGTH[i]; j++) { // key = key + ALLOWED_CHARS.charAt(sr.nextInt(allowedCharsLength)); // } // if (i < SUBGROUPS_LENGTH.length - 1) { // key += SUBGROUP_SEPARATOR; // } // } // // return key; // } // }
import com.reddyetwo.hashmypass.app.util.Constants; import com.reddyetwo.hashmypass.app.util.RandomPrivateKeyGenerator;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.data; /** * POJO class for profiles */ public class Profile { public static final long NO_ID = -1; private long mId = NO_ID; private String mName = "";
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/Constants.java // public class Constants { // // public static final String FONT_MONOSPACE = "UbuntuMono-Regular.ttf"; // public static final int MIN_PASSWORD_LENGTH = 4; // public static final int MAX_PASSWORD_LENGTH = 26; // public static final int DEFAULT_PASSWORD_LENGTH = 8; // // private Constants() { // // } // // } // // Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/RandomPrivateKeyGenerator.java // public class RandomPrivateKeyGenerator { // // private static final int[] SUBGROUPS_LENGTH = {8, 4, 4, 4, 12}; // private static final char SUBGROUP_SEPARATOR = '-'; // private static final String ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // // private RandomPrivateKeyGenerator() { // // } // // /** // * Generate a random private key // * // * @return the random private key // */ // public static String generate() { // SecureRandom sr = new SecureRandom(); // String key = ""; // int allowedCharsLength = ALLOWED_CHARS.length(); // // for (int i = 0; i < SUBGROUPS_LENGTH.length; i++) { // for (int j = 0; j < SUBGROUPS_LENGTH[i]; j++) { // key = key + ALLOWED_CHARS.charAt(sr.nextInt(allowedCharsLength)); // } // if (i < SUBGROUPS_LENGTH.length - 1) { // key += SUBGROUP_SEPARATOR; // } // } // // return key; // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/Profile.java import com.reddyetwo.hashmypass.app.util.Constants; import com.reddyetwo.hashmypass.app.util.RandomPrivateKeyGenerator; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.data; /** * POJO class for profiles */ public class Profile { public static final long NO_ID = -1; private long mId = NO_ID; private String mName = "";
private String mPrivateKey = RandomPrivateKeyGenerator.generate();
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/data/Profile.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/Constants.java // public class Constants { // // public static final String FONT_MONOSPACE = "UbuntuMono-Regular.ttf"; // public static final int MIN_PASSWORD_LENGTH = 4; // public static final int MAX_PASSWORD_LENGTH = 26; // public static final int DEFAULT_PASSWORD_LENGTH = 8; // // private Constants() { // // } // // } // // Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/RandomPrivateKeyGenerator.java // public class RandomPrivateKeyGenerator { // // private static final int[] SUBGROUPS_LENGTH = {8, 4, 4, 4, 12}; // private static final char SUBGROUP_SEPARATOR = '-'; // private static final String ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // // private RandomPrivateKeyGenerator() { // // } // // /** // * Generate a random private key // * // * @return the random private key // */ // public static String generate() { // SecureRandom sr = new SecureRandom(); // String key = ""; // int allowedCharsLength = ALLOWED_CHARS.length(); // // for (int i = 0; i < SUBGROUPS_LENGTH.length; i++) { // for (int j = 0; j < SUBGROUPS_LENGTH[i]; j++) { // key = key + ALLOWED_CHARS.charAt(sr.nextInt(allowedCharsLength)); // } // if (i < SUBGROUPS_LENGTH.length - 1) { // key += SUBGROUP_SEPARATOR; // } // } // // return key; // } // }
import com.reddyetwo.hashmypass.app.util.Constants; import com.reddyetwo.hashmypass.app.util.RandomPrivateKeyGenerator;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.data; /** * POJO class for profiles */ public class Profile { public static final long NO_ID = -1; private long mId = NO_ID; private String mName = ""; private String mPrivateKey = RandomPrivateKeyGenerator.generate();
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/Constants.java // public class Constants { // // public static final String FONT_MONOSPACE = "UbuntuMono-Regular.ttf"; // public static final int MIN_PASSWORD_LENGTH = 4; // public static final int MAX_PASSWORD_LENGTH = 26; // public static final int DEFAULT_PASSWORD_LENGTH = 8; // // private Constants() { // // } // // } // // Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/RandomPrivateKeyGenerator.java // public class RandomPrivateKeyGenerator { // // private static final int[] SUBGROUPS_LENGTH = {8, 4, 4, 4, 12}; // private static final char SUBGROUP_SEPARATOR = '-'; // private static final String ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // // private RandomPrivateKeyGenerator() { // // } // // /** // * Generate a random private key // * // * @return the random private key // */ // public static String generate() { // SecureRandom sr = new SecureRandom(); // String key = ""; // int allowedCharsLength = ALLOWED_CHARS.length(); // // for (int i = 0; i < SUBGROUPS_LENGTH.length; i++) { // for (int j = 0; j < SUBGROUPS_LENGTH[i]; j++) { // key = key + ALLOWED_CHARS.charAt(sr.nextInt(allowedCharsLength)); // } // if (i < SUBGROUPS_LENGTH.length - 1) { // key += SUBGROUP_SEPARATOR; // } // } // // return key; // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/Profile.java import com.reddyetwo.hashmypass.app.util.Constants; import com.reddyetwo.hashmypass.app.util.RandomPrivateKeyGenerator; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.data; /** * POJO class for profiles */ public class Profile { public static final long NO_ID = -1; private long mId = NO_ID; private String mName = ""; private String mPrivateKey = RandomPrivateKeyGenerator.generate();
private int mPasswordLength = Constants.DEFAULT_PASSWORD_LENGTH;
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/tutorial/TutorialSetupFragment.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/RandomPrivateKeyGenerator.java // public class RandomPrivateKeyGenerator { // // private static final int[] SUBGROUPS_LENGTH = {8, 4, 4, 4, 12}; // private static final char SUBGROUP_SEPARATOR = '-'; // private static final String ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // // private RandomPrivateKeyGenerator() { // // } // // /** // * Generate a random private key // * // * @return the random private key // */ // public static String generate() { // SecureRandom sr = new SecureRandom(); // String key = ""; // int allowedCharsLength = ALLOWED_CHARS.length(); // // for (int i = 0; i < SUBGROUPS_LENGTH.length; i++) { // for (int j = 0; j < SUBGROUPS_LENGTH[i]; j++) { // key = key + ALLOWED_CHARS.charAt(sr.nextInt(allowedCharsLength)); // } // if (i < SUBGROUPS_LENGTH.length - 1) { // key += SUBGROUP_SEPARATOR; // } // } // // return key; // } // }
import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.reddyetwo.hashmypass.app.R; import com.reddyetwo.hashmypass.app.util.RandomPrivateKeyGenerator;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.tutorial; /** * Fragment containing the tutorial private key setup screen */ public class TutorialSetupFragment extends Fragment { private EditText mPrivateKeyText; private PrivateKeyChangedListener mPrivateKeyChangedListener; /** * Set the listener for private key changed events. * * @param listener the {@link com.reddyetwo.hashmypass.app.tutorial.TutorialSetupFragment.PrivateKeyChangedListener} instance */ public void setPrivateKeyChangedListener(PrivateKeyChangedListener listener) { mPrivateKeyChangedListener = listener; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_tutorial_setup, container, false); mPrivateKeyText = (EditText) rootView.findViewById(R.id.private_key_text); mPrivateKeyText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Nothing to do } @Override public void afterTextChanged(Editable s) { if (mPrivateKeyChangedListener != null) { mPrivateKeyChangedListener .onPrivateKeyChanged(mPrivateKeyText.getText().toString()); } } });
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/RandomPrivateKeyGenerator.java // public class RandomPrivateKeyGenerator { // // private static final int[] SUBGROUPS_LENGTH = {8, 4, 4, 4, 12}; // private static final char SUBGROUP_SEPARATOR = '-'; // private static final String ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // // private RandomPrivateKeyGenerator() { // // } // // /** // * Generate a random private key // * // * @return the random private key // */ // public static String generate() { // SecureRandom sr = new SecureRandom(); // String key = ""; // int allowedCharsLength = ALLOWED_CHARS.length(); // // for (int i = 0; i < SUBGROUPS_LENGTH.length; i++) { // for (int j = 0; j < SUBGROUPS_LENGTH[i]; j++) { // key = key + ALLOWED_CHARS.charAt(sr.nextInt(allowedCharsLength)); // } // if (i < SUBGROUPS_LENGTH.length - 1) { // key += SUBGROUP_SEPARATOR; // } // } // // return key; // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/tutorial/TutorialSetupFragment.java import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.reddyetwo.hashmypass.app.R; import com.reddyetwo.hashmypass.app.util.RandomPrivateKeyGenerator; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.tutorial; /** * Fragment containing the tutorial private key setup screen */ public class TutorialSetupFragment extends Fragment { private EditText mPrivateKeyText; private PrivateKeyChangedListener mPrivateKeyChangedListener; /** * Set the listener for private key changed events. * * @param listener the {@link com.reddyetwo.hashmypass.app.tutorial.TutorialSetupFragment.PrivateKeyChangedListener} instance */ public void setPrivateKeyChangedListener(PrivateKeyChangedListener listener) { mPrivateKeyChangedListener = listener; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_tutorial_setup, container, false); mPrivateKeyText = (EditText) rootView.findViewById(R.id.private_key_text); mPrivateKeyText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Nothing to do } @Override public void afterTextChanged(Editable s) { if (mPrivateKeyChangedListener != null) { mPrivateKeyChangedListener .onPrivateKeyChanged(mPrivateKeyText.getText().toString()); } } });
mPrivateKeyText.setText(RandomPrivateKeyGenerator.generate());
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/IdenticonGenerationTask.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/IdenticonGenerator.java // public class IdenticonGenerator { // private static final int IDENTICON_HEIGHT = 5; // private static final int IDENTICON_WIDTH = 5; // private static final int IDENTICON_DIP_SIZE = 32; // private static final int IDENTICON_MARGIN = 1; // private static final int MASK_UNSIGNED = 255; // private static final int ALPHA_OPAQUE = 255; // private static final String COLOR_BACKGROUND = "#00f0f0f0"; // private static final int BYTE_RED = 0; // private static final int BYTE_GREEN = 1; // private static final int BYTE_BLUE = 2; // private static final int HALF_RATIO = 2; // private static final int NUMBER_OF_SIDES_WIDTH_MARGIN = 2; // // private IdenticonGenerator() { // // } // // /** // * Generator the identicon of an input string // * // * @param context the {@link android.content.Context} // * @param input the input // * @return the identicon {@link android.graphics.Bitmap} // */ // public static Bitmap generate(Context context, char[] input) { // // byte[] hash = PasswordHasher.calculateDigest(input); // // Bitmap identicon = Bitmap.createBitmap(IDENTICON_WIDTH, IDENTICON_HEIGHT, Config.ARGB_8888); // // // Get color byte values as unsigned integers // int r = hash[BYTE_RED] & MASK_UNSIGNED; // int g = hash[BYTE_GREEN] & MASK_UNSIGNED; // int b = hash[BYTE_BLUE] & MASK_UNSIGNED; // // int background = Color.parseColor(COLOR_BACKGROUND); // int foreground = Color.argb(ALPHA_OPAQUE, r, g, b); // int imageCenter = (int) Math.ceil(IDENTICON_WIDTH / HALF_RATIO); // // for (int x = 0; x < IDENTICON_WIDTH; x++) { // //make identicon horizontally symmetrical // int i = x < imageCenter ? x : IDENTICON_WIDTH - 1 - x; // int pixelColor; // for (int y = 0; y < IDENTICON_HEIGHT; y++) { // // if ((hash[i] >> y & 1) == 1) { // pixelColor = foreground; // } else { // pixelColor = background; // } // // identicon.setPixel(x, y, pixelColor); // } // } // // // scale image by 2 to add border // Resources res = context.getResources(); // int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, IDENTICON_DIP_SIZE, // res.getDisplayMetrics()); // Bitmap bmpWithBorder = Bitmap.createBitmap(size, size, identicon.getConfig()); // Canvas canvas = new Canvas(bmpWithBorder); // canvas.drawColor(background); // identicon = Bitmap.createScaledBitmap(identicon, // size - IDENTICON_MARGIN * NUMBER_OF_SIDES_WIDTH_MARGIN, // size - IDENTICON_MARGIN * NUMBER_OF_SIDES_WIDTH_MARGIN, false); // canvas.drawBitmap(identicon, IDENTICON_MARGIN, IDENTICON_MARGIN, null); // // return bmpWithBorder; // } // }
import android.os.AsyncTask; import com.reddyetwo.hashmypass.app.util.IdenticonGenerator; import android.content.Context; import android.graphics.Bitmap;
/* * Copyright 2014 Red Dye No. 2 * Copyright 2014 David Hamp-Gonsalves * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app; /** * {@link android.os.AsyncTask} for generating identicons in background */ public class IdenticonGenerationTask extends AsyncTask<char[], Void, Void> { private final Context mContext; private final OnIconGeneratedListener mListener; private Bitmap mBitmap; /** * Constructor * * @param context the {@link android.content.Context} instance * @param listener the {@link com.reddyetwo.hashmypass.app.IdenticonGenerationTask.OnIconGeneratedListener} listener */ public IdenticonGenerationTask(Context context, OnIconGeneratedListener listener) { mContext = context; mListener = listener; } @Override protected Void doInBackground(char[]... params) { if (params.length > 0 && params[0].length > 0) {
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/IdenticonGenerator.java // public class IdenticonGenerator { // private static final int IDENTICON_HEIGHT = 5; // private static final int IDENTICON_WIDTH = 5; // private static final int IDENTICON_DIP_SIZE = 32; // private static final int IDENTICON_MARGIN = 1; // private static final int MASK_UNSIGNED = 255; // private static final int ALPHA_OPAQUE = 255; // private static final String COLOR_BACKGROUND = "#00f0f0f0"; // private static final int BYTE_RED = 0; // private static final int BYTE_GREEN = 1; // private static final int BYTE_BLUE = 2; // private static final int HALF_RATIO = 2; // private static final int NUMBER_OF_SIDES_WIDTH_MARGIN = 2; // // private IdenticonGenerator() { // // } // // /** // * Generator the identicon of an input string // * // * @param context the {@link android.content.Context} // * @param input the input // * @return the identicon {@link android.graphics.Bitmap} // */ // public static Bitmap generate(Context context, char[] input) { // // byte[] hash = PasswordHasher.calculateDigest(input); // // Bitmap identicon = Bitmap.createBitmap(IDENTICON_WIDTH, IDENTICON_HEIGHT, Config.ARGB_8888); // // // Get color byte values as unsigned integers // int r = hash[BYTE_RED] & MASK_UNSIGNED; // int g = hash[BYTE_GREEN] & MASK_UNSIGNED; // int b = hash[BYTE_BLUE] & MASK_UNSIGNED; // // int background = Color.parseColor(COLOR_BACKGROUND); // int foreground = Color.argb(ALPHA_OPAQUE, r, g, b); // int imageCenter = (int) Math.ceil(IDENTICON_WIDTH / HALF_RATIO); // // for (int x = 0; x < IDENTICON_WIDTH; x++) { // //make identicon horizontally symmetrical // int i = x < imageCenter ? x : IDENTICON_WIDTH - 1 - x; // int pixelColor; // for (int y = 0; y < IDENTICON_HEIGHT; y++) { // // if ((hash[i] >> y & 1) == 1) { // pixelColor = foreground; // } else { // pixelColor = background; // } // // identicon.setPixel(x, y, pixelColor); // } // } // // // scale image by 2 to add border // Resources res = context.getResources(); // int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, IDENTICON_DIP_SIZE, // res.getDisplayMetrics()); // Bitmap bmpWithBorder = Bitmap.createBitmap(size, size, identicon.getConfig()); // Canvas canvas = new Canvas(bmpWithBorder); // canvas.drawColor(background); // identicon = Bitmap.createScaledBitmap(identicon, // size - IDENTICON_MARGIN * NUMBER_OF_SIDES_WIDTH_MARGIN, // size - IDENTICON_MARGIN * NUMBER_OF_SIDES_WIDTH_MARGIN, false); // canvas.drawBitmap(identicon, IDENTICON_MARGIN, IDENTICON_MARGIN, null); // // return bmpWithBorder; // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/IdenticonGenerationTask.java import android.os.AsyncTask; import com.reddyetwo.hashmypass.app.util.IdenticonGenerator; import android.content.Context; import android.graphics.Bitmap; /* * Copyright 2014 Red Dye No. 2 * Copyright 2014 David Hamp-Gonsalves * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app; /** * {@link android.os.AsyncTask} for generating identicons in background */ public class IdenticonGenerationTask extends AsyncTask<char[], Void, Void> { private final Context mContext; private final OnIconGeneratedListener mListener; private Bitmap mBitmap; /** * Constructor * * @param context the {@link android.content.Context} instance * @param listener the {@link com.reddyetwo.hashmypass.app.IdenticonGenerationTask.OnIconGeneratedListener} listener */ public IdenticonGenerationTask(Context context, OnIconGeneratedListener listener) { mContext = context; mListener = listener; } @Override protected Void doInBackground(char[]... params) { if (params.length > 0 && params[0].length > 0) {
mBitmap = IdenticonGenerator.generate(mContext, params[0]);
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/SettingsFragment.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/Preferences.java // public class Preferences { // // // Shared preferences name // public static final String PREFS_NAME = "MyPreferences"; // // // Preferences keys // private static final String PREFS_KEY_LAST_PROFILE = "LastProfile"; // private static final String PREFS_KEY_TUTORIAL_PAGE = "tutorialPage"; // private static final String PREFS_KEY_TAG_ORDER = "tagOrder"; // // private Preferences() { // } // // /** // * Get the time the master key is remembered for // * // * @param context the context // * @return the time // */ // public static int getRememberMasterKeyMins(Context context) { // return Integer.decode(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getString(context.getString(R.string.settings_key_remember_master_key), // context.getString(R.string.settings_default_remember_master_key))); // } // // /** // * Get the preference which enables/disables copying generated passwords to clipboard // * // * @param context the context // * @return the preference value // */ // public static boolean getCopyToClipboard(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getBoolean(context.getString(R.string.settings_key_copy_to_clipboard), // context.getResources() // .getBoolean(R.bool.settings_default_copy_to_clipboard)); // } // // /** // * Get the last shown tutorial page // * // * @param context the context // * @return the page number // */ // public static int getTutorialPage(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getInt(PREFS_KEY_TUTORIAL_PAGE, 0); // } // // /** // * Set the last shown tutorial page // * // * @param context the context // * @param tutorialPage the tutorial page // */ // public static void setTutorialPage(Context context, int tutorialPage) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putInt(PREFS_KEY_TUTORIAL_PAGE, tutorialPage).apply(); // } // // /** // * Get the tag order preference // * // * @param context the context // * @return the tag order // */ // public static int getTagOrder(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getInt(PREFS_KEY_TAG_ORDER, // context.getResources().getInteger(R.integer.settings_default_tag_order)); // } // // /** // * Set the tag order preference // * // * @param context the context // * @param tagOrder the tag order // */ // public static void setTagOrder(Context context, int tagOrder) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putInt(PREFS_KEY_TAG_ORDER, tagOrder).apply(); // } // // /** // * Get the last used profile ID // * // * @param context the context // * @return the last used profile ID or -1 if not defined // */ // public static long getLastProfile(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getLong(PREFS_KEY_LAST_PROFILE, -1); // } // // /** // * Set the last used profile ID // * // * @param context the context // * @param profileId the profile ID // */ // public static void setLastProfile(Context context, long profileId) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putLong(PREFS_KEY_LAST_PROFILE, profileId).apply(); // } // }
import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import com.reddyetwo.hashmypass.app.data.Preferences;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app; /** * Fragment for configuring the application preferencesM */ public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { private static final int MINUTES_IN_HOUR = 60; private Preference mRememberMasterKeyPreference; private Preference mCopyToClipboardPreference; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/Preferences.java // public class Preferences { // // // Shared preferences name // public static final String PREFS_NAME = "MyPreferences"; // // // Preferences keys // private static final String PREFS_KEY_LAST_PROFILE = "LastProfile"; // private static final String PREFS_KEY_TUTORIAL_PAGE = "tutorialPage"; // private static final String PREFS_KEY_TAG_ORDER = "tagOrder"; // // private Preferences() { // } // // /** // * Get the time the master key is remembered for // * // * @param context the context // * @return the time // */ // public static int getRememberMasterKeyMins(Context context) { // return Integer.decode(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getString(context.getString(R.string.settings_key_remember_master_key), // context.getString(R.string.settings_default_remember_master_key))); // } // // /** // * Get the preference which enables/disables copying generated passwords to clipboard // * // * @param context the context // * @return the preference value // */ // public static boolean getCopyToClipboard(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getBoolean(context.getString(R.string.settings_key_copy_to_clipboard), // context.getResources() // .getBoolean(R.bool.settings_default_copy_to_clipboard)); // } // // /** // * Get the last shown tutorial page // * // * @param context the context // * @return the page number // */ // public static int getTutorialPage(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getInt(PREFS_KEY_TUTORIAL_PAGE, 0); // } // // /** // * Set the last shown tutorial page // * // * @param context the context // * @param tutorialPage the tutorial page // */ // public static void setTutorialPage(Context context, int tutorialPage) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putInt(PREFS_KEY_TUTORIAL_PAGE, tutorialPage).apply(); // } // // /** // * Get the tag order preference // * // * @param context the context // * @return the tag order // */ // public static int getTagOrder(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getInt(PREFS_KEY_TAG_ORDER, // context.getResources().getInteger(R.integer.settings_default_tag_order)); // } // // /** // * Set the tag order preference // * // * @param context the context // * @param tagOrder the tag order // */ // public static void setTagOrder(Context context, int tagOrder) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putInt(PREFS_KEY_TAG_ORDER, tagOrder).apply(); // } // // /** // * Get the last used profile ID // * // * @param context the context // * @return the last used profile ID or -1 if not defined // */ // public static long getLastProfile(Context context) { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) // .getLong(PREFS_KEY_LAST_PROFILE, -1); // } // // /** // * Set the last used profile ID // * // * @param context the context // * @param profileId the profile ID // */ // public static void setLastProfile(Context context, long profileId) { // context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit() // .putLong(PREFS_KEY_LAST_PROFILE, profileId).apply(); // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/SettingsFragment.java import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import com.reddyetwo.hashmypass.app.data.Preferences; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app; /** * Fragment for configuring the application preferencesM */ public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { private static final int MINUTES_IN_HOUR = 60; private Preference mRememberMasterKeyPreference; private Preference mCopyToClipboardPreference; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(Preferences.PREFS_NAME);
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/util/MasterKeyAlarmManager.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java // public class TwikApplication extends Application { // // public static final String LOG_TAG = "TWIK"; // private char[] mCachedMasterKey; // private boolean mTutorialDismissed = false; // private static TwikApplication mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // LeakCanary.install(this); // } // // /** // * Return the Singleton instance of the {@link android.app.Application} // * @return the Singleton instance of the {@link android.app.Application} // */ // public static TwikApplication getInstance() { // return mInstance; // } // // /** // * Get the tutorial dismissed flag. // * // * @return true if the tutorial has been dismissed, false otherwise. // */ // public boolean getTutorialDismissed() { // return mTutorialDismissed; // } // // /** // * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. // * // * @param tutorialDismissed the flag value // */ // public void setTutorialDismissed(boolean tutorialDismissed) { // mTutorialDismissed = tutorialDismissed; // } // // /** // * Get the cached master key // * // * @return the cached master key // */ // public char[] getCachedMasterKey() { // if (mCachedMasterKey == null || Preferences.getRememberMasterKeyMins(this) == 0) { // mCachedMasterKey = new char[]{}; // } // return mCachedMasterKey; // } // // /** // * Wipe the cached master key // */ // public void wipeCachedMasterKey() { // if (mCachedMasterKey != null) { // Arrays.fill(mCachedMasterKey, ' '); // mCachedMasterKey = null; // } // } // // /** // * Save master key to cache if enabled by user // * // * @param masterKey the master key // */ // public void cacheMasterKey(char[] masterKey) { // if (Preferences.getRememberMasterKeyMins(this) > 0) { // mCachedMasterKey = Arrays.copyOf(masterKey, masterKey.length); // } // } // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.SystemClock; import com.reddyetwo.hashmypass.app.TwikApplication;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.util; /** * Manager for master key cache expired alarms */ public class MasterKeyAlarmManager extends BroadcastReceiver { private static final int REQUEST_REMOVE_MASTER_KEY = 1; private static final int MILLIS_IN_A_MINUTE = 60000; /** * Set the alarm * * @param context the {@link android.content.Context} instance * @param minutes the minutes before the alarm is triggered */ public static void setAlarm(Context context, int minutes) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent intent = PendingIntent.getBroadcast(context, REQUEST_REMOVE_MASTER_KEY, new Intent(context, MasterKeyAlarmManager.class), 0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { alarmManager.setExact(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + minutes * MILLIS_IN_A_MINUTE, intent); } else { alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + minutes * MILLIS_IN_A_MINUTE, intent); } } /** * Cancel the alarm * * @param context the {@link android.content.Context} instance */ public static void cancelAlarm(Context context) { PendingIntent intent = PendingIntent.getBroadcast(context, REQUEST_REMOVE_MASTER_KEY, new Intent(context, MasterKeyAlarmManager.class), 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(intent); } @Override public void onReceive(Context context, Intent intent) { // Remove cached master key
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java // public class TwikApplication extends Application { // // public static final String LOG_TAG = "TWIK"; // private char[] mCachedMasterKey; // private boolean mTutorialDismissed = false; // private static TwikApplication mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // LeakCanary.install(this); // } // // /** // * Return the Singleton instance of the {@link android.app.Application} // * @return the Singleton instance of the {@link android.app.Application} // */ // public static TwikApplication getInstance() { // return mInstance; // } // // /** // * Get the tutorial dismissed flag. // * // * @return true if the tutorial has been dismissed, false otherwise. // */ // public boolean getTutorialDismissed() { // return mTutorialDismissed; // } // // /** // * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. // * // * @param tutorialDismissed the flag value // */ // public void setTutorialDismissed(boolean tutorialDismissed) { // mTutorialDismissed = tutorialDismissed; // } // // /** // * Get the cached master key // * // * @return the cached master key // */ // public char[] getCachedMasterKey() { // if (mCachedMasterKey == null || Preferences.getRememberMasterKeyMins(this) == 0) { // mCachedMasterKey = new char[]{}; // } // return mCachedMasterKey; // } // // /** // * Wipe the cached master key // */ // public void wipeCachedMasterKey() { // if (mCachedMasterKey != null) { // Arrays.fill(mCachedMasterKey, ' '); // mCachedMasterKey = null; // } // } // // /** // * Save master key to cache if enabled by user // * // * @param masterKey the master key // */ // public void cacheMasterKey(char[] masterKey) { // if (Preferences.getRememberMasterKeyMins(this) > 0) { // mCachedMasterKey = Arrays.copyOf(masterKey, masterKey.length); // } // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/MasterKeyAlarmManager.java import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.SystemClock; import com.reddyetwo.hashmypass.app.TwikApplication; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.util; /** * Manager for master key cache expired alarms */ public class MasterKeyAlarmManager extends BroadcastReceiver { private static final int REQUEST_REMOVE_MASTER_KEY = 1; private static final int MILLIS_IN_A_MINUTE = 60000; /** * Set the alarm * * @param context the {@link android.content.Context} instance * @param minutes the minutes before the alarm is triggered */ public static void setAlarm(Context context, int minutes) { AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent intent = PendingIntent.getBroadcast(context, REQUEST_REMOVE_MASTER_KEY, new Intent(context, MasterKeyAlarmManager.class), 0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { alarmManager.setExact(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + minutes * MILLIS_IN_A_MINUTE, intent); } else { alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + minutes * MILLIS_IN_A_MINUTE, intent); } } /** * Cancel the alarm * * @param context the {@link android.content.Context} instance */ public static void cancelAlarm(Context context) { PendingIntent intent = PendingIntent.getBroadcast(context, REQUEST_REMOVE_MASTER_KEY, new Intent(context, MasterKeyAlarmManager.class), 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(intent); } @Override public void onReceive(Context context, Intent intent) { // Remove cached master key
TwikApplication.getInstance().wipeCachedMasterKey();
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/util/ProfileFormInflater.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/PasswordType.java // public enum PasswordType { // ALPHANUMERIC_AND_SPECIAL_CHARS, // ALPHANUMERIC, // NUMERIC // }
import android.content.Context; import android.widget.ArrayAdapter; import android.widget.Spinner; import com.reddyetwo.hashmypass.app.R; import com.reddyetwo.hashmypass.app.data.PasswordType;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.util; /** * Inflater for 'Add profile' or 'Edit profile' forms spinners */ public class ProfileFormInflater { private ProfileFormInflater() { } /** * Populate a password length spinner * * @param context the {@link android.content.Context} instance * @param spinner the {@link android.widget.Spinner} instance * @param passwordLength the password length */ public static void populatePasswordLengthSpinner(Context context, Spinner spinner, int passwordLength) { ArrayAdapter<String> passwordLengthAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, new String[]{String.valueOf(passwordLength)}); passwordLengthAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(passwordLengthAdapter); } /** * Populate a password type spinner * * @param context the {@link android.content.Context} instance * @param spinner the {@link android.widget.Spinner} instance * @param passwordType the password type */ public static void populatePasswordTypeSpinner(Context context, Spinner spinner,
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/PasswordType.java // public enum PasswordType { // ALPHANUMERIC_AND_SPECIAL_CHARS, // ALPHANUMERIC, // NUMERIC // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/ProfileFormInflater.java import android.content.Context; import android.widget.ArrayAdapter; import android.widget.Spinner; import com.reddyetwo.hashmypass.app.R; import com.reddyetwo.hashmypass.app.data.PasswordType; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.util; /** * Inflater for 'Add profile' or 'Edit profile' forms spinners */ public class ProfileFormInflater { private ProfileFormInflater() { } /** * Populate a password length spinner * * @param context the {@link android.content.Context} instance * @param spinner the {@link android.widget.Spinner} instance * @param passwordLength the password length */ public static void populatePasswordLengthSpinner(Context context, Spinner spinner, int passwordLength) { ArrayAdapter<String> passwordLengthAdapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, new String[]{String.valueOf(passwordLength)}); passwordLengthAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(passwordLengthAdapter); } /** * Populate a password type spinner * * @param context the {@link android.content.Context} instance * @param spinner the {@link android.widget.Spinner} instance * @param passwordType the password type */ public static void populatePasswordTypeSpinner(Context context, Spinner spinner,
PasswordType passwordType) {
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/dialog/PasswordLengthDialogFragment.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/Constants.java // public class Constants { // // public static final String FONT_MONOSPACE = "UbuntuMono-Regular.ttf"; // public static final int MIN_PASSWORD_LENGTH = 4; // public static final int MAX_PASSWORD_LENGTH = 26; // public static final int DEFAULT_PASSWORD_LENGTH = 8; // // private Constants() { // // } // // }
import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.NumberPicker; import com.reddyetwo.hashmypass.app.R; import com.reddyetwo.hashmypass.app.util.Constants;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.dialog; /** * Dialog fragment with a number picker for selecting password length. */ public class PasswordLengthDialogFragment extends DialogFragment { private int mPasswordLength; private OnSelectedListener mListener; /** * Set the password length * * @param passwordLength the password length */ public void setPasswordLength(int passwordLength) { this.mPasswordLength = passwordLength; } /** * Set the listener for password length selected events * * @param listener the {@link com.reddyetwo.hashmypass.app.dialog.PasswordLengthDialogFragment.OnSelectedListener} instance */ public void setOnSelectedListener(OnSelectedListener listener) { mListener = listener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if (mListener == null) { dismiss(); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.password_length)); // Inflate the layout View view = View.inflate(getActivity(), R.layout.dialog_number_picker, null); // Set up number picker final NumberPicker picker = (NumberPicker) view.findViewById(R.id.numberPicker);
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/Constants.java // public class Constants { // // public static final String FONT_MONOSPACE = "UbuntuMono-Regular.ttf"; // public static final int MIN_PASSWORD_LENGTH = 4; // public static final int MAX_PASSWORD_LENGTH = 26; // public static final int DEFAULT_PASSWORD_LENGTH = 8; // // private Constants() { // // } // // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/dialog/PasswordLengthDialogFragment.java import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.NumberPicker; import com.reddyetwo.hashmypass.app.R; import com.reddyetwo.hashmypass.app.util.Constants; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.dialog; /** * Dialog fragment with a number picker for selecting password length. */ public class PasswordLengthDialogFragment extends DialogFragment { private int mPasswordLength; private OnSelectedListener mListener; /** * Set the password length * * @param passwordLength the password length */ public void setPasswordLength(int passwordLength) { this.mPasswordLength = passwordLength; } /** * Set the listener for password length selected events * * @param listener the {@link com.reddyetwo.hashmypass.app.dialog.PasswordLengthDialogFragment.OnSelectedListener} instance */ public void setOnSelectedListener(OnSelectedListener listener) { mListener = listener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { if (mListener == null) { dismiss(); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(getString(R.string.password_length)); // Inflate the layout View view = View.inflate(getActivity(), R.layout.dialog_number_picker, null); // Set up number picker final NumberPicker picker = (NumberPicker) view.findViewById(R.id.numberPicker);
picker.setMinValue(Constants.MIN_PASSWORD_LENGTH);
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/util/PackageUtils.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java // public class TwikApplication extends Application { // // public static final String LOG_TAG = "TWIK"; // private char[] mCachedMasterKey; // private boolean mTutorialDismissed = false; // private static TwikApplication mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // LeakCanary.install(this); // } // // /** // * Return the Singleton instance of the {@link android.app.Application} // * @return the Singleton instance of the {@link android.app.Application} // */ // public static TwikApplication getInstance() { // return mInstance; // } // // /** // * Get the tutorial dismissed flag. // * // * @return true if the tutorial has been dismissed, false otherwise. // */ // public boolean getTutorialDismissed() { // return mTutorialDismissed; // } // // /** // * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. // * // * @param tutorialDismissed the flag value // */ // public void setTutorialDismissed(boolean tutorialDismissed) { // mTutorialDismissed = tutorialDismissed; // } // // /** // * Get the cached master key // * // * @return the cached master key // */ // public char[] getCachedMasterKey() { // if (mCachedMasterKey == null || Preferences.getRememberMasterKeyMins(this) == 0) { // mCachedMasterKey = new char[]{}; // } // return mCachedMasterKey; // } // // /** // * Wipe the cached master key // */ // public void wipeCachedMasterKey() { // if (mCachedMasterKey != null) { // Arrays.fill(mCachedMasterKey, ' '); // mCachedMasterKey = null; // } // } // // /** // * Save master key to cache if enabled by user // * // * @param masterKey the master key // */ // public void cacheMasterKey(char[] masterKey) { // if (Preferences.getRememberMasterKeyMins(this) > 0) { // mCachedMasterKey = Arrays.copyOf(masterKey, masterKey.length); // } // } // }
import com.reddyetwo.hashmypass.app.TwikApplication; import android.content.Context; import android.content.pm.PackageManager; import android.util.Log;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.util; /** * Helper for package-related tasks */ public class PackageUtils { private PackageUtils() { } /** * Get the application version name * * @param context the {@link android.content.Context} instance * @return the version name */ public static String getVersionName(Context context) { String versionName = ""; try { versionName = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) {
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java // public class TwikApplication extends Application { // // public static final String LOG_TAG = "TWIK"; // private char[] mCachedMasterKey; // private boolean mTutorialDismissed = false; // private static TwikApplication mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // LeakCanary.install(this); // } // // /** // * Return the Singleton instance of the {@link android.app.Application} // * @return the Singleton instance of the {@link android.app.Application} // */ // public static TwikApplication getInstance() { // return mInstance; // } // // /** // * Get the tutorial dismissed flag. // * // * @return true if the tutorial has been dismissed, false otherwise. // */ // public boolean getTutorialDismissed() { // return mTutorialDismissed; // } // // /** // * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. // * // * @param tutorialDismissed the flag value // */ // public void setTutorialDismissed(boolean tutorialDismissed) { // mTutorialDismissed = tutorialDismissed; // } // // /** // * Get the cached master key // * // * @return the cached master key // */ // public char[] getCachedMasterKey() { // if (mCachedMasterKey == null || Preferences.getRememberMasterKeyMins(this) == 0) { // mCachedMasterKey = new char[]{}; // } // return mCachedMasterKey; // } // // /** // * Wipe the cached master key // */ // public void wipeCachedMasterKey() { // if (mCachedMasterKey != null) { // Arrays.fill(mCachedMasterKey, ' '); // mCachedMasterKey = null; // } // } // // /** // * Save master key to cache if enabled by user // * // * @param masterKey the master key // */ // public void cacheMasterKey(char[] masterKey) { // if (Preferences.getRememberMasterKeyMins(this) > 0) { // mCachedMasterKey = Arrays.copyOf(masterKey, masterKey.length); // } // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/util/PackageUtils.java import com.reddyetwo.hashmypass.app.TwikApplication; import android.content.Context; import android.content.pm.PackageManager; import android.util.Log; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.util; /** * Helper for package-related tasks */ public class PackageUtils { private PackageUtils() { } /** * Get the application version name * * @param context the {@link android.content.Context} instance * @return the version name */ public static String getVersionName(Context context) { String versionName = ""; try { versionName = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) {
Log.e(TwikApplication.LOG_TAG, "Package not found: " + e);
gustavomondron/twik
app/src/main/java/com/reddyetwo/hashmypass/app/data/FaviconSettings.java
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java // public class TwikApplication extends Application { // // public static final String LOG_TAG = "TWIK"; // private char[] mCachedMasterKey; // private boolean mTutorialDismissed = false; // private static TwikApplication mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // LeakCanary.install(this); // } // // /** // * Return the Singleton instance of the {@link android.app.Application} // * @return the Singleton instance of the {@link android.app.Application} // */ // public static TwikApplication getInstance() { // return mInstance; // } // // /** // * Get the tutorial dismissed flag. // * // * @return true if the tutorial has been dismissed, false otherwise. // */ // public boolean getTutorialDismissed() { // return mTutorialDismissed; // } // // /** // * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. // * // * @param tutorialDismissed the flag value // */ // public void setTutorialDismissed(boolean tutorialDismissed) { // mTutorialDismissed = tutorialDismissed; // } // // /** // * Get the cached master key // * // * @return the cached master key // */ // public char[] getCachedMasterKey() { // if (mCachedMasterKey == null || Preferences.getRememberMasterKeyMins(this) == 0) { // mCachedMasterKey = new char[]{}; // } // return mCachedMasterKey; // } // // /** // * Wipe the cached master key // */ // public void wipeCachedMasterKey() { // if (mCachedMasterKey != null) { // Arrays.fill(mCachedMasterKey, ' '); // mCachedMasterKey = null; // } // } // // /** // * Save master key to cache if enabled by user // * // * @param masterKey the master key // */ // public void cacheMasterKey(char[] masterKey) { // if (Preferences.getRememberMasterKeyMins(this) > 0) { // mCachedMasterKey = Arrays.copyOf(masterKey, masterKey.length); // } // } // }
import java.io.FileNotFoundException; import java.io.FileOutputStream; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import com.reddyetwo.hashmypass.app.TwikApplication; import java.io.FileInputStream;
/* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.data; /** * Class to get/add/delete/update {@link com.reddyetwo.hashmypass.app.data.Favicon} from storage */ public class FaviconSettings { private static final String FILE_NAME = "favicon-%d.png"; private static final int FAVICON_QUALITY = 100; private FaviconSettings() { } /** * Get the favicon of a site * * @param context the {@link android.content.Context} instance * @param site the site * @return the {@link com.reddyetwo.hashmypass.app.data.Favicon} instance */ public static Favicon getFavicon(Context context, String site) { DataOpenHelper helper = new DataOpenHelper(context); SQLiteDatabase db = helper.getReadableDatabase(); Cursor cursor = db.query(DataOpenHelper.FAVICONS_TABLE_NAME, new String[]{DataOpenHelper.COLUMN_ID}, DataOpenHelper.COLUMN_FAVICONS_SITE + "= ?", new String[]{site}, null, null, null); Favicon favicon = null; if (cursor.moveToFirst()) { long id = cursor.getLong(cursor.getColumnIndex(DataOpenHelper.COLUMN_ID)); try { String filename = String.format(FILE_NAME, id); FileInputStream fis = context.openFileInput(filename); Bitmap icon = BitmapFactory.decodeStream(fis); favicon = new Favicon(id, site, icon); } catch (FileNotFoundException e) { // Favicon not found in storage
// Path: app/src/main/java/com/reddyetwo/hashmypass/app/TwikApplication.java // public class TwikApplication extends Application { // // public static final String LOG_TAG = "TWIK"; // private char[] mCachedMasterKey; // private boolean mTutorialDismissed = false; // private static TwikApplication mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // LeakCanary.install(this); // } // // /** // * Return the Singleton instance of the {@link android.app.Application} // * @return the Singleton instance of the {@link android.app.Application} // */ // public static TwikApplication getInstance() { // return mInstance; // } // // /** // * Get the tutorial dismissed flag. // * // * @return true if the tutorial has been dismissed, false otherwise. // */ // public boolean getTutorialDismissed() { // return mTutorialDismissed; // } // // /** // * Set the tutorial dismissed flag. Once the tutorial has been dismissed, it is never shown again. // * // * @param tutorialDismissed the flag value // */ // public void setTutorialDismissed(boolean tutorialDismissed) { // mTutorialDismissed = tutorialDismissed; // } // // /** // * Get the cached master key // * // * @return the cached master key // */ // public char[] getCachedMasterKey() { // if (mCachedMasterKey == null || Preferences.getRememberMasterKeyMins(this) == 0) { // mCachedMasterKey = new char[]{}; // } // return mCachedMasterKey; // } // // /** // * Wipe the cached master key // */ // public void wipeCachedMasterKey() { // if (mCachedMasterKey != null) { // Arrays.fill(mCachedMasterKey, ' '); // mCachedMasterKey = null; // } // } // // /** // * Save master key to cache if enabled by user // * // * @param masterKey the master key // */ // public void cacheMasterKey(char[] masterKey) { // if (Preferences.getRememberMasterKeyMins(this) > 0) { // mCachedMasterKey = Arrays.copyOf(masterKey, masterKey.length); // } // } // } // Path: app/src/main/java/com/reddyetwo/hashmypass/app/data/FaviconSettings.java import java.io.FileNotFoundException; import java.io.FileOutputStream; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import com.reddyetwo.hashmypass.app.TwikApplication; import java.io.FileInputStream; /* * Copyright 2014 Red Dye No. 2 * * This file is part of Twik. * * Twik is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twik is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Twik. If not, see <http://www.gnu.org/licenses/>. */ package com.reddyetwo.hashmypass.app.data; /** * Class to get/add/delete/update {@link com.reddyetwo.hashmypass.app.data.Favicon} from storage */ public class FaviconSettings { private static final String FILE_NAME = "favicon-%d.png"; private static final int FAVICON_QUALITY = 100; private FaviconSettings() { } /** * Get the favicon of a site * * @param context the {@link android.content.Context} instance * @param site the site * @return the {@link com.reddyetwo.hashmypass.app.data.Favicon} instance */ public static Favicon getFavicon(Context context, String site) { DataOpenHelper helper = new DataOpenHelper(context); SQLiteDatabase db = helper.getReadableDatabase(); Cursor cursor = db.query(DataOpenHelper.FAVICONS_TABLE_NAME, new String[]{DataOpenHelper.COLUMN_ID}, DataOpenHelper.COLUMN_FAVICONS_SITE + "= ?", new String[]{site}, null, null, null); Favicon favicon = null; if (cursor.moveToFirst()) { long id = cursor.getLong(cursor.getColumnIndex(DataOpenHelper.COLUMN_ID)); try { String filename = String.format(FILE_NAME, id); FileInputStream fis = context.openFileInput(filename); Bitmap icon = BitmapFactory.decodeStream(fis); favicon = new Favicon(id, site, icon); } catch (FileNotFoundException e) { // Favicon not found in storage
Log.d(TwikApplication.LOG_TAG, "Favicon file not found: " + e);
BruceHurrican/asstudydemo
app/src/blue/java/com/bruce/demo/BlueFragment.java
// Path: app/src/blue/java/com/bruce/demo/demon/KDemonService.java // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public class KDemonService extends NotificationListenerService { // @Override // public void onNotificationPosted(StatusBarNotification sbn) { // // super.onNotificationPosted(sbn); // } // // @Override // public void onNotificationRemoved(StatusBarNotification sbn) { // // super.onNotificationRemoved(sbn); // } // } // // Path: app/src/blue/java/com/bruce/demo/demon/KService.java // public class KService extends Service { // private int a = 0; // // @Override // public void onCreate() { // super.onCreate(); // LogUtils.i("service create"); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // LogUtils.i("service start"); // new Thread(new Runnable() { // @Override // public void run() { // while (a < 100000) { // LogDetails.i("打印 %d 次", a); // a++; // } // } // }).start(); // return super.onStartCommand(intent, flags, startId); // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // } // // Path: app/src/blue/java/com/bruce/demo/keeplive/OnepxReceiver.java // public class OnepxReceiver extends BroadcastReceiver { // private static OnepxReceiver receiver; // // public static void register1pxReceiver(Context context) { // if (receiver == null) { // receiver = new OnepxReceiver(); // } // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); // } // // public static void unregister1pxReceiver(Context context) { // context.unregisterReceiver(receiver); // } // // @Override // public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { // Intent it = new Intent(context, OnepxActivity.class); // it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(it); // LogUtils.i("1px--screen off-"); // } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { // context.sendBroadcast(new Intent("finish activity")); // LogUtils.i("1px--screen on-"); // } // } // }
import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.bruce.demo.demon.KDemonService; import com.bruce.demo.demon.KService; import com.bruce.demo.keeplive.OnepxReceiver; import com.bruceutils.base.BaseFragment; import com.bruceutils.utils.PublicUtil; import com.bruceutils.utils.StorageUtil; import com.bruceutils.utils.logdetails.LogDetails; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.view.LayoutInflater;
linearLayout.setBackgroundColor(getResources().getColor(android.R.color.black)); TextView tv1 = new TextView(getActivity()); tv1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); tv1.setText("Blue module"); tv1.setTextColor(getResources().getColor(android.R.color.holo_blue_dark)); linearLayout.addView(tv1); Button btn1 = new Button(getActivity()); btn1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn1.setText("获取当前屏幕亮度和模式"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showScreenModeandValue(); } }); linearLayout.addView(btn1); Button btn2 = new Button(getActivity()); btn2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn2.setText("开启新进程"); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
// Path: app/src/blue/java/com/bruce/demo/demon/KDemonService.java // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public class KDemonService extends NotificationListenerService { // @Override // public void onNotificationPosted(StatusBarNotification sbn) { // // super.onNotificationPosted(sbn); // } // // @Override // public void onNotificationRemoved(StatusBarNotification sbn) { // // super.onNotificationRemoved(sbn); // } // } // // Path: app/src/blue/java/com/bruce/demo/demon/KService.java // public class KService extends Service { // private int a = 0; // // @Override // public void onCreate() { // super.onCreate(); // LogUtils.i("service create"); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // LogUtils.i("service start"); // new Thread(new Runnable() { // @Override // public void run() { // while (a < 100000) { // LogDetails.i("打印 %d 次", a); // a++; // } // } // }).start(); // return super.onStartCommand(intent, flags, startId); // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // } // // Path: app/src/blue/java/com/bruce/demo/keeplive/OnepxReceiver.java // public class OnepxReceiver extends BroadcastReceiver { // private static OnepxReceiver receiver; // // public static void register1pxReceiver(Context context) { // if (receiver == null) { // receiver = new OnepxReceiver(); // } // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); // } // // public static void unregister1pxReceiver(Context context) { // context.unregisterReceiver(receiver); // } // // @Override // public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { // Intent it = new Intent(context, OnepxActivity.class); // it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(it); // LogUtils.i("1px--screen off-"); // } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { // context.sendBroadcast(new Intent("finish activity")); // LogUtils.i("1px--screen on-"); // } // } // } // Path: app/src/blue/java/com/bruce/demo/BlueFragment.java import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.bruce.demo.demon.KDemonService; import com.bruce.demo.demon.KService; import com.bruce.demo.keeplive.OnepxReceiver; import com.bruceutils.base.BaseFragment; import com.bruceutils.utils.PublicUtil; import com.bruceutils.utils.StorageUtil; import com.bruceutils.utils.logdetails.LogDetails; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.view.LayoutInflater; linearLayout.setBackgroundColor(getResources().getColor(android.R.color.black)); TextView tv1 = new TextView(getActivity()); tv1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); tv1.setText("Blue module"); tv1.setTextColor(getResources().getColor(android.R.color.holo_blue_dark)); linearLayout.addView(tv1); Button btn1 = new Button(getActivity()); btn1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn1.setText("获取当前屏幕亮度和模式"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showScreenModeandValue(); } }); linearLayout.addView(btn1); Button btn2 = new Button(getActivity()); btn2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn2.setText("开启新进程"); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
getActivity().startService(new Intent(getActivity(), KService.class));
BruceHurrican/asstudydemo
app/src/blue/java/com/bruce/demo/BlueFragment.java
// Path: app/src/blue/java/com/bruce/demo/demon/KDemonService.java // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public class KDemonService extends NotificationListenerService { // @Override // public void onNotificationPosted(StatusBarNotification sbn) { // // super.onNotificationPosted(sbn); // } // // @Override // public void onNotificationRemoved(StatusBarNotification sbn) { // // super.onNotificationRemoved(sbn); // } // } // // Path: app/src/blue/java/com/bruce/demo/demon/KService.java // public class KService extends Service { // private int a = 0; // // @Override // public void onCreate() { // super.onCreate(); // LogUtils.i("service create"); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // LogUtils.i("service start"); // new Thread(new Runnable() { // @Override // public void run() { // while (a < 100000) { // LogDetails.i("打印 %d 次", a); // a++; // } // } // }).start(); // return super.onStartCommand(intent, flags, startId); // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // } // // Path: app/src/blue/java/com/bruce/demo/keeplive/OnepxReceiver.java // public class OnepxReceiver extends BroadcastReceiver { // private static OnepxReceiver receiver; // // public static void register1pxReceiver(Context context) { // if (receiver == null) { // receiver = new OnepxReceiver(); // } // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); // } // // public static void unregister1pxReceiver(Context context) { // context.unregisterReceiver(receiver); // } // // @Override // public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { // Intent it = new Intent(context, OnepxActivity.class); // it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(it); // LogUtils.i("1px--screen off-"); // } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { // context.sendBroadcast(new Intent("finish activity")); // LogUtils.i("1px--screen on-"); // } // } // }
import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.bruce.demo.demon.KDemonService; import com.bruce.demo.demon.KService; import com.bruce.demo.keeplive.OnepxReceiver; import com.bruceutils.base.BaseFragment; import com.bruceutils.utils.PublicUtil; import com.bruceutils.utils.StorageUtil; import com.bruceutils.utils.logdetails.LogDetails; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.view.LayoutInflater;
TextView tv1 = new TextView(getActivity()); tv1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); tv1.setText("Blue module"); tv1.setTextColor(getResources().getColor(android.R.color.holo_blue_dark)); linearLayout.addView(tv1); Button btn1 = new Button(getActivity()); btn1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn1.setText("获取当前屏幕亮度和模式"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showScreenModeandValue(); } }); linearLayout.addView(btn1); Button btn2 = new Button(getActivity()); btn2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn2.setText("开启新进程"); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startService(new Intent(getActivity(), KService.class));
// Path: app/src/blue/java/com/bruce/demo/demon/KDemonService.java // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public class KDemonService extends NotificationListenerService { // @Override // public void onNotificationPosted(StatusBarNotification sbn) { // // super.onNotificationPosted(sbn); // } // // @Override // public void onNotificationRemoved(StatusBarNotification sbn) { // // super.onNotificationRemoved(sbn); // } // } // // Path: app/src/blue/java/com/bruce/demo/demon/KService.java // public class KService extends Service { // private int a = 0; // // @Override // public void onCreate() { // super.onCreate(); // LogUtils.i("service create"); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // LogUtils.i("service start"); // new Thread(new Runnable() { // @Override // public void run() { // while (a < 100000) { // LogDetails.i("打印 %d 次", a); // a++; // } // } // }).start(); // return super.onStartCommand(intent, flags, startId); // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // } // // Path: app/src/blue/java/com/bruce/demo/keeplive/OnepxReceiver.java // public class OnepxReceiver extends BroadcastReceiver { // private static OnepxReceiver receiver; // // public static void register1pxReceiver(Context context) { // if (receiver == null) { // receiver = new OnepxReceiver(); // } // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); // } // // public static void unregister1pxReceiver(Context context) { // context.unregisterReceiver(receiver); // } // // @Override // public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { // Intent it = new Intent(context, OnepxActivity.class); // it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(it); // LogUtils.i("1px--screen off-"); // } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { // context.sendBroadcast(new Intent("finish activity")); // LogUtils.i("1px--screen on-"); // } // } // } // Path: app/src/blue/java/com/bruce/demo/BlueFragment.java import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.bruce.demo.demon.KDemonService; import com.bruce.demo.demon.KService; import com.bruce.demo.keeplive.OnepxReceiver; import com.bruceutils.base.BaseFragment; import com.bruceutils.utils.PublicUtil; import com.bruceutils.utils.StorageUtil; import com.bruceutils.utils.logdetails.LogDetails; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.view.LayoutInflater; TextView tv1 = new TextView(getActivity()); tv1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); tv1.setText("Blue module"); tv1.setTextColor(getResources().getColor(android.R.color.holo_blue_dark)); linearLayout.addView(tv1); Button btn1 = new Button(getActivity()); btn1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn1.setText("获取当前屏幕亮度和模式"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showScreenModeandValue(); } }); linearLayout.addView(btn1); Button btn2 = new Button(getActivity()); btn2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn2.setText("开启新进程"); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startService(new Intent(getActivity(), KService.class));
getActivity().startService(new Intent(getActivity(), KDemonService.class));
BruceHurrican/asstudydemo
app/src/blue/java/com/bruce/demo/BlueFragment.java
// Path: app/src/blue/java/com/bruce/demo/demon/KDemonService.java // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public class KDemonService extends NotificationListenerService { // @Override // public void onNotificationPosted(StatusBarNotification sbn) { // // super.onNotificationPosted(sbn); // } // // @Override // public void onNotificationRemoved(StatusBarNotification sbn) { // // super.onNotificationRemoved(sbn); // } // } // // Path: app/src/blue/java/com/bruce/demo/demon/KService.java // public class KService extends Service { // private int a = 0; // // @Override // public void onCreate() { // super.onCreate(); // LogUtils.i("service create"); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // LogUtils.i("service start"); // new Thread(new Runnable() { // @Override // public void run() { // while (a < 100000) { // LogDetails.i("打印 %d 次", a); // a++; // } // } // }).start(); // return super.onStartCommand(intent, flags, startId); // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // } // // Path: app/src/blue/java/com/bruce/demo/keeplive/OnepxReceiver.java // public class OnepxReceiver extends BroadcastReceiver { // private static OnepxReceiver receiver; // // public static void register1pxReceiver(Context context) { // if (receiver == null) { // receiver = new OnepxReceiver(); // } // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); // } // // public static void unregister1pxReceiver(Context context) { // context.unregisterReceiver(receiver); // } // // @Override // public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { // Intent it = new Intent(context, OnepxActivity.class); // it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(it); // LogUtils.i("1px--screen off-"); // } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { // context.sendBroadcast(new Intent("finish activity")); // LogUtils.i("1px--screen on-"); // } // } // }
import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.bruce.demo.demon.KDemonService; import com.bruce.demo.demon.KService; import com.bruce.demo.keeplive.OnepxReceiver; import com.bruceutils.base.BaseFragment; import com.bruceutils.utils.PublicUtil; import com.bruceutils.utils.StorageUtil; import com.bruceutils.utils.logdetails.LogDetails; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.view.LayoutInflater;
public void onClick(View v) { getActivity().startService(new Intent(getActivity(), KService.class)); getActivity().startService(new Intent(getActivity(), KDemonService.class)); } }); linearLayout.addView(btn2); Button btn3 = new Button(getActivity()); btn3.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn3.setText("ping ip: 14.215.177.38"); // ping baidu ip btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PublicUtil.pingIpAddress("14.215.177.38"); LogDetails.i("获取SDCARD剩余存储空间" + StorageUtil.getAvailableExternalMemorySize (getActivity())); } }); linearLayout.addView(btn3); Button btn4 = new Button(getActivity()); btn4.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams .WRAP_CONTENT)); btn4.setText("启动1像素保活"); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
// Path: app/src/blue/java/com/bruce/demo/demon/KDemonService.java // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public class KDemonService extends NotificationListenerService { // @Override // public void onNotificationPosted(StatusBarNotification sbn) { // // super.onNotificationPosted(sbn); // } // // @Override // public void onNotificationRemoved(StatusBarNotification sbn) { // // super.onNotificationRemoved(sbn); // } // } // // Path: app/src/blue/java/com/bruce/demo/demon/KService.java // public class KService extends Service { // private int a = 0; // // @Override // public void onCreate() { // super.onCreate(); // LogUtils.i("service create"); // } // // @Override // public int onStartCommand(Intent intent, int flags, int startId) { // LogUtils.i("service start"); // new Thread(new Runnable() { // @Override // public void run() { // while (a < 100000) { // LogDetails.i("打印 %d 次", a); // a++; // } // } // }).start(); // return super.onStartCommand(intent, flags, startId); // } // // @Nullable // @Override // public IBinder onBind(Intent intent) { // return null; // } // } // // Path: app/src/blue/java/com/bruce/demo/keeplive/OnepxReceiver.java // public class OnepxReceiver extends BroadcastReceiver { // private static OnepxReceiver receiver; // // public static void register1pxReceiver(Context context) { // if (receiver == null) { // receiver = new OnepxReceiver(); // } // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); // context.registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_ON)); // } // // public static void unregister1pxReceiver(Context context) { // context.unregisterReceiver(receiver); // } // // @Override // public void onReceive(Context context, Intent intent) { // if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { // Intent it = new Intent(context, OnepxActivity.class); // it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(it); // LogUtils.i("1px--screen off-"); // } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { // context.sendBroadcast(new Intent("finish activity")); // LogUtils.i("1px--screen on-"); // } // } // } // Path: app/src/blue/java/com/bruce/demo/BlueFragment.java import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.bruce.demo.demon.KDemonService; import com.bruce.demo.demon.KService; import com.bruce.demo.keeplive.OnepxReceiver; import com.bruceutils.base.BaseFragment; import com.bruceutils.utils.PublicUtil; import com.bruceutils.utils.StorageUtil; import com.bruceutils.utils.logdetails.LogDetails; import android.content.Intent; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.Nullable; import android.view.LayoutInflater; public void onClick(View v) { getActivity().startService(new Intent(getActivity(), KService.class)); getActivity().startService(new Intent(getActivity(), KDemonService.class)); } }); linearLayout.addView(btn2); Button btn3 = new Button(getActivity()); btn3.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btn3.setText("ping ip: 14.215.177.38"); // ping baidu ip btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PublicUtil.pingIpAddress("14.215.177.38"); LogDetails.i("获取SDCARD剩余存储空间" + StorageUtil.getAvailableExternalMemorySize (getActivity())); } }); linearLayout.addView(btn3); Button btn4 = new Button(getActivity()); btn4.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams .WRAP_CONTENT)); btn4.setText("启动1像素保活"); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
OnepxReceiver.register1pxReceiver(getActivity());
BruceHurrican/asstudydemo
app/src/main/java/com/bruce/demo/social/qq/QQLoginAndShare.java
// Path: app/src/main/java/com/bruce/demo/social/ShareData.java // public class ShareData { // /** // * 分享标题 // */ // public String title; // /** // * 分享内容,QQ要求字符数不能超过50 // */ // public String content; // /** // * 用户点击后跳转的URL // */ // public String targetUrl; // /** // * 单个图片url,适用于QQ分享 // */ // public String imgUrl; // /** // * 图片url集合,适用于QQ空间分享,分享的图片在QQ空间上只显示imgList.get(0)的其余不显示 // */ // public ArrayList<String> imgList; // }
import com.bruce.demo.social.ShareData; import com.bruceutils.utils.LogUtils; import com.tencent.connect.common.Constants; import com.tencent.connect.share.QQShare; import com.tencent.connect.share.QzoneShare; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.Toast;
return instance; } public void init(String QQAppID, Activity context) { if (null == tencent) { tencent = Tencent.createInstance(QQAppID, context.getApplicationContext()); } this.context = context; } public void login(QQListener loginListener) { this.login(null, null, null, loginListener); } public void login(String token, String expires, String openId, QQListener loginListener) { if (null != tencent) { if (!tencent.isSessionValid()) { String scope = "all"; // 应用需要获得哪些API的权限,由“,”分隔。 例如:SCOPE =“get_user_info,add_t”;所有权限用“all” tencent.setAccessToken(token, expires); tencent.setOpenId(openId); tencent.login(context, scope, loginListener); } else { LogUtils.i("session 未过期"); } } else { LogUtils.e("tencent未初始化"); Toast.makeText(context, "tencent未初始化", Toast.LENGTH_SHORT).show(); } }
// Path: app/src/main/java/com/bruce/demo/social/ShareData.java // public class ShareData { // /** // * 分享标题 // */ // public String title; // /** // * 分享内容,QQ要求字符数不能超过50 // */ // public String content; // /** // * 用户点击后跳转的URL // */ // public String targetUrl; // /** // * 单个图片url,适用于QQ分享 // */ // public String imgUrl; // /** // * 图片url集合,适用于QQ空间分享,分享的图片在QQ空间上只显示imgList.get(0)的其余不显示 // */ // public ArrayList<String> imgList; // } // Path: app/src/main/java/com/bruce/demo/social/qq/QQLoginAndShare.java import com.bruce.demo.social.ShareData; import com.bruceutils.utils.LogUtils; import com.tencent.connect.common.Constants; import com.tencent.connect.share.QQShare; import com.tencent.connect.share.QzoneShare; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; return instance; } public void init(String QQAppID, Activity context) { if (null == tencent) { tencent = Tencent.createInstance(QQAppID, context.getApplicationContext()); } this.context = context; } public void login(QQListener loginListener) { this.login(null, null, null, loginListener); } public void login(String token, String expires, String openId, QQListener loginListener) { if (null != tencent) { if (!tencent.isSessionValid()) { String scope = "all"; // 应用需要获得哪些API的权限,由“,”分隔。 例如:SCOPE =“get_user_info,add_t”;所有权限用“all” tencent.setAccessToken(token, expires); tencent.setOpenId(openId); tencent.login(context, scope, loginListener); } else { LogUtils.i("session 未过期"); } } else { LogUtils.e("tencent未初始化"); Toast.makeText(context, "tencent未初始化", Toast.LENGTH_SHORT).show(); } }
public void qqShare(ShareData shareData, QQListener qqShareListener) {
BruceHurrican/asstudydemo
app/src/main/java/com/bruce/demo/mvp/presenter/CalculatePresenter.java
// Path: app/src/main/java/com/bruce/demo/mvp/model/CalculateTwoNumbers.java // public class CalculateTwoNumbers { // public int n1, n2; // // public int addResult() { // return n1 + n2; // } // // public int subtractResult() { // return n1 - n2; // } // // public int multiplyResult() { // return n1 * n2; // } // // public double divideResult() { // return n1 / n2; // } // } // // Path: app/src/main/java/com/bruce/demo/mvp/view/IResult.java // public interface IResult { // void showAdd(int result); // // void showSubtract(int result); // // void showMultiply(int result); // // void showDivide(double result); // }
import com.bruce.demo.mvp.model.CalculateTwoNumbers; import com.bruce.demo.mvp.view.IResult; import com.bruceutils.utils.LogUtils;
/* * BruceHurrican * Copyright (c) 2016. * 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. * * This document is Bruce's individual learning the android demo, wherein the use of the code from the Internet, only to use as a learning exchanges. * And where any person can download and use, but not for commercial purposes. * Author does not assume the resulting corresponding disputes. * If you have good suggestions for the code, you can contact BurrceHurrican@foxmail.com * 本文件为Bruce's个人学习android的demo, 其中所用到的代码来源于互联网,仅作为学习交流使用。 * 任和何人可以下载并使用, 但是不能用于商业用途。 * 作者不承担由此带来的相应纠纷。 * 如果对本代码有好的建议,可以联系BurrceHurrican@foxmail.com */ package com.bruce.demo.mvp.presenter; /** * Created by BruceHurrican on 16-3-23. */ public class CalculatePresenter implements ICalculate { private IResult iResult;
// Path: app/src/main/java/com/bruce/demo/mvp/model/CalculateTwoNumbers.java // public class CalculateTwoNumbers { // public int n1, n2; // // public int addResult() { // return n1 + n2; // } // // public int subtractResult() { // return n1 - n2; // } // // public int multiplyResult() { // return n1 * n2; // } // // public double divideResult() { // return n1 / n2; // } // } // // Path: app/src/main/java/com/bruce/demo/mvp/view/IResult.java // public interface IResult { // void showAdd(int result); // // void showSubtract(int result); // // void showMultiply(int result); // // void showDivide(double result); // } // Path: app/src/main/java/com/bruce/demo/mvp/presenter/CalculatePresenter.java import com.bruce.demo.mvp.model.CalculateTwoNumbers; import com.bruce.demo.mvp.view.IResult; import com.bruceutils.utils.LogUtils; /* * BruceHurrican * Copyright (c) 2016. * 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. * * This document is Bruce's individual learning the android demo, wherein the use of the code from the Internet, only to use as a learning exchanges. * And where any person can download and use, but not for commercial purposes. * Author does not assume the resulting corresponding disputes. * If you have good suggestions for the code, you can contact BurrceHurrican@foxmail.com * 本文件为Bruce's个人学习android的demo, 其中所用到的代码来源于互联网,仅作为学习交流使用。 * 任和何人可以下载并使用, 但是不能用于商业用途。 * 作者不承担由此带来的相应纠纷。 * 如果对本代码有好的建议,可以联系BurrceHurrican@foxmail.com */ package com.bruce.demo.mvp.presenter; /** * Created by BruceHurrican on 16-3-23. */ public class CalculatePresenter implements ICalculate { private IResult iResult;
private CalculateTwoNumbers calculateTwoNumbers;
BruceHurrican/asstudydemo
app/src/blue/java/com/bruce/demo/BlueManager.java
// Path: app/src/blue/java/com/bruce/demo/net/RetrofitDemo.java // public class RetrofitDemo { // public void doRetrofit() { // String url = "http://10.180.184.14:8080"; // Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory // (GsonConverterFactory.create()).client(new OkHttpClient.Builder().addInterceptor // (new Interceptor() { // @Override // public okhttp3.Response intercept(Chain chain) throws IOException { // Request request = chain.request().newBuilder().addHeader("a1", "A").addHeader // ("device", "mac").build(); // return chain.proceed(request); // } // }).build()).build(); // Call<ApkModel> call = retrofit.create(IGetData.class).getData(); // call.enqueue(new Callback<ApkModel>() { // @Override // public void onResponse(Call<ApkModel> call, Response<ApkModel> response) { // LogDetails.d("call is cancelled ? " + call.isCanceled()); // LogDetails.d(response); // } // // @Override // public void onFailure(Call<ApkModel> call, Throwable t) { // LogDetails.d("call is cancelled ? " + call.isCanceled()); // LogDetails.d("网络请求失败"); // } // }); // } // // public void doRx() { // String url = "http://10.180.184.14:8080"; // Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory // (GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory // .create()).client(new OkHttpClient.Builder().addInterceptor(new Interceptor() { // @Override // public okhttp3.Response intercept(Chain chain) throws IOException { // Request request = chain.request().newBuilder().addHeader("a1", "A").addHeader // ("device", "mac").build(); // return chain.proceed(request); // } // }).build()).build(); // APIService apiService = retrofit.create(APIService.class); // apiService.getData().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread // ()).subscribe(new Subscriber<ApkModel>() { // @Override // public void onCompleted() { // LogDetails.d("请求成功"); // } // // @Override // public void onError(Throwable throwable) { // LogDetails.d("失败"); // // } // // @Override // public void onNext(ApkModel apkModel) { // LogDetails.d("获取数据"); // LogDetails.d(apkModel); // // } // }); // } // }
import android.app.Activity; import android.content.Intent; import com.bruce.demo.net.RetrofitDemo; import com.bruceutils.utils.logdetails.LogDetails;
/* * BruceHurrican * Copyright (c) 2016. * 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. * * This document is Bruce's individual learning the android demo, wherein the use of the code from the Internet, only to use as a learning exchanges. * And where any person can download and use, but not for commercial purposes. * Author does not assume the resulting corresponding disputes. * If you have good suggestions for the code, you can contact BurrceHurrican@foxmail.com * 本文件为Bruce's个人学习android的作品, 其中所用到的代码来源于互联网,仅作为学习交流使用。 * 任和何人可以下载并使用, 但是不能用于商业用途。 * 作者不承担由此带来的相应纠纷。 * 如果对本代码有好的建议,可以联系BurrceHurrican@foxmail.com */ package com.bruce.demo; /** * blue 模块入口控制 * Created by BruceHurrican on 17/1/5. */ public class BlueManager { private static BlueManager instance; private BlueManager() { } public static BlueManager getInstance() { return Holder.INSTANCE; } public void init() { LogDetails.getLogConfig().configTagPrefix("BLUE").configShowBorders(true); LogDetails.d("blue module init success"); } public void showRetrofit() {
// Path: app/src/blue/java/com/bruce/demo/net/RetrofitDemo.java // public class RetrofitDemo { // public void doRetrofit() { // String url = "http://10.180.184.14:8080"; // Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory // (GsonConverterFactory.create()).client(new OkHttpClient.Builder().addInterceptor // (new Interceptor() { // @Override // public okhttp3.Response intercept(Chain chain) throws IOException { // Request request = chain.request().newBuilder().addHeader("a1", "A").addHeader // ("device", "mac").build(); // return chain.proceed(request); // } // }).build()).build(); // Call<ApkModel> call = retrofit.create(IGetData.class).getData(); // call.enqueue(new Callback<ApkModel>() { // @Override // public void onResponse(Call<ApkModel> call, Response<ApkModel> response) { // LogDetails.d("call is cancelled ? " + call.isCanceled()); // LogDetails.d(response); // } // // @Override // public void onFailure(Call<ApkModel> call, Throwable t) { // LogDetails.d("call is cancelled ? " + call.isCanceled()); // LogDetails.d("网络请求失败"); // } // }); // } // // public void doRx() { // String url = "http://10.180.184.14:8080"; // Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory // (GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory // .create()).client(new OkHttpClient.Builder().addInterceptor(new Interceptor() { // @Override // public okhttp3.Response intercept(Chain chain) throws IOException { // Request request = chain.request().newBuilder().addHeader("a1", "A").addHeader // ("device", "mac").build(); // return chain.proceed(request); // } // }).build()).build(); // APIService apiService = retrofit.create(APIService.class); // apiService.getData().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread // ()).subscribe(new Subscriber<ApkModel>() { // @Override // public void onCompleted() { // LogDetails.d("请求成功"); // } // // @Override // public void onError(Throwable throwable) { // LogDetails.d("失败"); // // } // // @Override // public void onNext(ApkModel apkModel) { // LogDetails.d("获取数据"); // LogDetails.d(apkModel); // // } // }); // } // } // Path: app/src/blue/java/com/bruce/demo/BlueManager.java import android.app.Activity; import android.content.Intent; import com.bruce.demo.net.RetrofitDemo; import com.bruceutils.utils.logdetails.LogDetails; /* * BruceHurrican * Copyright (c) 2016. * 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. * * This document is Bruce's individual learning the android demo, wherein the use of the code from the Internet, only to use as a learning exchanges. * And where any person can download and use, but not for commercial purposes. * Author does not assume the resulting corresponding disputes. * If you have good suggestions for the code, you can contact BurrceHurrican@foxmail.com * 本文件为Bruce's个人学习android的作品, 其中所用到的代码来源于互联网,仅作为学习交流使用。 * 任和何人可以下载并使用, 但是不能用于商业用途。 * 作者不承担由此带来的相应纠纷。 * 如果对本代码有好的建议,可以联系BurrceHurrican@foxmail.com */ package com.bruce.demo; /** * blue 模块入口控制 * Created by BruceHurrican on 17/1/5. */ public class BlueManager { private static BlueManager instance; private BlueManager() { } public static BlueManager getInstance() { return Holder.INSTANCE; } public void init() { LogDetails.getLogConfig().configTagPrefix("BLUE").configShowBorders(true); LogDetails.d("blue module init success"); } public void showRetrofit() {
RetrofitDemo demo = new RetrofitDemo();
BruceHurrican/asstudydemo
app/src/main/java/com/bruce/demo/studydata/game/gamepuzzle/adapter/GridPicListAdapter.java
// Path: app/src/main/java/com/bruce/demo/studydata/game/gamepuzzle/util/ScreenUtil.java // public class ScreenUtil { // // /** // * 获取屏幕相关参数 // * // * @param context context // * @return DisplayMetrics 屏幕宽高 // */ // public static DisplayMetrics getScreenSize(Context context) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = wm.getDefaultDisplay(); // display.getMetrics(metrics); // return metrics; // } // // /** // * 获取屏幕density // * // * @param context context // * @return density 屏幕density // */ // public static float getDeviceDensity(Context context) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // wm.getDefaultDisplay().getMetrics(metrics); // return metrics.density; // } // }
import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import com.bruce.demo.studydata.game.gamepuzzle.util.ScreenUtil; import java.util.List; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.view.View; import android.view.ViewGroup;
/* * BruceHurrican * Copyright (c) 2016. * 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. * * This document is Bruce's individual learning the android demo, wherein the use of the code from the Internet, only to use as a learning exchanges. * And where any person can download and use, but not for commercial purposes. * Author does not assume the resulting corresponding disputes. * If you have good suggestions for the code, you can contact BurrceHurrican@foxmail.com * 本文件为Bruce's个人学习android的demo, 其中所用到的代码来源于互联网,仅作为学习交流使用。 * 任和何人可以下载并使用, 但是不能用于商业用途。 * 作者不承担由此带来的相应纠纷。 * 如果对本代码有好的建议,可以联系BurrceHurrican@foxmail.com */ package com.bruce.demo.studydata.game.gamepuzzle.adapter; /** * 程序主界面数据适配器 * * @author xys */ public class GridPicListAdapter extends BaseAdapter { // 映射List private List<Bitmap> picList; private Context context; public GridPicListAdapter(Context context, List<Bitmap> picList) { this.context = context; this.picList = picList; } @Override public int getCount() { return picList.size(); } @Override public Object getItem(int position) { return picList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup arg2) { ImageView iv_pic_item = null;
// Path: app/src/main/java/com/bruce/demo/studydata/game/gamepuzzle/util/ScreenUtil.java // public class ScreenUtil { // // /** // * 获取屏幕相关参数 // * // * @param context context // * @return DisplayMetrics 屏幕宽高 // */ // public static DisplayMetrics getScreenSize(Context context) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = wm.getDefaultDisplay(); // display.getMetrics(metrics); // return metrics; // } // // /** // * 获取屏幕density // * // * @param context context // * @return density 屏幕density // */ // public static float getDeviceDensity(Context context) { // DisplayMetrics metrics = new DisplayMetrics(); // WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // wm.getDefaultDisplay().getMetrics(metrics); // return metrics.density; // } // } // Path: app/src/main/java/com/bruce/demo/studydata/game/gamepuzzle/adapter/GridPicListAdapter.java import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import com.bruce.demo.studydata.game.gamepuzzle.util.ScreenUtil; import java.util.List; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; /* * BruceHurrican * Copyright (c) 2016. * 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. * * This document is Bruce's individual learning the android demo, wherein the use of the code from the Internet, only to use as a learning exchanges. * And where any person can download and use, but not for commercial purposes. * Author does not assume the resulting corresponding disputes. * If you have good suggestions for the code, you can contact BurrceHurrican@foxmail.com * 本文件为Bruce's个人学习android的demo, 其中所用到的代码来源于互联网,仅作为学习交流使用。 * 任和何人可以下载并使用, 但是不能用于商业用途。 * 作者不承担由此带来的相应纠纷。 * 如果对本代码有好的建议,可以联系BurrceHurrican@foxmail.com */ package com.bruce.demo.studydata.game.gamepuzzle.adapter; /** * 程序主界面数据适配器 * * @author xys */ public class GridPicListAdapter extends BaseAdapter { // 映射List private List<Bitmap> picList; private Context context; public GridPicListAdapter(Context context, List<Bitmap> picList) { this.context = context; this.picList = picList; } @Override public int getCount() { return picList.size(); } @Override public Object getItem(int position) { return picList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup arg2) { ImageView iv_pic_item = null;
int density = (int) ScreenUtil.getDeviceDensity(context);
portablejim/VeinMiner
src/main/java/portablejim/veinminer/configuration/ConfigurationSettings.java
// Path: src/main/java/portablejim/veinminer/configuration/json/ToolStruct.java // public class ToolStruct { // public String name; // public String icon; // public String[] toollist; // public String[] blocklist; // } // // Path: src/main/java/portablejim/veinminer/util/BlockID.java // public class BlockID implements Comparable<BlockID> // { // public String name; // public int metadata; // public IBlockState state = null; // // public BlockID(String fullDescription) { // int preMeta = -1; // Pattern p = Pattern.compile("([^/]+)(?:/([-]?\\d{1,2}))?"); // Matcher m = p.matcher(fullDescription); // // if(m.matches()) { // name = m.group(1); // if(m.group(2) != null) { // try { // preMeta = Integer.parseInt(m.group(2)); // } // catch (NumberFormatException e) { // preMeta = -1; // } // } // } // else { // name = ""; // } // metadata = preMeta >= -1 ? preMeta : -1; // } // // public BlockID(String name, int meta) { // this.name = name; // this.metadata = meta < -1 || meta == OreDictionary.WILDCARD_VALUE ? -1 : meta; // } // // @Deprecated // public BlockID(World world, BlockPos position) { // this(world.getBlockState(position)); // } // // public BlockID(IBlockState state) { // this(Block.blockRegistry.getNameForObject(state.getBlock()).toString(), state.getBlock().getMetaFromState(state)); // this.state = state; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // return name.equals(o.name) && metadata == o.metadata; // } // // /** // * Compare the objects using the metadata value of -1 to be a wildcard that matches all. // * @param obj The object to compare to this one // * @return Whether this object and obj are equal, using the wildcard value. // */ // public boolean wildcardEquals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // if (o.metadata == -1 || metadata == -1) // return this.equals(obj); // else // return name.equals(o.name) && metadata == o.metadata; // } // // @Override // public int hashCode() // { // return (this.name.hashCode() << 6) + this.metadata; // } // // @Override // public String toString() // { // return (metadata == -1 ? name + "" : name + "/" + metadata); // } // // @Override // public int compareTo(BlockID blockID) { // if(name != null && !name.equals(blockID.name)) { // int result = name.compareTo(blockID.name); // if(result > 0) return 1; // else if (result < 0) return -1; // return 0; // } // else if(metadata < blockID.metadata) { // return -1; // } // else if(metadata > blockID.metadata) { // return 1; // } // else { // return 0; // } // } // } // // Path: src/main/java/portablejim/veinminer/util/PreferredMode.java // public class PreferredMode { // public static final int DISABLED = 0; // public static final int PRESSED = 1; // public static final int RELEASED = 2; // public static final int SNEAK_ACTIVE = 3; // public static final int SNEAK_INACTIVE = 4; // // public static int length() { // return 5; // } // }
import com.google.common.base.Joiner; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import portablejim.veinminer.configuration.json.ToolStruct; import portablejim.veinminer.util.BlockID; import portablejim.veinminer.util.PreferredMode; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set;
/* This file is part of VeinMiner. * * VeinMiner is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * VeinMiner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with VeinMiner. * If not, see <http://www.gnu.org/licenses/>. */ package portablejim.veinminer.configuration; /** * Class to manage the config settings. It takes the raw values from * ConfigurationValues and stores the settings in much more useful types * and provides methods to retrieve the settings. */ public class ConfigurationSettings { private ConfigurationValues configValues; public ConfigurationSettings(ConfigurationValues configValues) { this.configValues = configValues; autoDetectBlocksToggle = new boolean[ToolType.values().length]; //noinspection unchecked autoDetectBlocksList = new HashSet[ToolType.values().length]; for (ToolType tool : ToolType.values()) { autoDetectBlocksToggle[tool.ordinal()] = false; autoDetectBlocksList[tool.ordinal()] = new HashSet<String>(); }
// Path: src/main/java/portablejim/veinminer/configuration/json/ToolStruct.java // public class ToolStruct { // public String name; // public String icon; // public String[] toollist; // public String[] blocklist; // } // // Path: src/main/java/portablejim/veinminer/util/BlockID.java // public class BlockID implements Comparable<BlockID> // { // public String name; // public int metadata; // public IBlockState state = null; // // public BlockID(String fullDescription) { // int preMeta = -1; // Pattern p = Pattern.compile("([^/]+)(?:/([-]?\\d{1,2}))?"); // Matcher m = p.matcher(fullDescription); // // if(m.matches()) { // name = m.group(1); // if(m.group(2) != null) { // try { // preMeta = Integer.parseInt(m.group(2)); // } // catch (NumberFormatException e) { // preMeta = -1; // } // } // } // else { // name = ""; // } // metadata = preMeta >= -1 ? preMeta : -1; // } // // public BlockID(String name, int meta) { // this.name = name; // this.metadata = meta < -1 || meta == OreDictionary.WILDCARD_VALUE ? -1 : meta; // } // // @Deprecated // public BlockID(World world, BlockPos position) { // this(world.getBlockState(position)); // } // // public BlockID(IBlockState state) { // this(Block.blockRegistry.getNameForObject(state.getBlock()).toString(), state.getBlock().getMetaFromState(state)); // this.state = state; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // return name.equals(o.name) && metadata == o.metadata; // } // // /** // * Compare the objects using the metadata value of -1 to be a wildcard that matches all. // * @param obj The object to compare to this one // * @return Whether this object and obj are equal, using the wildcard value. // */ // public boolean wildcardEquals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // if (o.metadata == -1 || metadata == -1) // return this.equals(obj); // else // return name.equals(o.name) && metadata == o.metadata; // } // // @Override // public int hashCode() // { // return (this.name.hashCode() << 6) + this.metadata; // } // // @Override // public String toString() // { // return (metadata == -1 ? name + "" : name + "/" + metadata); // } // // @Override // public int compareTo(BlockID blockID) { // if(name != null && !name.equals(blockID.name)) { // int result = name.compareTo(blockID.name); // if(result > 0) return 1; // else if (result < 0) return -1; // return 0; // } // else if(metadata < blockID.metadata) { // return -1; // } // else if(metadata > blockID.metadata) { // return 1; // } // else { // return 0; // } // } // } // // Path: src/main/java/portablejim/veinminer/util/PreferredMode.java // public class PreferredMode { // public static final int DISABLED = 0; // public static final int PRESSED = 1; // public static final int RELEASED = 2; // public static final int SNEAK_ACTIVE = 3; // public static final int SNEAK_INACTIVE = 4; // // public static int length() { // return 5; // } // } // Path: src/main/java/portablejim/veinminer/configuration/ConfigurationSettings.java import com.google.common.base.Joiner; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import portablejim.veinminer.configuration.json.ToolStruct; import portablejim.veinminer.util.BlockID; import portablejim.veinminer.util.PreferredMode; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /* This file is part of VeinMiner. * * VeinMiner is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * VeinMiner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with VeinMiner. * If not, see <http://www.gnu.org/licenses/>. */ package portablejim.veinminer.configuration; /** * Class to manage the config settings. It takes the raw values from * ConfigurationValues and stores the settings in much more useful types * and provides methods to retrieve the settings. */ public class ConfigurationSettings { private ConfigurationValues configValues; public ConfigurationSettings(ConfigurationValues configValues) { this.configValues = configValues; autoDetectBlocksToggle = new boolean[ToolType.values().length]; //noinspection unchecked autoDetectBlocksList = new HashSet[ToolType.values().length]; for (ToolType tool : ToolType.values()) { autoDetectBlocksToggle[tool.ordinal()] = false; autoDetectBlocksList[tool.ordinal()] = new HashSet<String>(); }
blockCongruenceList = new ArrayList<Set<BlockID>>();
portablejim/VeinMiner
src/main/java/portablejim/veinminer/configuration/ConfigurationSettings.java
// Path: src/main/java/portablejim/veinminer/configuration/json/ToolStruct.java // public class ToolStruct { // public String name; // public String icon; // public String[] toollist; // public String[] blocklist; // } // // Path: src/main/java/portablejim/veinminer/util/BlockID.java // public class BlockID implements Comparable<BlockID> // { // public String name; // public int metadata; // public IBlockState state = null; // // public BlockID(String fullDescription) { // int preMeta = -1; // Pattern p = Pattern.compile("([^/]+)(?:/([-]?\\d{1,2}))?"); // Matcher m = p.matcher(fullDescription); // // if(m.matches()) { // name = m.group(1); // if(m.group(2) != null) { // try { // preMeta = Integer.parseInt(m.group(2)); // } // catch (NumberFormatException e) { // preMeta = -1; // } // } // } // else { // name = ""; // } // metadata = preMeta >= -1 ? preMeta : -1; // } // // public BlockID(String name, int meta) { // this.name = name; // this.metadata = meta < -1 || meta == OreDictionary.WILDCARD_VALUE ? -1 : meta; // } // // @Deprecated // public BlockID(World world, BlockPos position) { // this(world.getBlockState(position)); // } // // public BlockID(IBlockState state) { // this(Block.blockRegistry.getNameForObject(state.getBlock()).toString(), state.getBlock().getMetaFromState(state)); // this.state = state; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // return name.equals(o.name) && metadata == o.metadata; // } // // /** // * Compare the objects using the metadata value of -1 to be a wildcard that matches all. // * @param obj The object to compare to this one // * @return Whether this object and obj are equal, using the wildcard value. // */ // public boolean wildcardEquals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // if (o.metadata == -1 || metadata == -1) // return this.equals(obj); // else // return name.equals(o.name) && metadata == o.metadata; // } // // @Override // public int hashCode() // { // return (this.name.hashCode() << 6) + this.metadata; // } // // @Override // public String toString() // { // return (metadata == -1 ? name + "" : name + "/" + metadata); // } // // @Override // public int compareTo(BlockID blockID) { // if(name != null && !name.equals(blockID.name)) { // int result = name.compareTo(blockID.name); // if(result > 0) return 1; // else if (result < 0) return -1; // return 0; // } // else if(metadata < blockID.metadata) { // return -1; // } // else if(metadata > blockID.metadata) { // return 1; // } // else { // return 0; // } // } // } // // Path: src/main/java/portablejim/veinminer/util/PreferredMode.java // public class PreferredMode { // public static final int DISABLED = 0; // public static final int PRESSED = 1; // public static final int RELEASED = 2; // public static final int SNEAK_ACTIVE = 3; // public static final int SNEAK_INACTIVE = 4; // // public static int length() { // return 5; // } // }
import com.google.common.base.Joiner; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import portablejim.veinminer.configuration.json.ToolStruct; import portablejim.veinminer.util.BlockID; import portablejim.veinminer.util.PreferredMode; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set;
private int experienceModifier; public int getHungerMultiplier() { return hungerModifier; } public void setHungerModifier(int hungerModifier) { this.hungerModifier = hungerModifier < 0 ? 0 : hungerModifier; } public int getExperienceMultiplier() { return experienceModifier; } public void setExperienceModifier(int experienceModifier) { this.experienceModifier = experienceModifier < 0 ? 0 : experienceModifier; } public boolean toolIsOfType(ItemStack tool, String type) { return tool == null || toolsAndBlocks.get(type).toollist.contains(Item.itemRegistry.getNameForObject(tool.getItem()).toString()); } /** * Sets the preferred mode to the modeString if valid or fallback if modeString is not valid * @param modeString one of 'auto', 'sneak', 'no_sneak' * @param fallback one of 'auto', 'sneak', 'no_sneak' * @return If modestring is valid */ boolean setPreferredMode(String modeString, String fallback) { if("disabled".equals(modeString)) {
// Path: src/main/java/portablejim/veinminer/configuration/json/ToolStruct.java // public class ToolStruct { // public String name; // public String icon; // public String[] toollist; // public String[] blocklist; // } // // Path: src/main/java/portablejim/veinminer/util/BlockID.java // public class BlockID implements Comparable<BlockID> // { // public String name; // public int metadata; // public IBlockState state = null; // // public BlockID(String fullDescription) { // int preMeta = -1; // Pattern p = Pattern.compile("([^/]+)(?:/([-]?\\d{1,2}))?"); // Matcher m = p.matcher(fullDescription); // // if(m.matches()) { // name = m.group(1); // if(m.group(2) != null) { // try { // preMeta = Integer.parseInt(m.group(2)); // } // catch (NumberFormatException e) { // preMeta = -1; // } // } // } // else { // name = ""; // } // metadata = preMeta >= -1 ? preMeta : -1; // } // // public BlockID(String name, int meta) { // this.name = name; // this.metadata = meta < -1 || meta == OreDictionary.WILDCARD_VALUE ? -1 : meta; // } // // @Deprecated // public BlockID(World world, BlockPos position) { // this(world.getBlockState(position)); // } // // public BlockID(IBlockState state) { // this(Block.blockRegistry.getNameForObject(state.getBlock()).toString(), state.getBlock().getMetaFromState(state)); // this.state = state; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // return name.equals(o.name) && metadata == o.metadata; // } // // /** // * Compare the objects using the metadata value of -1 to be a wildcard that matches all. // * @param obj The object to compare to this one // * @return Whether this object and obj are equal, using the wildcard value. // */ // public boolean wildcardEquals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // if (o.metadata == -1 || metadata == -1) // return this.equals(obj); // else // return name.equals(o.name) && metadata == o.metadata; // } // // @Override // public int hashCode() // { // return (this.name.hashCode() << 6) + this.metadata; // } // // @Override // public String toString() // { // return (metadata == -1 ? name + "" : name + "/" + metadata); // } // // @Override // public int compareTo(BlockID blockID) { // if(name != null && !name.equals(blockID.name)) { // int result = name.compareTo(blockID.name); // if(result > 0) return 1; // else if (result < 0) return -1; // return 0; // } // else if(metadata < blockID.metadata) { // return -1; // } // else if(metadata > blockID.metadata) { // return 1; // } // else { // return 0; // } // } // } // // Path: src/main/java/portablejim/veinminer/util/PreferredMode.java // public class PreferredMode { // public static final int DISABLED = 0; // public static final int PRESSED = 1; // public static final int RELEASED = 2; // public static final int SNEAK_ACTIVE = 3; // public static final int SNEAK_INACTIVE = 4; // // public static int length() { // return 5; // } // } // Path: src/main/java/portablejim/veinminer/configuration/ConfigurationSettings.java import com.google.common.base.Joiner; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import portablejim.veinminer.configuration.json.ToolStruct; import portablejim.veinminer.util.BlockID; import portablejim.veinminer.util.PreferredMode; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; private int experienceModifier; public int getHungerMultiplier() { return hungerModifier; } public void setHungerModifier(int hungerModifier) { this.hungerModifier = hungerModifier < 0 ? 0 : hungerModifier; } public int getExperienceMultiplier() { return experienceModifier; } public void setExperienceModifier(int experienceModifier) { this.experienceModifier = experienceModifier < 0 ? 0 : experienceModifier; } public boolean toolIsOfType(ItemStack tool, String type) { return tool == null || toolsAndBlocks.get(type).toollist.contains(Item.itemRegistry.getNameForObject(tool.getItem()).toString()); } /** * Sets the preferred mode to the modeString if valid or fallback if modeString is not valid * @param modeString one of 'auto', 'sneak', 'no_sneak' * @param fallback one of 'auto', 'sneak', 'no_sneak' * @return If modestring is valid */ boolean setPreferredMode(String modeString, String fallback) { if("disabled".equals(modeString)) {
preferredMode = PreferredMode.DISABLED;
portablejim/VeinMiner
src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // }
import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance;
event.getModLog().error("Error writing config file"); } } @SuppressWarnings("unused") @EventHandler public void init(@SuppressWarnings("UnusedParameters") FMLInitializationEvent event) { MinecraftForge.EVENT_BUS.register(this); ModContainer thisMod = Loader.instance().getIndexedModList().get(ModInfo.MOD_ID); if(thisMod != null) { String fileName = thisMod.getSource().getName(); if(fileName.contains("-dev") || !fileName.contains(".jar")) { debugMode = true; devLog("DEV VERSION"); } } forceConsumerAvailable = false; if(AUTODETECT_TOOLS_TOGGLE) { addTools(); } } private void addTools() { if(Loader.isModLoaded("tconstruct")) { devLog("Tinkers support loaded"); } if(Loader.isModLoaded("exnihilo")) { devLog("Ex Nihilo support loaded");
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // } // Path: src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance; event.getModLog().error("Error writing config file"); } } @SuppressWarnings("unused") @EventHandler public void init(@SuppressWarnings("UnusedParameters") FMLInitializationEvent event) { MinecraftForge.EVENT_BUS.register(this); ModContainer thisMod = Loader.instance().getIndexedModList().get(ModInfo.MOD_ID); if(thisMod != null) { String fileName = thisMod.getSource().getName(); if(fileName.contains("-dev") || !fileName.contains(".jar")) { debugMode = true; devLog("DEV VERSION"); } } forceConsumerAvailable = false; if(AUTODETECT_TOOLS_TOGGLE) { addTools(); } } private void addTools() { if(Loader.isModLoaded("tconstruct")) { devLog("Tinkers support loaded"); } if(Loader.isModLoaded("exnihilo")) { devLog("Ex Nihilo support loaded");
IMCMessage.addToolType("crook", "Crook", "exnihilo:crook");
portablejim/VeinMiner
src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // }
import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance;
} } @SuppressWarnings("UnusedDeclaration") @EventHandler public void postInit(FMLPostInitializationEvent event) { if(Loader.isModLoaded("DartCraft")) { devLog("Testing for dartcraft classes and functions."); try { Object obj = Class.forName("bluedart.api.IForceConsumer").getMethod("attemptRepair", ItemStack.class); // Class present. forceConsumerAvailable = true; } catch (ClassNotFoundException e) { devLog("Failed to find Dartcraft force consumer. Disabling repair support"); } catch (NoSuchMethodException e) { devLog("Failed to find Dartcraft force consumer function. Disabling repair support"); } } } private void devLog(String string) { if(debugMode) { FMLLog.getLogger().info("[" + ModInfo.MOD_ID + "] " + string); } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // } // Path: src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance; } } @SuppressWarnings("UnusedDeclaration") @EventHandler public void postInit(FMLPostInitializationEvent event) { if(Loader.isModLoaded("DartCraft")) { devLog("Testing for dartcraft classes and functions."); try { Object obj = Class.forName("bluedart.api.IForceConsumer").getMethod("attemptRepair", ItemStack.class); // Class present. forceConsumerAvailable = true; } catch (ClassNotFoundException e) { devLog("Failed to find Dartcraft force consumer. Disabling repair support"); } catch (NoSuchMethodException e) { devLog("Failed to find Dartcraft force consumer function. Disabling repair support"); } } } private void devLog(String string) { if(debugMode) { FMLLog.getLogger().info("[" + ModInfo.MOD_ID + "] " + string); } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent
public void banBadTools(VeinminerHarvestFailedCheck event) {
portablejim/VeinMiner
src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // }
import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance;
public void postInit(FMLPostInitializationEvent event) { if(Loader.isModLoaded("DartCraft")) { devLog("Testing for dartcraft classes and functions."); try { Object obj = Class.forName("bluedart.api.IForceConsumer").getMethod("attemptRepair", ItemStack.class); // Class present. forceConsumerAvailable = true; } catch (ClassNotFoundException e) { devLog("Failed to find Dartcraft force consumer. Disabling repair support"); } catch (NoSuchMethodException e) { devLog("Failed to find Dartcraft force consumer function. Disabling repair support"); } } } private void devLog(String string) { if(debugMode) { FMLLog.getLogger().info("[" + ModInfo.MOD_ID + "] " + string); } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent public void banBadTools(VeinminerHarvestFailedCheck event) { ItemStack currentEquipped = event.player.getHeldItemMainhand(); if(currentEquipped != null && currentEquipped.getItem() != null && Item.itemRegistry.getNameForObject(currentEquipped.getItem()) != null) { String item_name = Item.itemRegistry.getNameForObject(currentEquipped.getItem()).toString(); if(badTools.contains(item_name)) {
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // } // Path: src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance; public void postInit(FMLPostInitializationEvent event) { if(Loader.isModLoaded("DartCraft")) { devLog("Testing for dartcraft classes and functions."); try { Object obj = Class.forName("bluedart.api.IForceConsumer").getMethod("attemptRepair", ItemStack.class); // Class present. forceConsumerAvailable = true; } catch (ClassNotFoundException e) { devLog("Failed to find Dartcraft force consumer. Disabling repair support"); } catch (NoSuchMethodException e) { devLog("Failed to find Dartcraft force consumer function. Disabling repair support"); } } } private void devLog(String string) { if(debugMode) { FMLLog.getLogger().info("[" + ModInfo.MOD_ID + "] " + string); } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent public void banBadTools(VeinminerHarvestFailedCheck event) { ItemStack currentEquipped = event.player.getHeldItemMainhand(); if(currentEquipped != null && currentEquipped.getItem() != null && Item.itemRegistry.getNameForObject(currentEquipped.getItem()) != null) { String item_name = Item.itemRegistry.getNameForObject(currentEquipped.getItem()).toString(); if(badTools.contains(item_name)) {
event.allowContinue = Permission.FORCE_DENY;
portablejim/VeinMiner
src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // }
import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance;
if(currentEquipped != null && currentEquipped.getItem() != null && Item.itemRegistry.getNameForObject(currentEquipped.getItem()) != null) { String item_name = Item.itemRegistry.getNameForObject(currentEquipped.getItem()).toString(); if(badTools.contains(item_name)) { event.allowContinue = Permission.FORCE_DENY; } } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent public void makeToolsWork(VeinminerHarvestFailedCheck event) { ItemStack currentEquipped = event.player.getHeldItemMainhand(); if(currentEquipped == null) { return; } if(event.allowContinue == Permission.DENY) { if(overrideBlacklist.contains(event.blockName)) { devLog("Denied with block: " + event.blockName); event.allowContinue = Permission.FORCE_DENY; } else { devLog("Not Denied with block: " + event.blockName); } } Item currentEquippedItem = event.player.getHeldItemMainhand().getItem(); if(Loader.isModLoaded("DartCraft")) { devLog("Dartcraft detected");
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // } // Path: src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance; if(currentEquipped != null && currentEquipped.getItem() != null && Item.itemRegistry.getNameForObject(currentEquipped.getItem()) != null) { String item_name = Item.itemRegistry.getNameForObject(currentEquipped.getItem()).toString(); if(badTools.contains(item_name)) { event.allowContinue = Permission.FORCE_DENY; } } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent public void makeToolsWork(VeinminerHarvestFailedCheck event) { ItemStack currentEquipped = event.player.getHeldItemMainhand(); if(currentEquipped == null) { return; } if(event.allowContinue == Permission.DENY) { if(overrideBlacklist.contains(event.blockName)) { devLog("Denied with block: " + event.blockName); event.allowContinue = Permission.FORCE_DENY; } else { devLog("Not Denied with block: " + event.blockName); } } Item currentEquippedItem = event.player.getHeldItemMainhand().getItem(); if(Loader.isModLoaded("DartCraft")) { devLog("Dartcraft detected");
if(currentEquippedItem instanceof IBreakable && event.allowContinue == Permission.DENY) {
portablejim/VeinMiner
src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // }
import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance;
if(block == null) { devLog("ERROR: Block id wrong."); return; } /*if(toolTags.hasKey("Broken")) { devLog("DENY: Tool broken"); if(event.allowContinue == Permission.ALLOW) { event.allowContinue = Permission.DENY; } return; }*/ devLog("Allowing event"); if(event.allowContinue == Permission.DENY) { event.allowContinue = Permission.ALLOW; } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent public void fixFalseNegatives(VeinminerHarvestFailedCheck event) { // Some blocks return false when they shouldn't. if(event.allowContinue == Permission.DENY) { if("IC2:blockRubWood".equals(event.blockName)) event.allowContinue = Permission.ALLOW; } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent
// Path: src/api/java/bluedart/api/IBreakable.java // public abstract interface IBreakable { // } // // Path: src/main/java/portablejim/veinminer/api/IMCMessage.java // @SuppressWarnings("UnusedDeclaration") // public class IMCMessage { // public static void addTool(String type, String itemName) { // sendWhitelistMessage("item", type, itemName); // } // // public static void addBlock(String type, String blockName) { // sendWhitelistMessage("block", type, blockName); // } // // private static void sendWhitelistMessage(String itemType, String toolType, String blockName) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("whitelistType", itemType); // message.setString("toolType", toolType); // message.setString("blockName", blockName); // FMLInterModComms.sendMessage("VeinMiner", "whitelist", message); // } // // public static void addToolType(String type, String name, String icon) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("toolType", type); // message.setString("toolName", name); // message.setString("toolIcon", icon); // FMLInterModComms.sendMessage("VeinMiner", "addTool", message); // } // // public static void addBlockEquivalence(String existingBlock, String newBlock) { // NBTTagCompound message = new NBTTagCompound(); // message.setString("existingBlock", existingBlock); // message.setString("newBlock", newBlock); // FMLInterModComms.sendMessage("VeinMiner", "addEqualBlocks", message); // } // } // // Path: src/main/java/portablejim/veinminer/api/Permission.java // public enum Permission { // FORCE_ALLOW, // ALLOW, // DENY, // FORCE_DENY; // // public boolean isAllowed() { // return this == ALLOW || this == FORCE_ALLOW; // } // // public boolean isDenied() { // return this == DENY || this == FORCE_DENY; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerHarvestFailedCheck.java // public class VeinminerHarvestFailedCheck extends Event { // public Permission allowContinue; // public final EntityPlayerMP player; // public final String blockName; // public final int blockMetadata; // public final Point blockPoint; // // public VeinminerHarvestFailedCheck(EntityPlayerMP player, Point blockPoint, String name, int metadata) { // this.blockPoint = blockPoint; // allowContinue = Permission.DENY; // this.player = player; // this.blockName = name; // this.blockMetadata = metadata; // } // } // // Path: src/main/java/portablejim/veinminer/api/VeinminerPostUseTool.java // public class VeinminerPostUseTool extends Event { // public final EntityPlayerMP player; // public final Point blockPos; // // public VeinminerPostUseTool(EntityPlayerMP player, Point blockPos) { // this.player = player; // this.blockPos = blockPos; // } // } // Path: src/main/java/portablejim/veinminermodsupport/VeinMinerModSupport.java import bluedart.api.IBreakable; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.FMLLog; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.ModContainer; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.network.NetworkCheckHandler; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.common.config.Configuration; import portablejim.veinminer.api.IMCMessage; import portablejim.veinminer.api.Permission; import portablejim.veinminer.api.VeinminerHarvestFailedCheck; import portablejim.veinminer.api.VeinminerPostUseTool; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import static net.minecraftforge.fml.common.Mod.EventHandler; import static net.minecraftforge.fml.common.Mod.Instance; if(block == null) { devLog("ERROR: Block id wrong."); return; } /*if(toolTags.hasKey("Broken")) { devLog("DENY: Tool broken"); if(event.allowContinue == Permission.ALLOW) { event.allowContinue = Permission.DENY; } return; }*/ devLog("Allowing event"); if(event.allowContinue == Permission.DENY) { event.allowContinue = Permission.ALLOW; } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent public void fixFalseNegatives(VeinminerHarvestFailedCheck event) { // Some blocks return false when they shouldn't. if(event.allowContinue == Permission.DENY) { if("IC2:blockRubWood".equals(event.blockName)) event.allowContinue = Permission.ALLOW; } } @SuppressWarnings("UnusedDeclaration") @SubscribeEvent
public void applyForce(VeinminerPostUseTool event) {
portablejim/VeinMiner
src/main/java/portablejim/veinminer/configuration/Tool.java
// Path: src/main/java/portablejim/veinminer/configuration/json/ToolStruct.java // public class ToolStruct { // public String name; // public String icon; // public String[] toollist; // public String[] blocklist; // } // // Path: src/main/java/portablejim/veinminer/util/BlockID.java // public class BlockID implements Comparable<BlockID> // { // public String name; // public int metadata; // public IBlockState state = null; // // public BlockID(String fullDescription) { // int preMeta = -1; // Pattern p = Pattern.compile("([^/]+)(?:/([-]?\\d{1,2}))?"); // Matcher m = p.matcher(fullDescription); // // if(m.matches()) { // name = m.group(1); // if(m.group(2) != null) { // try { // preMeta = Integer.parseInt(m.group(2)); // } // catch (NumberFormatException e) { // preMeta = -1; // } // } // } // else { // name = ""; // } // metadata = preMeta >= -1 ? preMeta : -1; // } // // public BlockID(String name, int meta) { // this.name = name; // this.metadata = meta < -1 || meta == OreDictionary.WILDCARD_VALUE ? -1 : meta; // } // // @Deprecated // public BlockID(World world, BlockPos position) { // this(world.getBlockState(position)); // } // // public BlockID(IBlockState state) { // this(Block.blockRegistry.getNameForObject(state.getBlock()).toString(), state.getBlock().getMetaFromState(state)); // this.state = state; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // return name.equals(o.name) && metadata == o.metadata; // } // // /** // * Compare the objects using the metadata value of -1 to be a wildcard that matches all. // * @param obj The object to compare to this one // * @return Whether this object and obj are equal, using the wildcard value. // */ // public boolean wildcardEquals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // if (o.metadata == -1 || metadata == -1) // return this.equals(obj); // else // return name.equals(o.name) && metadata == o.metadata; // } // // @Override // public int hashCode() // { // return (this.name.hashCode() << 6) + this.metadata; // } // // @Override // public String toString() // { // return (metadata == -1 ? name + "" : name + "/" + metadata); // } // // @Override // public int compareTo(BlockID blockID) { // if(name != null && !name.equals(blockID.name)) { // int result = name.compareTo(blockID.name); // if(result > 0) return 1; // else if (result < 0) return -1; // return 0; // } // else if(metadata < blockID.metadata) { // return -1; // } // else if(metadata > blockID.metadata) { // return 1; // } // else { // return 0; // } // } // }
import portablejim.veinminer.configuration.json.ToolStruct; import portablejim.veinminer.util.BlockID; import java.util.Collections; import java.util.HashSet; import java.util.Set;
package portablejim.veinminer.configuration; /** * Class to manage tool tool lists and block lists. */ public class Tool { public String name; public String icon; public Set<String> toollist;
// Path: src/main/java/portablejim/veinminer/configuration/json/ToolStruct.java // public class ToolStruct { // public String name; // public String icon; // public String[] toollist; // public String[] blocklist; // } // // Path: src/main/java/portablejim/veinminer/util/BlockID.java // public class BlockID implements Comparable<BlockID> // { // public String name; // public int metadata; // public IBlockState state = null; // // public BlockID(String fullDescription) { // int preMeta = -1; // Pattern p = Pattern.compile("([^/]+)(?:/([-]?\\d{1,2}))?"); // Matcher m = p.matcher(fullDescription); // // if(m.matches()) { // name = m.group(1); // if(m.group(2) != null) { // try { // preMeta = Integer.parseInt(m.group(2)); // } // catch (NumberFormatException e) { // preMeta = -1; // } // } // } // else { // name = ""; // } // metadata = preMeta >= -1 ? preMeta : -1; // } // // public BlockID(String name, int meta) { // this.name = name; // this.metadata = meta < -1 || meta == OreDictionary.WILDCARD_VALUE ? -1 : meta; // } // // @Deprecated // public BlockID(World world, BlockPos position) { // this(world.getBlockState(position)); // } // // public BlockID(IBlockState state) { // this(Block.blockRegistry.getNameForObject(state.getBlock()).toString(), state.getBlock().getMetaFromState(state)); // this.state = state; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // return name.equals(o.name) && metadata == o.metadata; // } // // /** // * Compare the objects using the metadata value of -1 to be a wildcard that matches all. // * @param obj The object to compare to this one // * @return Whether this object and obj are equal, using the wildcard value. // */ // public boolean wildcardEquals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // if (o.metadata == -1 || metadata == -1) // return this.equals(obj); // else // return name.equals(o.name) && metadata == o.metadata; // } // // @Override // public int hashCode() // { // return (this.name.hashCode() << 6) + this.metadata; // } // // @Override // public String toString() // { // return (metadata == -1 ? name + "" : name + "/" + metadata); // } // // @Override // public int compareTo(BlockID blockID) { // if(name != null && !name.equals(blockID.name)) { // int result = name.compareTo(blockID.name); // if(result > 0) return 1; // else if (result < 0) return -1; // return 0; // } // else if(metadata < blockID.metadata) { // return -1; // } // else if(metadata > blockID.metadata) { // return 1; // } // else { // return 0; // } // } // } // Path: src/main/java/portablejim/veinminer/configuration/Tool.java import portablejim.veinminer.configuration.json.ToolStruct; import portablejim.veinminer.util.BlockID; import java.util.Collections; import java.util.HashSet; import java.util.Set; package portablejim.veinminer.configuration; /** * Class to manage tool tool lists and block lists. */ public class Tool { public String name; public String icon; public Set<String> toollist;
public Set<BlockID> blocklist;
portablejim/VeinMiner
src/main/java/portablejim/veinminer/configuration/Tool.java
// Path: src/main/java/portablejim/veinminer/configuration/json/ToolStruct.java // public class ToolStruct { // public String name; // public String icon; // public String[] toollist; // public String[] blocklist; // } // // Path: src/main/java/portablejim/veinminer/util/BlockID.java // public class BlockID implements Comparable<BlockID> // { // public String name; // public int metadata; // public IBlockState state = null; // // public BlockID(String fullDescription) { // int preMeta = -1; // Pattern p = Pattern.compile("([^/]+)(?:/([-]?\\d{1,2}))?"); // Matcher m = p.matcher(fullDescription); // // if(m.matches()) { // name = m.group(1); // if(m.group(2) != null) { // try { // preMeta = Integer.parseInt(m.group(2)); // } // catch (NumberFormatException e) { // preMeta = -1; // } // } // } // else { // name = ""; // } // metadata = preMeta >= -1 ? preMeta : -1; // } // // public BlockID(String name, int meta) { // this.name = name; // this.metadata = meta < -1 || meta == OreDictionary.WILDCARD_VALUE ? -1 : meta; // } // // @Deprecated // public BlockID(World world, BlockPos position) { // this(world.getBlockState(position)); // } // // public BlockID(IBlockState state) { // this(Block.blockRegistry.getNameForObject(state.getBlock()).toString(), state.getBlock().getMetaFromState(state)); // this.state = state; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // return name.equals(o.name) && metadata == o.metadata; // } // // /** // * Compare the objects using the metadata value of -1 to be a wildcard that matches all. // * @param obj The object to compare to this one // * @return Whether this object and obj are equal, using the wildcard value. // */ // public boolean wildcardEquals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // if (o.metadata == -1 || metadata == -1) // return this.equals(obj); // else // return name.equals(o.name) && metadata == o.metadata; // } // // @Override // public int hashCode() // { // return (this.name.hashCode() << 6) + this.metadata; // } // // @Override // public String toString() // { // return (metadata == -1 ? name + "" : name + "/" + metadata); // } // // @Override // public int compareTo(BlockID blockID) { // if(name != null && !name.equals(blockID.name)) { // int result = name.compareTo(blockID.name); // if(result > 0) return 1; // else if (result < 0) return -1; // return 0; // } // else if(metadata < blockID.metadata) { // return -1; // } // else if(metadata > blockID.metadata) { // return 1; // } // else { // return 0; // } // } // }
import portablejim.veinminer.configuration.json.ToolStruct; import portablejim.veinminer.util.BlockID; import java.util.Collections; import java.util.HashSet; import java.util.Set;
package portablejim.veinminer.configuration; /** * Class to manage tool tool lists and block lists. */ public class Tool { public String name; public String icon; public Set<String> toollist; public Set<BlockID> blocklist; public Tool(String name, String icon, String[] toollist, String[] blocklist) { this.name = name; this.icon = icon; this.toollist = new HashSet<String>(toollist.length); this.blocklist = new HashSet<BlockID>(blocklist.length); Collections.addAll(this.toollist, toollist); for(String block : blocklist) { this.blocklist.add(new BlockID(block)); } }
// Path: src/main/java/portablejim/veinminer/configuration/json/ToolStruct.java // public class ToolStruct { // public String name; // public String icon; // public String[] toollist; // public String[] blocklist; // } // // Path: src/main/java/portablejim/veinminer/util/BlockID.java // public class BlockID implements Comparable<BlockID> // { // public String name; // public int metadata; // public IBlockState state = null; // // public BlockID(String fullDescription) { // int preMeta = -1; // Pattern p = Pattern.compile("([^/]+)(?:/([-]?\\d{1,2}))?"); // Matcher m = p.matcher(fullDescription); // // if(m.matches()) { // name = m.group(1); // if(m.group(2) != null) { // try { // preMeta = Integer.parseInt(m.group(2)); // } // catch (NumberFormatException e) { // preMeta = -1; // } // } // } // else { // name = ""; // } // metadata = preMeta >= -1 ? preMeta : -1; // } // // public BlockID(String name, int meta) { // this.name = name; // this.metadata = meta < -1 || meta == OreDictionary.WILDCARD_VALUE ? -1 : meta; // } // // @Deprecated // public BlockID(World world, BlockPos position) { // this(world.getBlockState(position)); // } // // public BlockID(IBlockState state) { // this(Block.blockRegistry.getNameForObject(state.getBlock()).toString(), state.getBlock().getMetaFromState(state)); // this.state = state; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // return name.equals(o.name) && metadata == o.metadata; // } // // /** // * Compare the objects using the metadata value of -1 to be a wildcard that matches all. // * @param obj The object to compare to this one // * @return Whether this object and obj are equal, using the wildcard value. // */ // public boolean wildcardEquals(Object obj) // { // if (this == obj) // return true; // // if (!(obj instanceof BlockID)) // return false; // // BlockID o = (BlockID) obj; // if (o.metadata == -1 || metadata == -1) // return this.equals(obj); // else // return name.equals(o.name) && metadata == o.metadata; // } // // @Override // public int hashCode() // { // return (this.name.hashCode() << 6) + this.metadata; // } // // @Override // public String toString() // { // return (metadata == -1 ? name + "" : name + "/" + metadata); // } // // @Override // public int compareTo(BlockID blockID) { // if(name != null && !name.equals(blockID.name)) { // int result = name.compareTo(blockID.name); // if(result > 0) return 1; // else if (result < 0) return -1; // return 0; // } // else if(metadata < blockID.metadata) { // return -1; // } // else if(metadata > blockID.metadata) { // return 1; // } // else { // return 0; // } // } // } // Path: src/main/java/portablejim/veinminer/configuration/Tool.java import portablejim.veinminer.configuration.json.ToolStruct; import portablejim.veinminer.util.BlockID; import java.util.Collections; import java.util.HashSet; import java.util.Set; package portablejim.veinminer.configuration; /** * Class to manage tool tool lists and block lists. */ public class Tool { public String name; public String icon; public Set<String> toollist; public Set<BlockID> blocklist; public Tool(String name, String icon, String[] toollist, String[] blocklist) { this.name = name; this.icon = icon; this.toollist = new HashSet<String>(toollist.length); this.blocklist = new HashSet<BlockID>(blocklist.length); Collections.addAll(this.toollist, toollist); for(String block : blocklist) { this.blocklist.add(new BlockID(block)); } }
public Tool(ToolStruct baseTool) {
iflove/UIKit-ViewBlock
uikit-library/src/main/java/android/uikit/ViewBlockManagerImpl.java
// Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // }
import android.support.annotation.NonNull; import android.util.SparseArray; import android.utils.Preconditions; import android.view.View; import android.view.ViewGroup; import java.util.Stack; import static android.view.View.NO_ID;
} @Override public ViewBlockManager detachView(@NonNull ViewBlock viewBlock) { if (contains(viewBlock) && viewBlock.getBlockingView() != null) { ViewBlockParent parent = viewBlock.getParent(); if (parent != null) { ViewBlock block = parent.getViewBlock(); View blockingView = block.getBlockingView(); if (blockingView instanceof ViewGroup) { ((ViewGroup) blockingView).removeView(viewBlock.getBlockingView()); } } } return this; } @Override public ViewBlock findViewBlockByKey(int key) { return viewBlockSparseArray.get(key); } @Override public boolean contains(@NonNull ViewBlock viewBlock) { return (viewBlockSparseArray.indexOfKey(viewBlock.getId()) > 0 || viewBlockSparseArray.indexOfValue(viewBlock) != -1); } @Override public ViewBlockManager add(@NonNull ViewBlock viewBlock) {
// Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // } // Path: uikit-library/src/main/java/android/uikit/ViewBlockManagerImpl.java import android.support.annotation.NonNull; import android.util.SparseArray; import android.utils.Preconditions; import android.view.View; import android.view.ViewGroup; import java.util.Stack; import static android.view.View.NO_ID; } @Override public ViewBlockManager detachView(@NonNull ViewBlock viewBlock) { if (contains(viewBlock) && viewBlock.getBlockingView() != null) { ViewBlockParent parent = viewBlock.getParent(); if (parent != null) { ViewBlock block = parent.getViewBlock(); View blockingView = block.getBlockingView(); if (blockingView instanceof ViewGroup) { ((ViewGroup) blockingView).removeView(viewBlock.getBlockingView()); } } } return this; } @Override public ViewBlock findViewBlockByKey(int key) { return viewBlockSparseArray.get(key); } @Override public boolean contains(@NonNull ViewBlock viewBlock) { return (viewBlockSparseArray.indexOfKey(viewBlock.getId()) > 0 || viewBlockSparseArray.indexOfValue(viewBlock) != -1); } @Override public ViewBlockManager add(@NonNull ViewBlock viewBlock) {
Preconditions.checkNotNull(viewBlock);
iflove/UIKit-ViewBlock
uikit-library/src/main/java/android/uikit/ViewBlock.java
// Path: uikit-library/src/main/java/android/content/UIKitIntent.java // public class UIKitIntent extends Intent { // public ViewBlock fromViewBlock; // public ViewBlock toViewBlock; // // private UIKitIntent(Intent o) { // } // // private UIKitIntent(String action) { // } // // private UIKitIntent(String action, Uri uri) { // } // // private UIKitIntent(Context packageContext, Class<?> cls) { // } // // private UIKitIntent(String action, Uri uri, Context packageContext, Class<?> cls) { // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock, @NonNull ViewBlock toViewBlock) { // this.fromViewBlock = fromViewBlock; // this.toViewBlock = toViewBlock; // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public ViewBlock getFromViewBlock() { // return fromViewBlock; // } // // public void setFromViewBlock(ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public void setToViewBlock(ViewBlock toViewBlock) { // this.toViewBlock = toViewBlock; // } // // public ViewBlock getToViewBlock() { // return toViewBlock; // } // }
import android.app.Activity; import android.content.Context; import android.content.UIKitIntent; import android.support.annotation.AnimRes; import android.support.annotation.IdRes; import android.support.annotation.IntDef; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.SparseArrayCompat; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.util.Stack; import static android.view.View.GONE; import static android.view.View.VISIBLE;
package android.uikit; public abstract class ViewBlock extends ContextViewBlock implements ViewBlockParent, ViewBlockAnimation, BaseViewInterface { private static final String TAG = "ViewBlock"; private ViewBlockParent mParent;
// Path: uikit-library/src/main/java/android/content/UIKitIntent.java // public class UIKitIntent extends Intent { // public ViewBlock fromViewBlock; // public ViewBlock toViewBlock; // // private UIKitIntent(Intent o) { // } // // private UIKitIntent(String action) { // } // // private UIKitIntent(String action, Uri uri) { // } // // private UIKitIntent(Context packageContext, Class<?> cls) { // } // // private UIKitIntent(String action, Uri uri, Context packageContext, Class<?> cls) { // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock, @NonNull ViewBlock toViewBlock) { // this.fromViewBlock = fromViewBlock; // this.toViewBlock = toViewBlock; // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public ViewBlock getFromViewBlock() { // return fromViewBlock; // } // // public void setFromViewBlock(ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public void setToViewBlock(ViewBlock toViewBlock) { // this.toViewBlock = toViewBlock; // } // // public ViewBlock getToViewBlock() { // return toViewBlock; // } // } // Path: uikit-library/src/main/java/android/uikit/ViewBlock.java import android.app.Activity; import android.content.Context; import android.content.UIKitIntent; import android.support.annotation.AnimRes; import android.support.annotation.IdRes; import android.support.annotation.IntDef; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.SparseArrayCompat; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.util.Stack; import static android.view.View.GONE; import static android.view.View.VISIBLE; package android.uikit; public abstract class ViewBlock extends ContextViewBlock implements ViewBlockParent, ViewBlockAnimation, BaseViewInterface { private static final String TAG = "ViewBlock"; private ViewBlockParent mParent;
UIKitIntent mUiKitIntent = new UIKitIntent(this);
iflove/UIKit-ViewBlock
uikit-library/src/main/java/android/uikit/UIKitActivity.java
// Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // } // // Path: uikit-library/src/main/java/android/utils/AndroidAttrs.java // public static final List<String> ANDROID_LAYOUT_TAG = Collections.unmodifiableList(new ArrayList<String>() { // { // add(FrameLayout.class.getSimpleName()); // add(LinearLayout.class.getSimpleName()); // add(RelativeLayout.class.getSimpleName()); // } // });
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.AttributeSet; import android.util.SparseArray; import android.utils.Preconditions; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Stack; import static android.utils.AndroidAttrs.ANDROID_LAYOUT_TAG;
static final String ON_CREATE = "onCreate"; static final String ON_START = "onStart"; static final String ON_NEW_INTENT = "onNewIntent"; static final String ON_RESTART = "onRestart"; static final String ON_RESUME = "onResume"; static final String ON_STOP = "onStop"; static final String ON_PAUSE = "onPause"; static final String ON_DESTROY = "onDestroy"; static final String ON_RESTORE_INSTANCE_STATE = "onRestoreInstanceState"; static final String ON_SAVE_INSTANCE_STATE = "onSaveInstanceState"; static final String ON_ACTIVITY_RESULT = "onActivityResult"; static final String ON_BACK_PRESSED = "onBackPressed"; final ViewBlockManager mViewBlockManager = new ViewBlockManagerImpl(); private boolean enterContentView; private static final HashMap<String, Constructor<? extends View>> sConstructorMap = new HashMap<String, Constructor<? extends View>>(); static final Class<?>[] mConstructorSignature = new Class[]{ Context.class, AttributeSet.class}; static final Object[] sConstructorArgs = new Object[2]; @Override public View onCreateView(String name, Context context, AttributeSet attrs) { return super.onCreateView(name, context, attrs); } @Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
// Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // } // // Path: uikit-library/src/main/java/android/utils/AndroidAttrs.java // public static final List<String> ANDROID_LAYOUT_TAG = Collections.unmodifiableList(new ArrayList<String>() { // { // add(FrameLayout.class.getSimpleName()); // add(LinearLayout.class.getSimpleName()); // add(RelativeLayout.class.getSimpleName()); // } // }); // Path: uikit-library/src/main/java/android/uikit/UIKitActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.AttributeSet; import android.util.SparseArray; import android.utils.Preconditions; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Stack; import static android.utils.AndroidAttrs.ANDROID_LAYOUT_TAG; static final String ON_CREATE = "onCreate"; static final String ON_START = "onStart"; static final String ON_NEW_INTENT = "onNewIntent"; static final String ON_RESTART = "onRestart"; static final String ON_RESUME = "onResume"; static final String ON_STOP = "onStop"; static final String ON_PAUSE = "onPause"; static final String ON_DESTROY = "onDestroy"; static final String ON_RESTORE_INSTANCE_STATE = "onRestoreInstanceState"; static final String ON_SAVE_INSTANCE_STATE = "onSaveInstanceState"; static final String ON_ACTIVITY_RESULT = "onActivityResult"; static final String ON_BACK_PRESSED = "onBackPressed"; final ViewBlockManager mViewBlockManager = new ViewBlockManagerImpl(); private boolean enterContentView; private static final HashMap<String, Constructor<? extends View>> sConstructorMap = new HashMap<String, Constructor<? extends View>>(); static final Class<?>[] mConstructorSignature = new Class[]{ Context.class, AttributeSet.class}; static final Object[] sConstructorArgs = new Object[2]; @Override public View onCreateView(String name, Context context, AttributeSet attrs) { return super.onCreateView(name, context, attrs); } @Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
if (!enterContentView && Preconditions.nonNull(parent) && parent.getId() == android.R.id.content) {
iflove/UIKit-ViewBlock
uikit-library/src/main/java/android/uikit/UIKitActivity.java
// Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // } // // Path: uikit-library/src/main/java/android/utils/AndroidAttrs.java // public static final List<String> ANDROID_LAYOUT_TAG = Collections.unmodifiableList(new ArrayList<String>() { // { // add(FrameLayout.class.getSimpleName()); // add(LinearLayout.class.getSimpleName()); // add(RelativeLayout.class.getSimpleName()); // } // });
import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.AttributeSet; import android.util.SparseArray; import android.utils.Preconditions; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Stack; import static android.utils.AndroidAttrs.ANDROID_LAYOUT_TAG;
private static final HashMap<String, Constructor<? extends View>> sConstructorMap = new HashMap<String, Constructor<? extends View>>(); static final Class<?>[] mConstructorSignature = new Class[]{ Context.class, AttributeSet.class}; static final Object[] sConstructorArgs = new Object[2]; @Override public View onCreateView(String name, Context context, AttributeSet attrs) { return super.onCreateView(name, context, attrs); } @Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { if (!enterContentView && Preconditions.nonNull(parent) && parent.getId() == android.R.id.content) { enterContentView = true; } if (enterContentView) { View view = onCreateUIKitView(parent, name, context, attrs, mViewBlockManager); if (view != null) return view; } return super.onCreateView(parent, name, context, attrs); } static View onCreateUIKitView(View parent, String name, Context context, AttributeSet attrs, final ViewBlockManager mViewBlockManager) { View view = null;
// Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // } // // Path: uikit-library/src/main/java/android/utils/AndroidAttrs.java // public static final List<String> ANDROID_LAYOUT_TAG = Collections.unmodifiableList(new ArrayList<String>() { // { // add(FrameLayout.class.getSimpleName()); // add(LinearLayout.class.getSimpleName()); // add(RelativeLayout.class.getSimpleName()); // } // }); // Path: uikit-library/src/main/java/android/uikit/UIKitActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.AttributeSet; import android.util.SparseArray; import android.utils.Preconditions; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Stack; import static android.utils.AndroidAttrs.ANDROID_LAYOUT_TAG; private static final HashMap<String, Constructor<? extends View>> sConstructorMap = new HashMap<String, Constructor<? extends View>>(); static final Class<?>[] mConstructorSignature = new Class[]{ Context.class, AttributeSet.class}; static final Object[] sConstructorArgs = new Object[2]; @Override public View onCreateView(String name, Context context, AttributeSet attrs) { return super.onCreateView(name, context, attrs); } @Override public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { if (!enterContentView && Preconditions.nonNull(parent) && parent.getId() == android.R.id.content) { enterContentView = true; } if (enterContentView) { View view = onCreateUIKitView(parent, name, context, attrs, mViewBlockManager); if (view != null) return view; } return super.onCreateView(parent, name, context, attrs); } static View onCreateUIKitView(View parent, String name, Context context, AttributeSet attrs, final ViewBlockManager mViewBlockManager) { View view = null;
if (ANDROID_LAYOUT_TAG.contains(name)) {
iflove/UIKit-ViewBlock
uikit-library/src/main/java/android/uikit/UIKitHelper.java
// Path: uikit-library/src/main/java/android/utils/AndroidAttrs.java // public final class AndroidAttrs { // public static final int[] ATTRS = new int[] // { // // android.R.attr.name, // android.R.attr.id, // android.R.attr.tag, // R.attr.block_class, // }; // // public static final int NAME_INDEX = 0; // public static final int ID_INDEX = 1; // public static final int TAG_INDEX = 2; // public static final int BLOCK_CLASS_INDEX = 3; // // public static final List<String> ANDROID_LAYOUT_TAG = Collections.unmodifiableList(new ArrayList<String>() { // { // add(FrameLayout.class.getSimpleName()); // add(LinearLayout.class.getSimpleName()); // add(RelativeLayout.class.getSimpleName()); // } // }); // // public static final List<String> UIKIT_TAGS = Collections.unmodifiableList(new ArrayList<String>() { // { // add(UIKitFrameLayout.class.getName()); // add(UIKitLinearLayout.class.getName()); // add(UIKitRelativeLayout.class.getName()); // // addAll(ANDROID_LAYOUT_TAG); // add("fragment"); // } // }); // // // }
import android.content.Context; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v4.util.Pair; import android.support.v4.util.SparseArrayCompat; import android.util.AttributeSet; import android.util.SparseArray; import android.utils.AndroidAttrs; import android.view.View; import android.view.ViewGroup; import com.lazy.library.logging.Logcat; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import static android.view.View.NO_ID;
package android.uikit; final class UIKitHelper { static final String TAG_UIKIT = "UIKit"; private final ViewGroup mHost; private final Context mContext; UIKitHelper(ViewGroup mHost) { this.mHost = mHost; this.mContext = mHost.getContext(); TypedArray typedArray = this.mContext.getTheme().obtainStyledAttributes(R.style.ViewBlockTheme, new int[]{android.R.attr.background}); int backgroundColor = typedArray.getColor(0, Color.WHITE); typedArray.recycle(); if (this.mHost.getBackground() == null) { this.mHost.setBackgroundColor(backgroundColor); } } public Context getContext() { return mContext; } private Pair<Integer, String> getViewBlockAttrs(AttributeSet attrs) { int resourceId = NO_ID; String name = null;
// Path: uikit-library/src/main/java/android/utils/AndroidAttrs.java // public final class AndroidAttrs { // public static final int[] ATTRS = new int[] // { // // android.R.attr.name, // android.R.attr.id, // android.R.attr.tag, // R.attr.block_class, // }; // // public static final int NAME_INDEX = 0; // public static final int ID_INDEX = 1; // public static final int TAG_INDEX = 2; // public static final int BLOCK_CLASS_INDEX = 3; // // public static final List<String> ANDROID_LAYOUT_TAG = Collections.unmodifiableList(new ArrayList<String>() { // { // add(FrameLayout.class.getSimpleName()); // add(LinearLayout.class.getSimpleName()); // add(RelativeLayout.class.getSimpleName()); // } // }); // // public static final List<String> UIKIT_TAGS = Collections.unmodifiableList(new ArrayList<String>() { // { // add(UIKitFrameLayout.class.getName()); // add(UIKitLinearLayout.class.getName()); // add(UIKitRelativeLayout.class.getName()); // // addAll(ANDROID_LAYOUT_TAG); // add("fragment"); // } // }); // // // } // Path: uikit-library/src/main/java/android/uikit/UIKitHelper.java import android.content.Context; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v4.util.Pair; import android.support.v4.util.SparseArrayCompat; import android.util.AttributeSet; import android.util.SparseArray; import android.utils.AndroidAttrs; import android.view.View; import android.view.ViewGroup; import com.lazy.library.logging.Logcat; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import static android.view.View.NO_ID; package android.uikit; final class UIKitHelper { static final String TAG_UIKIT = "UIKit"; private final ViewGroup mHost; private final Context mContext; UIKitHelper(ViewGroup mHost) { this.mHost = mHost; this.mContext = mHost.getContext(); TypedArray typedArray = this.mContext.getTheme().obtainStyledAttributes(R.style.ViewBlockTheme, new int[]{android.R.attr.background}); int backgroundColor = typedArray.getColor(0, Color.WHITE); typedArray.recycle(); if (this.mHost.getBackground() == null) { this.mHost.setBackgroundColor(backgroundColor); } } public Context getContext() { return mContext; } private Pair<Integer, String> getViewBlockAttrs(AttributeSet attrs) { int resourceId = NO_ID; String name = null;
TypedArray array = getContext().obtainStyledAttributes(attrs, AndroidAttrs.ATTRS);
iflove/UIKit-ViewBlock
app/src/main/java/android/uikit/demo/activity/GeneralActivity.java
// Path: uikit-library/src/main/java/android/uikit/UIKit.java // public class UIKit { // private static boolean registerActivity = false; // // // public static void inject(@NonNull final Activity activity) { // if (activity instanceof UIKitActivity) { // return; // } // // View rootView = activity.findViewById(android.R.id.content); // final ViewBlockManager mViewBlockManager = new ViewBlockManagerImpl(); // rootView.setTag(R.id.ViewBlockManager, mViewBlockManager); // // if (activity.getLayoutInflater().getFactory2() == null) { // activity.getLayoutInflater().setFactory2(new LayoutInflater.Factory2() { // @Override // public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { // View view = UIKitActivity.onCreateUIKitView(parent, name, context, attrs, mViewBlockManager); // if (view != null) return view; // return activity.onCreateView(parent, name, activity, attrs); // } // // @Override // public View onCreateView(String name, Context context, AttributeSet attrs) { // return activity.onCreateView(name, activity, attrs); // } // }); // } // // registerActivityLifecycleCallbacks(activity); // } // // private static void registerActivityLifecycleCallbacks(@NonNull Activity activity) { // if (!registerActivity) { // registerActivity = true; // if (Build.VERSION.SDK_INT < 14) { // return; // } // Application application = activity.getApplication(); // application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_CREATE, savedInstanceState); // } // // @Override // public void onActivityStarted(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_START); // } // // @Override // public void onActivityResumed(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_RESUME); // } // // @Override // public void onActivityPaused(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_PAUSE); // } // // @Override // public void onActivityStopped(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_STOP); // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_SAVE_INSTANCE_STATE, outState); // } // // @Override // public void onActivityDestroyed(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_DESTROY); // } // }); // } // } // // public static ViewBlockManager getViewBlockManager(@NonNull final Activity activity) { // View rootView = activity.findViewById(android.R.id.content); // return (ViewBlockManager) rootView.getTag(R.id.ViewBlockManager); // } // // }
import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.uikit.UIKit; import android.uikit.demo.R;
package android.uikit.demo.activity; public class GeneralActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) {
// Path: uikit-library/src/main/java/android/uikit/UIKit.java // public class UIKit { // private static boolean registerActivity = false; // // // public static void inject(@NonNull final Activity activity) { // if (activity instanceof UIKitActivity) { // return; // } // // View rootView = activity.findViewById(android.R.id.content); // final ViewBlockManager mViewBlockManager = new ViewBlockManagerImpl(); // rootView.setTag(R.id.ViewBlockManager, mViewBlockManager); // // if (activity.getLayoutInflater().getFactory2() == null) { // activity.getLayoutInflater().setFactory2(new LayoutInflater.Factory2() { // @Override // public View onCreateView(View parent, String name, Context context, AttributeSet attrs) { // View view = UIKitActivity.onCreateUIKitView(parent, name, context, attrs, mViewBlockManager); // if (view != null) return view; // return activity.onCreateView(parent, name, activity, attrs); // } // // @Override // public View onCreateView(String name, Context context, AttributeSet attrs) { // return activity.onCreateView(name, activity, attrs); // } // }); // } // // registerActivityLifecycleCallbacks(activity); // } // // private static void registerActivityLifecycleCallbacks(@NonNull Activity activity) { // if (!registerActivity) { // registerActivity = true; // if (Build.VERSION.SDK_INT < 14) { // return; // } // Application application = activity.getApplication(); // application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_CREATE, savedInstanceState); // } // // @Override // public void onActivityStarted(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_START); // } // // @Override // public void onActivityResumed(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_RESUME); // } // // @Override // public void onActivityPaused(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_PAUSE); // } // // @Override // public void onActivityStopped(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_STOP); // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_SAVE_INSTANCE_STATE, outState); // } // // @Override // public void onActivityDestroyed(Activity activity) { // ViewBlockManager viewBlockManager = getViewBlockManager(activity); // if (viewBlockManager == null) return; // SparseArray<ViewBlock> viewBlocks = viewBlockManager.getViewBlocks(); // UIKitActivity.dispatch(viewBlocks, UIKitActivity.ON_DESTROY); // } // }); // } // } // // public static ViewBlockManager getViewBlockManager(@NonNull final Activity activity) { // View rootView = activity.findViewById(android.R.id.content); // return (ViewBlockManager) rootView.getTag(R.id.ViewBlockManager); // } // // } // Path: app/src/main/java/android/uikit/demo/activity/GeneralActivity.java import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.uikit.UIKit; import android.uikit.demo.R; package android.uikit.demo.activity; public class GeneralActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) {
UIKit.inject(this);
iflove/UIKit-ViewBlock
uikit-library/src/main/java/android/uikit/ContextViewBlock.java
// Path: uikit-library/src/main/java/android/content/UIKitIntent.java // public class UIKitIntent extends Intent { // public ViewBlock fromViewBlock; // public ViewBlock toViewBlock; // // private UIKitIntent(Intent o) { // } // // private UIKitIntent(String action) { // } // // private UIKitIntent(String action, Uri uri) { // } // // private UIKitIntent(Context packageContext, Class<?> cls) { // } // // private UIKitIntent(String action, Uri uri, Context packageContext, Class<?> cls) { // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock, @NonNull ViewBlock toViewBlock) { // this.fromViewBlock = fromViewBlock; // this.toViewBlock = toViewBlock; // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public ViewBlock getFromViewBlock() { // return fromViewBlock; // } // // public void setFromViewBlock(ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public void setToViewBlock(ViewBlock toViewBlock) { // this.toViewBlock = toViewBlock; // } // // public ViewBlock getToViewBlock() { // return toViewBlock; // } // } // // Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // }
import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.UIKitIntent; import android.content.res.AssetManager; import android.content.res.Resources; import android.os.Bundle; import android.os.Looper; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.utils.Preconditions; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;
package android.uikit; /** * Created by lazy on 2017/4/23. */ abstract class ContextViewBlock implements ActivityLifeCycle { protected final String TAG = this.getClass().getCanonicalName(); protected final Activity mActivity; protected final Context mContext; View mBlockingView; @IdRes int mBlockingViewId = View.NO_ID; static final int INITIALIZING = 0; // Not yet created. static final int CREATED = 1; // The activity has finished its creation. static final int CREATED_VIEW = 2; // Created. static final int STARTED = 3; // Created and started, not resumed. static final int RESUMED = 4; // Created started and resumed. static final int STOPPED = 5; // Fully created, not started. static final int PAUSE = 6; // Created started and resumed. static final int STOP = 7; // Created started and resumed. static final int DESTROY = 8; // Created started and resumed. int mState = INITIALIZING; protected ContextViewBlock(Context context) {
// Path: uikit-library/src/main/java/android/content/UIKitIntent.java // public class UIKitIntent extends Intent { // public ViewBlock fromViewBlock; // public ViewBlock toViewBlock; // // private UIKitIntent(Intent o) { // } // // private UIKitIntent(String action) { // } // // private UIKitIntent(String action, Uri uri) { // } // // private UIKitIntent(Context packageContext, Class<?> cls) { // } // // private UIKitIntent(String action, Uri uri, Context packageContext, Class<?> cls) { // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock, @NonNull ViewBlock toViewBlock) { // this.fromViewBlock = fromViewBlock; // this.toViewBlock = toViewBlock; // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public ViewBlock getFromViewBlock() { // return fromViewBlock; // } // // public void setFromViewBlock(ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public void setToViewBlock(ViewBlock toViewBlock) { // this.toViewBlock = toViewBlock; // } // // public ViewBlock getToViewBlock() { // return toViewBlock; // } // } // // Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // } // Path: uikit-library/src/main/java/android/uikit/ContextViewBlock.java import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.UIKitIntent; import android.content.res.AssetManager; import android.content.res.Resources; import android.os.Bundle; import android.os.Looper; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.utils.Preconditions; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; package android.uikit; /** * Created by lazy on 2017/4/23. */ abstract class ContextViewBlock implements ActivityLifeCycle { protected final String TAG = this.getClass().getCanonicalName(); protected final Activity mActivity; protected final Context mContext; View mBlockingView; @IdRes int mBlockingViewId = View.NO_ID; static final int INITIALIZING = 0; // Not yet created. static final int CREATED = 1; // The activity has finished its creation. static final int CREATED_VIEW = 2; // Created. static final int STARTED = 3; // Created and started, not resumed. static final int RESUMED = 4; // Created started and resumed. static final int STOPPED = 5; // Fully created, not started. static final int PAUSE = 6; // Created started and resumed. static final int STOP = 7; // Created started and resumed. static final int DESTROY = 8; // Created started and resumed. int mState = INITIALIZING; protected ContextViewBlock(Context context) {
Preconditions.checkNotNull(context);
iflove/UIKit-ViewBlock
uikit-library/src/main/java/android/uikit/ContextViewBlock.java
// Path: uikit-library/src/main/java/android/content/UIKitIntent.java // public class UIKitIntent extends Intent { // public ViewBlock fromViewBlock; // public ViewBlock toViewBlock; // // private UIKitIntent(Intent o) { // } // // private UIKitIntent(String action) { // } // // private UIKitIntent(String action, Uri uri) { // } // // private UIKitIntent(Context packageContext, Class<?> cls) { // } // // private UIKitIntent(String action, Uri uri, Context packageContext, Class<?> cls) { // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock, @NonNull ViewBlock toViewBlock) { // this.fromViewBlock = fromViewBlock; // this.toViewBlock = toViewBlock; // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public ViewBlock getFromViewBlock() { // return fromViewBlock; // } // // public void setFromViewBlock(ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public void setToViewBlock(ViewBlock toViewBlock) { // this.toViewBlock = toViewBlock; // } // // public ViewBlock getToViewBlock() { // return toViewBlock; // } // } // // Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // }
import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.UIKitIntent; import android.content.res.AssetManager; import android.content.res.Resources; import android.os.Bundle; import android.os.Looper; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.utils.Preconditions; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;
} public Looper getMainLooper() { return mContext.getMainLooper(); } public void startActivity(Intent intent) { mActivity.startActivity(intent); } protected void startActivity(Class<? extends Activity> clazz) { Intent intent = new Intent(); intent.setClass(getContext(), clazz); mActivity.startActivity(intent); } public void finishActivity() { mActivity.finish(); } public View getBlockingView() { return mBlockingView; } protected <T> T castBlockingView() { //noinspection unchecked return (T) mBlockingView; }
// Path: uikit-library/src/main/java/android/content/UIKitIntent.java // public class UIKitIntent extends Intent { // public ViewBlock fromViewBlock; // public ViewBlock toViewBlock; // // private UIKitIntent(Intent o) { // } // // private UIKitIntent(String action) { // } // // private UIKitIntent(String action, Uri uri) { // } // // private UIKitIntent(Context packageContext, Class<?> cls) { // } // // private UIKitIntent(String action, Uri uri, Context packageContext, Class<?> cls) { // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock, @NonNull ViewBlock toViewBlock) { // this.fromViewBlock = fromViewBlock; // this.toViewBlock = toViewBlock; // } // // public UIKitIntent(@NonNull ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public ViewBlock getFromViewBlock() { // return fromViewBlock; // } // // public void setFromViewBlock(ViewBlock fromViewBlock) { // this.fromViewBlock = fromViewBlock; // } // // public void setToViewBlock(ViewBlock toViewBlock) { // this.toViewBlock = toViewBlock; // } // // public ViewBlock getToViewBlock() { // return toViewBlock; // } // } // // Path: uikit-library/src/main/java/android/utils/Preconditions.java // public final class Preconditions { // private Preconditions() { // } // // public static <T> T checkNotNull(T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { // if (reference == null) { // throw new NullPointerException(String.valueOf(errorMessage)); // } // return reference; // } // // public static boolean isNull(Object obj) { // return obj == null; // } // // public static boolean nonNull(Object obj) { // return obj != null; // } // // } // Path: uikit-library/src/main/java/android/uikit/ContextViewBlock.java import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.UIKitIntent; import android.content.res.AssetManager; import android.content.res.Resources; import android.os.Bundle; import android.os.Looper; import android.support.annotation.IdRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.utils.Preconditions; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; } public Looper getMainLooper() { return mContext.getMainLooper(); } public void startActivity(Intent intent) { mActivity.startActivity(intent); } protected void startActivity(Class<? extends Activity> clazz) { Intent intent = new Intent(); intent.setClass(getContext(), clazz); mActivity.startActivity(intent); } public void finishActivity() { mActivity.finish(); } public View getBlockingView() { return mBlockingView; } protected <T> T castBlockingView() { //noinspection unchecked return (T) mBlockingView; }
public abstract UIKitIntent getUIKitIntent();
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/PageInterceptor.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // }
import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.RowBounds; import java.sql.Connection; import java.util.Properties;
package chanedi.dao.impl.mybatis.interceptor; /** * 支持物理分页。 * Created by unknown * Modify by Chanedi */ @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) }) @Slf4j public class PageInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); BoundSql boundSql = statementHandler.getBoundSql(); MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory()); RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds"); if ((rowBounds != null) && (rowBounds != RowBounds.DEFAULT)) { Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration");
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/PageInterceptor.java import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.RowBounds; import java.sql.Connection; import java.util.Properties; package chanedi.dao.impl.mybatis.interceptor; /** * 支持物理分页。 * Created by unknown * Modify by Chanedi */ @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) }) @Slf4j public class PageInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); BoundSql boundSql = statementHandler.getBoundSql(); MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory()); RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds"); if ((rowBounds != null) && (rowBounds != RowBounds.DEFAULT)) { Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration");
Dialect dialect = DialectParser.parse(configuration);
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/PageInterceptor.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // }
import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.RowBounds; import java.sql.Connection; import java.util.Properties;
package chanedi.dao.impl.mybatis.interceptor; /** * 支持物理分页。 * Created by unknown * Modify by Chanedi */ @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) }) @Slf4j public class PageInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); BoundSql boundSql = statementHandler.getBoundSql(); MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory()); RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds"); if ((rowBounds != null) && (rowBounds != RowBounds.DEFAULT)) { Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration");
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/PageInterceptor.java import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.RowBounds; import java.sql.Connection; import java.util.Properties; package chanedi.dao.impl.mybatis.interceptor; /** * 支持物理分页。 * Created by unknown * Modify by Chanedi */ @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) }) @Slf4j public class PageInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); BoundSql boundSql = statementHandler.getBoundSql(); MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory()); RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds"); if ((rowBounds != null) && (rowBounds != RowBounds.DEFAULT)) { Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration");
Dialect dialect = DialectParser.parse(configuration);
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java
// Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // }
import chanedi.util.StringUtils; import lombok.Getter; import lombok.Setter;
package chanedi.generator.model; /** * @author Chanedi */ public class Property { @Getter private String name; @Getter private String capitalizeName; @Getter private String columnName; @Getter@Setter private String comment; @Getter@Setter private PropertyType type; public void setColumnName(String columnName) { this.columnName = columnName;
// Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java import chanedi.util.StringUtils; import lombok.Getter; import lombok.Setter; package chanedi.generator.model; /** * @author Chanedi */ public class Property { @Getter private String name; @Getter private String capitalizeName; @Getter private String columnName; @Getter@Setter private String comment; @Getter@Setter private PropertyType type; public void setColumnName(String columnName) { this.columnName = columnName;
this.name = StringUtils.uncapitalizeCamelBySeparator(columnName, "_");
chanedi/QuickProject
QuickProject-Core/src/test/java/chanedi/bas/model/EventProcess.java
// Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // }
import chanedi.model.Entity; import lombok.Data; import javax.persistence.Table; import java.util.Date;
package chanedi.bas.model; @Data @Table(name = "T_EVE_EVENT_PROCESS")
// Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // } // Path: QuickProject-Core/src/test/java/chanedi/bas/model/EventProcess.java import chanedi.model.Entity; import lombok.Data; import javax.persistence.Table; import java.util.Date; package chanedi.bas.model; @Data @Table(name = "T_EVE_EVENT_PROCESS")
public class EventProcess extends Entity {
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/SortListInterceptor.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // }
import chanedi.dao.complexQuery.Sort; import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.List; import java.util.Properties;
package chanedi.dao.impl.mybatis.interceptor; /** * 将sortList加入sql。 * * @author Chanedi */ @Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) @Slf4j public class SortListInterceptor implements Interceptor {
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/SortListInterceptor.java import chanedi.dao.complexQuery.Sort; import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.List; import java.util.Properties; package chanedi.dao.impl.mybatis.interceptor; /** * 将sortList加入sql。 * * @author Chanedi */ @Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) @Slf4j public class SortListInterceptor implements Interceptor {
private static ThreadLocal<List<Sort>> sortList = new ThreadLocal<List<Sort>>();
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/SortListInterceptor.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // }
import chanedi.dao.complexQuery.Sort; import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.List; import java.util.Properties;
package chanedi.dao.impl.mybatis.interceptor; /** * 将sortList加入sql。 * * @author Chanedi */ @Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) @Slf4j public class SortListInterceptor implements Interceptor { private static ThreadLocal<List<Sort>> sortList = new ThreadLocal<List<Sort>>(); public static List<Sort> getSortList() { List<Sort> sortList = SortListInterceptor.sortList.get(); SortListInterceptor.sortList.remove(); return sortList; } public static void setSortList(List<Sort> sortList) { SortListInterceptor.sortList.set(sortList); } @Override public Object intercept(Invocation invocation) throws Throwable { List<Sort> sortList = getSortList(); if (sortList == null || sortList.size() == 0) { return invocation.proceed(); } Executor executor = (Executor) invocation.getTarget(); Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; // 计算修改BoundSql BoundSql boundSql = ms.getBoundSql(parameter); MetaObject boundSqlHandler = MetaObject.forObject(boundSql, new DefaultObjectFactory(), new DefaultObjectWrapperFactory());
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/SortListInterceptor.java import chanedi.dao.complexQuery.Sort; import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.List; import java.util.Properties; package chanedi.dao.impl.mybatis.interceptor; /** * 将sortList加入sql。 * * @author Chanedi */ @Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) @Slf4j public class SortListInterceptor implements Interceptor { private static ThreadLocal<List<Sort>> sortList = new ThreadLocal<List<Sort>>(); public static List<Sort> getSortList() { List<Sort> sortList = SortListInterceptor.sortList.get(); SortListInterceptor.sortList.remove(); return sortList; } public static void setSortList(List<Sort> sortList) { SortListInterceptor.sortList.set(sortList); } @Override public Object intercept(Invocation invocation) throws Throwable { List<Sort> sortList = getSortList(); if (sortList == null || sortList.size() == 0) { return invocation.proceed(); } Executor executor = (Executor) invocation.getTarget(); Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; // 计算修改BoundSql BoundSql boundSql = ms.getBoundSql(parameter); MetaObject boundSqlHandler = MetaObject.forObject(boundSql, new DefaultObjectFactory(), new DefaultObjectWrapperFactory());
Dialect dialect = DialectParser.parse(ms.getConfiguration());
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/SortListInterceptor.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // }
import chanedi.dao.complexQuery.Sort; import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.List; import java.util.Properties;
package chanedi.dao.impl.mybatis.interceptor; /** * 将sortList加入sql。 * * @author Chanedi */ @Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) @Slf4j public class SortListInterceptor implements Interceptor { private static ThreadLocal<List<Sort>> sortList = new ThreadLocal<List<Sort>>(); public static List<Sort> getSortList() { List<Sort> sortList = SortListInterceptor.sortList.get(); SortListInterceptor.sortList.remove(); return sortList; } public static void setSortList(List<Sort> sortList) { SortListInterceptor.sortList.set(sortList); } @Override public Object intercept(Invocation invocation) throws Throwable { List<Sort> sortList = getSortList(); if (sortList == null || sortList.size() == 0) { return invocation.proceed(); } Executor executor = (Executor) invocation.getTarget(); Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; // 计算修改BoundSql BoundSql boundSql = ms.getBoundSql(parameter); MetaObject boundSqlHandler = MetaObject.forObject(boundSql, new DefaultObjectFactory(), new DefaultObjectWrapperFactory());
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java // public class DialectParser { // // public static Dialect parse(Configuration configuration) { // DBDialectType databaseType = null; // try { // databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); // } catch (Exception e) { // // ignore // } // if (databaseType == null) { // throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); // } // Dialect dialect = null; // switch (databaseType) { // case MYSQL: // dialect = new MySql5Dialect(); // break; // case ORACLE: // dialect = new OracleDialect(); // break; // case H2: // dialect = new H2Dialect(); // break; // } // return dialect; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/interceptor/SortListInterceptor.java import chanedi.dao.complexQuery.Sort; import chanedi.dao.dialect.Dialect; import chanedi.dao.impl.mybatis.DialectParser; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.cache.CacheKey; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.factory.DefaultObjectFactory; import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.List; import java.util.Properties; package chanedi.dao.impl.mybatis.interceptor; /** * 将sortList加入sql。 * * @author Chanedi */ @Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) @Slf4j public class SortListInterceptor implements Interceptor { private static ThreadLocal<List<Sort>> sortList = new ThreadLocal<List<Sort>>(); public static List<Sort> getSortList() { List<Sort> sortList = SortListInterceptor.sortList.get(); SortListInterceptor.sortList.remove(); return sortList; } public static void setSortList(List<Sort> sortList) { SortListInterceptor.sortList.set(sortList); } @Override public Object intercept(Invocation invocation) throws Throwable { List<Sort> sortList = getSortList(); if (sortList == null || sortList.size() == 0) { return invocation.proceed(); } Executor executor = (Executor) invocation.getTarget(); Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; RowBounds rowBounds = (RowBounds) args[2]; ResultHandler resultHandler = (ResultHandler) args[3]; // 计算修改BoundSql BoundSql boundSql = ms.getBoundSql(parameter); MetaObject boundSqlHandler = MetaObject.forObject(boundSql, new DefaultObjectFactory(), new DefaultObjectWrapperFactory());
Dialect dialect = DialectParser.parse(ms.getConfiguration());
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/log/MethodToLog.java
// Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // }
import chanedi.util.StringUtils; import java.util.HashMap;
package chanedi.generator.log; /** * Created by jijingyu625 on 2016/5/2. */ class MethodToLog extends HashMap { private String methodName; public MethodToLog(String returnType, String methodName, String argStr) { if (returnType.contains("List")) { put("isList", true); } else { put("isList", false); } put("methodName", methodName); String[] argNames = argStr.split(","); for (int i = 0; i < argNames.length; i++) { String[] arg = argNames[i].split(" "); argNames[i] = arg[arg.length - 1]; }
// Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/log/MethodToLog.java import chanedi.util.StringUtils; import java.util.HashMap; package chanedi.generator.log; /** * Created by jijingyu625 on 2016/5/2. */ class MethodToLog extends HashMap { private String methodName; public MethodToLog(String returnType, String methodName, String argStr) { if (returnType.contains("List")) { put("isList", true); } else { put("isList", false); } put("methodName", methodName); String[] argNames = argStr.split(","); for (int i = 0; i < argNames.length; i++) { String[] arg = argNames[i].split(" "); argNames[i] = arg[arg.length - 1]; }
put("isEmptyArgs", StringUtils.isEmpty(argStr));
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/TemplateRootConfig.java
// Path: QuickProject-Util/src/main/java/chanedi/util/ReflectUtils.java // public class ReflectUtils { // // public static PropertyDescriptor[] getBeanSetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanSetters(type); // } // // public static PropertyDescriptor[] getBeanGetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanGetters(type); // } // // public static Method getBeanGetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getReadMethod(); // } // // public static Method getBeanSetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getWriteMethod(); // } // // public static Field getFieldByGetter(Class<?> modelClass, String getterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(getterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // public static Field getFieldBySetter(Class<?> modelClass, String setterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(setterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // }
import chanedi.util.ReflectUtils; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Method; import java.util.Map; import java.util.Properties; import java.util.Set;
package chanedi.generator.file; /** * 非单例。 * @author Chanedi */ @Data public final class TemplateRootConfig { public static final String CONFIG_FILE_NAME = "config.properties"; private static final Logger logger = LoggerFactory.getLogger(TemplateRootConfig.class); private String rootPath = "src"; private String fileExtension = "java"; private TemplateRootConfig() { super(); } public static TemplateRootConfig getInstance(String path) throws IOException { Properties properties = new Properties(); properties.load(new FileInputStream(path + "/" + CONFIG_FILE_NAME)); TemplateRootConfig config = new TemplateRootConfig(); Set<Map.Entry<Object, Object>> entrySet = properties.entrySet(); for (Map.Entry<Object, Object> entry : entrySet) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); Method setter = null; try {
// Path: QuickProject-Util/src/main/java/chanedi/util/ReflectUtils.java // public class ReflectUtils { // // public static PropertyDescriptor[] getBeanSetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanSetters(type); // } // // public static PropertyDescriptor[] getBeanGetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanGetters(type); // } // // public static Method getBeanGetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getReadMethod(); // } // // public static Method getBeanSetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getWriteMethod(); // } // // public static Field getFieldByGetter(Class<?> modelClass, String getterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(getterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // public static Field getFieldBySetter(Class<?> modelClass, String setterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(setterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/TemplateRootConfig.java import chanedi.util.ReflectUtils; import lombok.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Method; import java.util.Map; import java.util.Properties; import java.util.Set; package chanedi.generator.file; /** * 非单例。 * @author Chanedi */ @Data public final class TemplateRootConfig { public static final String CONFIG_FILE_NAME = "config.properties"; private static final Logger logger = LoggerFactory.getLogger(TemplateRootConfig.class); private String rootPath = "src"; private String fileExtension = "java"; private TemplateRootConfig() { super(); } public static TemplateRootConfig getInstance(String path) throws IOException { Properties properties = new Properties(); properties.load(new FileInputStream(path + "/" + CONFIG_FILE_NAME)); TemplateRootConfig config = new TemplateRootConfig(); Set<Map.Entry<Object, Object>> entrySet = properties.entrySet(); for (Map.Entry<Object, Object> entry : entrySet) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); Method setter = null; try {
setter = ReflectUtils.getBeanSetter(TemplateRootConfig.class, key);
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/FilesGenerator.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Config.java // @Data // public class Config { // // private String javaPackageName; // private String javaPackagePath; // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Generate.java // public final class Generate { // // private static final Generate INSTANCE = new Generate(); // // private Generate() { // super(); // } // // public static Generate getInstance() { // return INSTANCE; // } // // public String getSerialVersionUID() { // return "private static final long serialVersionUID = " + UUID.randomUUID().getMostSignificantBits() + "L;"; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Module.java // public class Module { // // @Getter // private String name; // /** // * name的大写形式 // */ // @Setter // private String capName; // @Getter // private Collection<Bean> beans; // // public Module(File sqlFile, GlobalConfig globalConfig) throws IOException { // name = FileUtils.removeFileExtension(sqlFile.getName()); // // parseBean(sqlFile, globalConfig); // } // // private void parseBean(File sqlFile, GlobalConfig globalConfig) throws IOException { // CharStream input = new ANTLRFileStream(sqlFile.getAbsolutePath()); // CreateTableLexer lexer = new CreateTableLexer(input); // CommonTokenStream tokens = new CommonTokenStream(lexer); // CreateTableParser parser = new CreateTableParser(tokens); // ParseTree tree = parser.sql(); // // ParseTreeWalker walker = new ParseTreeWalker(); // CreateTableListenerImpl extractor = new CreateTableListenerImpl(globalConfig); // walker.walk(extractor, tree); // beans = extractor.getTables(); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/FileUtils.java // public class FileUtils { // // public static String getFileExtension(File file) { // return getFileExtension(file.getName()); // } // // public static String getFileExtension(String fileName) { // String[] splits = fileName.split("\\."); // return splits[splits.length - 1]; // } // // public static String removeFileExtension(String fileName) { // int indexOfFileExtension = fileName.lastIndexOf('.'); // return fileName.substring(0, indexOfFileExtension); // } // // public static String getFullPath(String rootPath, String path) { // if (!path.startsWith("/")) { // path = "/" + path; // } // return rootPath + path; // } // // }
import chanedi.generator.file.exception.GlobalConfigException; import chanedi.generator.model.Bean; import chanedi.generator.model.Config; import chanedi.generator.model.Generate; import chanedi.generator.model.Module; import chanedi.util.FileUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.Getter; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*;
package chanedi.generator.file; /** * @author Chanedi */ public class FilesGenerator { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Getter private GlobalConfig globalConfig;
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Config.java // @Data // public class Config { // // private String javaPackageName; // private String javaPackagePath; // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Generate.java // public final class Generate { // // private static final Generate INSTANCE = new Generate(); // // private Generate() { // super(); // } // // public static Generate getInstance() { // return INSTANCE; // } // // public String getSerialVersionUID() { // return "private static final long serialVersionUID = " + UUID.randomUUID().getMostSignificantBits() + "L;"; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Module.java // public class Module { // // @Getter // private String name; // /** // * name的大写形式 // */ // @Setter // private String capName; // @Getter // private Collection<Bean> beans; // // public Module(File sqlFile, GlobalConfig globalConfig) throws IOException { // name = FileUtils.removeFileExtension(sqlFile.getName()); // // parseBean(sqlFile, globalConfig); // } // // private void parseBean(File sqlFile, GlobalConfig globalConfig) throws IOException { // CharStream input = new ANTLRFileStream(sqlFile.getAbsolutePath()); // CreateTableLexer lexer = new CreateTableLexer(input); // CommonTokenStream tokens = new CommonTokenStream(lexer); // CreateTableParser parser = new CreateTableParser(tokens); // ParseTree tree = parser.sql(); // // ParseTreeWalker walker = new ParseTreeWalker(); // CreateTableListenerImpl extractor = new CreateTableListenerImpl(globalConfig); // walker.walk(extractor, tree); // beans = extractor.getTables(); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/FileUtils.java // public class FileUtils { // // public static String getFileExtension(File file) { // return getFileExtension(file.getName()); // } // // public static String getFileExtension(String fileName) { // String[] splits = fileName.split("\\."); // return splits[splits.length - 1]; // } // // public static String removeFileExtension(String fileName) { // int indexOfFileExtension = fileName.lastIndexOf('.'); // return fileName.substring(0, indexOfFileExtension); // } // // public static String getFullPath(String rootPath, String path) { // if (!path.startsWith("/")) { // path = "/" + path; // } // return rootPath + path; // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/FilesGenerator.java import chanedi.generator.file.exception.GlobalConfigException; import chanedi.generator.model.Bean; import chanedi.generator.model.Config; import chanedi.generator.model.Generate; import chanedi.generator.model.Module; import chanedi.util.FileUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.Getter; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; package chanedi.generator.file; /** * @author Chanedi */ public class FilesGenerator { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Getter private GlobalConfig globalConfig;
private List<Module> modules;
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/FilesGenerator.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Config.java // @Data // public class Config { // // private String javaPackageName; // private String javaPackagePath; // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Generate.java // public final class Generate { // // private static final Generate INSTANCE = new Generate(); // // private Generate() { // super(); // } // // public static Generate getInstance() { // return INSTANCE; // } // // public String getSerialVersionUID() { // return "private static final long serialVersionUID = " + UUID.randomUUID().getMostSignificantBits() + "L;"; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Module.java // public class Module { // // @Getter // private String name; // /** // * name的大写形式 // */ // @Setter // private String capName; // @Getter // private Collection<Bean> beans; // // public Module(File sqlFile, GlobalConfig globalConfig) throws IOException { // name = FileUtils.removeFileExtension(sqlFile.getName()); // // parseBean(sqlFile, globalConfig); // } // // private void parseBean(File sqlFile, GlobalConfig globalConfig) throws IOException { // CharStream input = new ANTLRFileStream(sqlFile.getAbsolutePath()); // CreateTableLexer lexer = new CreateTableLexer(input); // CommonTokenStream tokens = new CommonTokenStream(lexer); // CreateTableParser parser = new CreateTableParser(tokens); // ParseTree tree = parser.sql(); // // ParseTreeWalker walker = new ParseTreeWalker(); // CreateTableListenerImpl extractor = new CreateTableListenerImpl(globalConfig); // walker.walk(extractor, tree); // beans = extractor.getTables(); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/FileUtils.java // public class FileUtils { // // public static String getFileExtension(File file) { // return getFileExtension(file.getName()); // } // // public static String getFileExtension(String fileName) { // String[] splits = fileName.split("\\."); // return splits[splits.length - 1]; // } // // public static String removeFileExtension(String fileName) { // int indexOfFileExtension = fileName.lastIndexOf('.'); // return fileName.substring(0, indexOfFileExtension); // } // // public static String getFullPath(String rootPath, String path) { // if (!path.startsWith("/")) { // path = "/" + path; // } // return rootPath + path; // } // // }
import chanedi.generator.file.exception.GlobalConfigException; import chanedi.generator.model.Bean; import chanedi.generator.model.Config; import chanedi.generator.model.Generate; import chanedi.generator.model.Module; import chanedi.util.FileUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.Getter; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*;
package chanedi.generator.file; /** * @author Chanedi */ public class FilesGenerator { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Getter private GlobalConfig globalConfig; private List<Module> modules; private List<TemplateRoot> templateRoots;
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Config.java // @Data // public class Config { // // private String javaPackageName; // private String javaPackagePath; // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Generate.java // public final class Generate { // // private static final Generate INSTANCE = new Generate(); // // private Generate() { // super(); // } // // public static Generate getInstance() { // return INSTANCE; // } // // public String getSerialVersionUID() { // return "private static final long serialVersionUID = " + UUID.randomUUID().getMostSignificantBits() + "L;"; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Module.java // public class Module { // // @Getter // private String name; // /** // * name的大写形式 // */ // @Setter // private String capName; // @Getter // private Collection<Bean> beans; // // public Module(File sqlFile, GlobalConfig globalConfig) throws IOException { // name = FileUtils.removeFileExtension(sqlFile.getName()); // // parseBean(sqlFile, globalConfig); // } // // private void parseBean(File sqlFile, GlobalConfig globalConfig) throws IOException { // CharStream input = new ANTLRFileStream(sqlFile.getAbsolutePath()); // CreateTableLexer lexer = new CreateTableLexer(input); // CommonTokenStream tokens = new CommonTokenStream(lexer); // CreateTableParser parser = new CreateTableParser(tokens); // ParseTree tree = parser.sql(); // // ParseTreeWalker walker = new ParseTreeWalker(); // CreateTableListenerImpl extractor = new CreateTableListenerImpl(globalConfig); // walker.walk(extractor, tree); // beans = extractor.getTables(); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/FileUtils.java // public class FileUtils { // // public static String getFileExtension(File file) { // return getFileExtension(file.getName()); // } // // public static String getFileExtension(String fileName) { // String[] splits = fileName.split("\\."); // return splits[splits.length - 1]; // } // // public static String removeFileExtension(String fileName) { // int indexOfFileExtension = fileName.lastIndexOf('.'); // return fileName.substring(0, indexOfFileExtension); // } // // public static String getFullPath(String rootPath, String path) { // if (!path.startsWith("/")) { // path = "/" + path; // } // return rootPath + path; // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/FilesGenerator.java import chanedi.generator.file.exception.GlobalConfigException; import chanedi.generator.model.Bean; import chanedi.generator.model.Config; import chanedi.generator.model.Generate; import chanedi.generator.model.Module; import chanedi.util.FileUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.Getter; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; package chanedi.generator.file; /** * @author Chanedi */ public class FilesGenerator { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Getter private GlobalConfig globalConfig; private List<Module> modules; private List<TemplateRoot> templateRoots;
private Generate generate;
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/FilesGenerator.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Config.java // @Data // public class Config { // // private String javaPackageName; // private String javaPackagePath; // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Generate.java // public final class Generate { // // private static final Generate INSTANCE = new Generate(); // // private Generate() { // super(); // } // // public static Generate getInstance() { // return INSTANCE; // } // // public String getSerialVersionUID() { // return "private static final long serialVersionUID = " + UUID.randomUUID().getMostSignificantBits() + "L;"; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Module.java // public class Module { // // @Getter // private String name; // /** // * name的大写形式 // */ // @Setter // private String capName; // @Getter // private Collection<Bean> beans; // // public Module(File sqlFile, GlobalConfig globalConfig) throws IOException { // name = FileUtils.removeFileExtension(sqlFile.getName()); // // parseBean(sqlFile, globalConfig); // } // // private void parseBean(File sqlFile, GlobalConfig globalConfig) throws IOException { // CharStream input = new ANTLRFileStream(sqlFile.getAbsolutePath()); // CreateTableLexer lexer = new CreateTableLexer(input); // CommonTokenStream tokens = new CommonTokenStream(lexer); // CreateTableParser parser = new CreateTableParser(tokens); // ParseTree tree = parser.sql(); // // ParseTreeWalker walker = new ParseTreeWalker(); // CreateTableListenerImpl extractor = new CreateTableListenerImpl(globalConfig); // walker.walk(extractor, tree); // beans = extractor.getTables(); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/FileUtils.java // public class FileUtils { // // public static String getFileExtension(File file) { // return getFileExtension(file.getName()); // } // // public static String getFileExtension(String fileName) { // String[] splits = fileName.split("\\."); // return splits[splits.length - 1]; // } // // public static String removeFileExtension(String fileName) { // int indexOfFileExtension = fileName.lastIndexOf('.'); // return fileName.substring(0, indexOfFileExtension); // } // // public static String getFullPath(String rootPath, String path) { // if (!path.startsWith("/")) { // path = "/" + path; // } // return rootPath + path; // } // // }
import chanedi.generator.file.exception.GlobalConfigException; import chanedi.generator.model.Bean; import chanedi.generator.model.Config; import chanedi.generator.model.Generate; import chanedi.generator.model.Module; import chanedi.util.FileUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.Getter; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*;
package chanedi.generator.file; /** * @author Chanedi */ public class FilesGenerator { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Getter private GlobalConfig globalConfig; private List<Module> modules; private List<TemplateRoot> templateRoots; private Generate generate;
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Config.java // @Data // public class Config { // // private String javaPackageName; // private String javaPackagePath; // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Generate.java // public final class Generate { // // private static final Generate INSTANCE = new Generate(); // // private Generate() { // super(); // } // // public static Generate getInstance() { // return INSTANCE; // } // // public String getSerialVersionUID() { // return "private static final long serialVersionUID = " + UUID.randomUUID().getMostSignificantBits() + "L;"; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Module.java // public class Module { // // @Getter // private String name; // /** // * name的大写形式 // */ // @Setter // private String capName; // @Getter // private Collection<Bean> beans; // // public Module(File sqlFile, GlobalConfig globalConfig) throws IOException { // name = FileUtils.removeFileExtension(sqlFile.getName()); // // parseBean(sqlFile, globalConfig); // } // // private void parseBean(File sqlFile, GlobalConfig globalConfig) throws IOException { // CharStream input = new ANTLRFileStream(sqlFile.getAbsolutePath()); // CreateTableLexer lexer = new CreateTableLexer(input); // CommonTokenStream tokens = new CommonTokenStream(lexer); // CreateTableParser parser = new CreateTableParser(tokens); // ParseTree tree = parser.sql(); // // ParseTreeWalker walker = new ParseTreeWalker(); // CreateTableListenerImpl extractor = new CreateTableListenerImpl(globalConfig); // walker.walk(extractor, tree); // beans = extractor.getTables(); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/FileUtils.java // public class FileUtils { // // public static String getFileExtension(File file) { // return getFileExtension(file.getName()); // } // // public static String getFileExtension(String fileName) { // String[] splits = fileName.split("\\."); // return splits[splits.length - 1]; // } // // public static String removeFileExtension(String fileName) { // int indexOfFileExtension = fileName.lastIndexOf('.'); // return fileName.substring(0, indexOfFileExtension); // } // // public static String getFullPath(String rootPath, String path) { // if (!path.startsWith("/")) { // path = "/" + path; // } // return rootPath + path; // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/FilesGenerator.java import chanedi.generator.file.exception.GlobalConfigException; import chanedi.generator.model.Bean; import chanedi.generator.model.Config; import chanedi.generator.model.Generate; import chanedi.generator.model.Module; import chanedi.util.FileUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.Getter; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; package chanedi.generator.file; /** * @author Chanedi */ public class FilesGenerator { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Getter private GlobalConfig globalConfig; private List<Module> modules; private List<TemplateRoot> templateRoots; private Generate generate;
private Config config;
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/FilesGenerator.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Config.java // @Data // public class Config { // // private String javaPackageName; // private String javaPackagePath; // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Generate.java // public final class Generate { // // private static final Generate INSTANCE = new Generate(); // // private Generate() { // super(); // } // // public static Generate getInstance() { // return INSTANCE; // } // // public String getSerialVersionUID() { // return "private static final long serialVersionUID = " + UUID.randomUUID().getMostSignificantBits() + "L;"; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Module.java // public class Module { // // @Getter // private String name; // /** // * name的大写形式 // */ // @Setter // private String capName; // @Getter // private Collection<Bean> beans; // // public Module(File sqlFile, GlobalConfig globalConfig) throws IOException { // name = FileUtils.removeFileExtension(sqlFile.getName()); // // parseBean(sqlFile, globalConfig); // } // // private void parseBean(File sqlFile, GlobalConfig globalConfig) throws IOException { // CharStream input = new ANTLRFileStream(sqlFile.getAbsolutePath()); // CreateTableLexer lexer = new CreateTableLexer(input); // CommonTokenStream tokens = new CommonTokenStream(lexer); // CreateTableParser parser = new CreateTableParser(tokens); // ParseTree tree = parser.sql(); // // ParseTreeWalker walker = new ParseTreeWalker(); // CreateTableListenerImpl extractor = new CreateTableListenerImpl(globalConfig); // walker.walk(extractor, tree); // beans = extractor.getTables(); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/FileUtils.java // public class FileUtils { // // public static String getFileExtension(File file) { // return getFileExtension(file.getName()); // } // // public static String getFileExtension(String fileName) { // String[] splits = fileName.split("\\."); // return splits[splits.length - 1]; // } // // public static String removeFileExtension(String fileName) { // int indexOfFileExtension = fileName.lastIndexOf('.'); // return fileName.substring(0, indexOfFileExtension); // } // // public static String getFullPath(String rootPath, String path) { // if (!path.startsWith("/")) { // path = "/" + path; // } // return rootPath + path; // } // // }
import chanedi.generator.file.exception.GlobalConfigException; import chanedi.generator.model.Bean; import chanedi.generator.model.Config; import chanedi.generator.model.Generate; import chanedi.generator.model.Module; import chanedi.util.FileUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.Getter; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*;
package chanedi.generator.file; /** * @author Chanedi */ public class FilesGenerator { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Getter private GlobalConfig globalConfig; private List<Module> modules; private List<TemplateRoot> templateRoots; private Generate generate; private Config config; public FilesGenerator() { globalConfig = GlobalConfig.getInstance(); modules = new ArrayList<Module>(); templateRoots = new ArrayList<TemplateRoot>(); generate = Generate.getInstance(); }
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Config.java // @Data // public class Config { // // private String javaPackageName; // private String javaPackagePath; // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Generate.java // public final class Generate { // // private static final Generate INSTANCE = new Generate(); // // private Generate() { // super(); // } // // public static Generate getInstance() { // return INSTANCE; // } // // public String getSerialVersionUID() { // return "private static final long serialVersionUID = " + UUID.randomUUID().getMostSignificantBits() + "L;"; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Module.java // public class Module { // // @Getter // private String name; // /** // * name的大写形式 // */ // @Setter // private String capName; // @Getter // private Collection<Bean> beans; // // public Module(File sqlFile, GlobalConfig globalConfig) throws IOException { // name = FileUtils.removeFileExtension(sqlFile.getName()); // // parseBean(sqlFile, globalConfig); // } // // private void parseBean(File sqlFile, GlobalConfig globalConfig) throws IOException { // CharStream input = new ANTLRFileStream(sqlFile.getAbsolutePath()); // CreateTableLexer lexer = new CreateTableLexer(input); // CommonTokenStream tokens = new CommonTokenStream(lexer); // CreateTableParser parser = new CreateTableParser(tokens); // ParseTree tree = parser.sql(); // // ParseTreeWalker walker = new ParseTreeWalker(); // CreateTableListenerImpl extractor = new CreateTableListenerImpl(globalConfig); // walker.walk(extractor, tree); // beans = extractor.getTables(); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/FileUtils.java // public class FileUtils { // // public static String getFileExtension(File file) { // return getFileExtension(file.getName()); // } // // public static String getFileExtension(String fileName) { // String[] splits = fileName.split("\\."); // return splits[splits.length - 1]; // } // // public static String removeFileExtension(String fileName) { // int indexOfFileExtension = fileName.lastIndexOf('.'); // return fileName.substring(0, indexOfFileExtension); // } // // public static String getFullPath(String rootPath, String path) { // if (!path.startsWith("/")) { // path = "/" + path; // } // return rootPath + path; // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/FilesGenerator.java import chanedi.generator.file.exception.GlobalConfigException; import chanedi.generator.model.Bean; import chanedi.generator.model.Config; import chanedi.generator.model.Generate; import chanedi.generator.model.Module; import chanedi.util.FileUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import lombok.Getter; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; package chanedi.generator.file; /** * @author Chanedi */ public class FilesGenerator { protected final Logger logger = LoggerFactory.getLogger(getClass()); @Getter private GlobalConfig globalConfig; private List<Module> modules; private List<TemplateRoot> templateRoots; private Generate generate; private Config config; public FilesGenerator() { globalConfig = GlobalConfig.getInstance(); modules = new ArrayList<Module>(); templateRoots = new ArrayList<TemplateRoot>(); generate = Generate.getInstance(); }
public void process() throws GlobalConfigException {
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // }
import chanedi.dao.complexQuery.Sort; import java.util.List;
package chanedi.dao.dialect; /** * Created by unknown * Modify by Chanedi */ public class MySql5Dialect extends Dialect { public String getLimitString(String sql, boolean hasOffset) { return MySql5PageHepler.addLimitString(sql, -1, -1); } @Override public String addLimitString(String sql, int offset, int limit) { return MySql5PageHepler.addLimitString(sql, offset, limit); } @Override
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java import chanedi.dao.complexQuery.Sort; import java.util.List; package chanedi.dao.dialect; /** * Created by unknown * Modify by Chanedi */ public class MySql5Dialect extends Dialect { public String getLimitString(String sql, boolean hasOffset) { return MySql5PageHepler.addLimitString(sql, -1, -1); } @Override public String addLimitString(String sql, int offset, int limit) { return MySql5PageHepler.addLimitString(sql, offset, limit); } @Override
public String addSortString(String sql, List<Sort> sortList) {
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/CodeGenerator.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java // public class Property { // // @Getter // private String name; // @Getter // private String capitalizeName; // @Getter // private String columnName; // @Getter@Setter // private String comment; // @Getter@Setter // private PropertyType type; // // public void setColumnName(String columnName) { // this.columnName = columnName; // this.name = StringUtils.uncapitalizeCamelBySeparator(columnName, "_"); // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setName(String name) { // this.name = name; // this.columnName = name.replaceAll("([A-Z])", "_$0").toUpperCase(); // this.capitalizeName = StringUtils.capitalize(name); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // }
import chanedi.generator.model.Bean; import chanedi.generator.model.Property; import chanedi.generator.model.PropertyType; import chanedi.util.StringUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package chanedi.generator; /** * Created by jijingyu625 on 2016/4/18. */ public class CodeGenerator { private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); public static void generateSetter(File file, String className) throws IOException {
// Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java // public class Property { // // @Getter // private String name; // @Getter // private String capitalizeName; // @Getter // private String columnName; // @Getter@Setter // private String comment; // @Getter@Setter // private PropertyType type; // // public void setColumnName(String columnName) { // this.columnName = columnName; // this.name = StringUtils.uncapitalizeCamelBySeparator(columnName, "_"); // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setName(String name) { // this.name = name; // this.columnName = name.replaceAll("([A-Z])", "_$0").toUpperCase(); // this.capitalizeName = StringUtils.capitalize(name); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/CodeGenerator.java import chanedi.generator.model.Bean; import chanedi.generator.model.Property; import chanedi.generator.model.PropertyType; import chanedi.util.StringUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package chanedi.generator; /** * Created by jijingyu625 on 2016/4/18. */ public class CodeGenerator { private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); public static void generateSetter(File file, String className) throws IOException {
String variableName = StringUtils.uncapitalize(className);
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/CodeGenerator.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java // public class Property { // // @Getter // private String name; // @Getter // private String capitalizeName; // @Getter // private String columnName; // @Getter@Setter // private String comment; // @Getter@Setter // private PropertyType type; // // public void setColumnName(String columnName) { // this.columnName = columnName; // this.name = StringUtils.uncapitalizeCamelBySeparator(columnName, "_"); // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setName(String name) { // this.name = name; // this.columnName = name.replaceAll("([A-Z])", "_$0").toUpperCase(); // this.capitalizeName = StringUtils.capitalize(name); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // }
import chanedi.generator.model.Bean; import chanedi.generator.model.Property; import chanedi.generator.model.PropertyType; import chanedi.util.StringUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package chanedi.generator; /** * Created by jijingyu625 on 2016/4/18. */ public class CodeGenerator { private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); public static void generateSetter(File file, String className) throws IOException { String variableName = StringUtils.uncapitalize(className); System.out.println(className + " " + variableName + " = new " + className + "();"); BufferedReader fileReader = new BufferedReader(new FileReader(file)); while (true) { String line = fileReader.readLine(); if (line == null) { break; } if (!line.contains(";")) { continue; } String[] splits = line.split(";")[0].split(" "); String attrName = splits[splits.length - 1]; System.out.println(variableName + ".set" + StringUtils.capitalize(attrName) + "(" + attrName + ");"); } } public static void generateDaoGetMethod(boolean isReturnList, String beanNameRegex, String tableName, String attrs) throws IOException, TemplateException { File dir = resourceLoader.getResource("classpath:/tmpl/code").getFile();
// Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java // public class Property { // // @Getter // private String name; // @Getter // private String capitalizeName; // @Getter // private String columnName; // @Getter@Setter // private String comment; // @Getter@Setter // private PropertyType type; // // public void setColumnName(String columnName) { // this.columnName = columnName; // this.name = StringUtils.uncapitalizeCamelBySeparator(columnName, "_"); // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setName(String name) { // this.name = name; // this.columnName = name.replaceAll("([A-Z])", "_$0").toUpperCase(); // this.capitalizeName = StringUtils.capitalize(name); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/CodeGenerator.java import chanedi.generator.model.Bean; import chanedi.generator.model.Property; import chanedi.generator.model.PropertyType; import chanedi.util.StringUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package chanedi.generator; /** * Created by jijingyu625 on 2016/4/18. */ public class CodeGenerator { private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); public static void generateSetter(File file, String className) throws IOException { String variableName = StringUtils.uncapitalize(className); System.out.println(className + " " + variableName + " = new " + className + "();"); BufferedReader fileReader = new BufferedReader(new FileReader(file)); while (true) { String line = fileReader.readLine(); if (line == null) { break; } if (!line.contains(";")) { continue; } String[] splits = line.split(";")[0].split(" "); String attrName = splits[splits.length - 1]; System.out.println(variableName + ".set" + StringUtils.capitalize(attrName) + "(" + attrName + ");"); } } public static void generateDaoGetMethod(boolean isReturnList, String beanNameRegex, String tableName, String attrs) throws IOException, TemplateException { File dir = resourceLoader.getResource("classpath:/tmpl/code").getFile();
Bean bean = new Bean();
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/CodeGenerator.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java // public class Property { // // @Getter // private String name; // @Getter // private String capitalizeName; // @Getter // private String columnName; // @Getter@Setter // private String comment; // @Getter@Setter // private PropertyType type; // // public void setColumnName(String columnName) { // this.columnName = columnName; // this.name = StringUtils.uncapitalizeCamelBySeparator(columnName, "_"); // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setName(String name) { // this.name = name; // this.columnName = name.replaceAll("([A-Z])", "_$0").toUpperCase(); // this.capitalizeName = StringUtils.capitalize(name); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // }
import chanedi.generator.model.Bean; import chanedi.generator.model.Property; import chanedi.generator.model.PropertyType; import chanedi.util.StringUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package chanedi.generator; /** * Created by jijingyu625 on 2016/4/18. */ public class CodeGenerator { private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); public static void generateSetter(File file, String className) throws IOException { String variableName = StringUtils.uncapitalize(className); System.out.println(className + " " + variableName + " = new " + className + "();"); BufferedReader fileReader = new BufferedReader(new FileReader(file)); while (true) { String line = fileReader.readLine(); if (line == null) { break; } if (!line.contains(";")) { continue; } String[] splits = line.split(";")[0].split(" "); String attrName = splits[splits.length - 1]; System.out.println(variableName + ".set" + StringUtils.capitalize(attrName) + "(" + attrName + ");"); } } public static void generateDaoGetMethod(boolean isReturnList, String beanNameRegex, String tableName, String attrs) throws IOException, TemplateException { File dir = resourceLoader.getResource("classpath:/tmpl/code").getFile(); Bean bean = new Bean(); bean.setTableName(tableName); String[] attrArray = attrs.replace(", ", ",").split(","); for (String attr : attrArray) { try { String[] splits = attr.split(" ");
// Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java // public class Property { // // @Getter // private String name; // @Getter // private String capitalizeName; // @Getter // private String columnName; // @Getter@Setter // private String comment; // @Getter@Setter // private PropertyType type; // // public void setColumnName(String columnName) { // this.columnName = columnName; // this.name = StringUtils.uncapitalizeCamelBySeparator(columnName, "_"); // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setName(String name) { // this.name = name; // this.columnName = name.replaceAll("([A-Z])", "_$0").toUpperCase(); // this.capitalizeName = StringUtils.capitalize(name); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/CodeGenerator.java import chanedi.generator.model.Bean; import chanedi.generator.model.Property; import chanedi.generator.model.PropertyType; import chanedi.util.StringUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package chanedi.generator; /** * Created by jijingyu625 on 2016/4/18. */ public class CodeGenerator { private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); public static void generateSetter(File file, String className) throws IOException { String variableName = StringUtils.uncapitalize(className); System.out.println(className + " " + variableName + " = new " + className + "();"); BufferedReader fileReader = new BufferedReader(new FileReader(file)); while (true) { String line = fileReader.readLine(); if (line == null) { break; } if (!line.contains(";")) { continue; } String[] splits = line.split(";")[0].split(" "); String attrName = splits[splits.length - 1]; System.out.println(variableName + ".set" + StringUtils.capitalize(attrName) + "(" + attrName + ");"); } } public static void generateDaoGetMethod(boolean isReturnList, String beanNameRegex, String tableName, String attrs) throws IOException, TemplateException { File dir = resourceLoader.getResource("classpath:/tmpl/code").getFile(); Bean bean = new Bean(); bean.setTableName(tableName); String[] attrArray = attrs.replace(", ", ",").split(","); for (String attr : attrArray) { try { String[] splits = attr.split(" ");
Property property = new Property();
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/CodeGenerator.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java // public class Property { // // @Getter // private String name; // @Getter // private String capitalizeName; // @Getter // private String columnName; // @Getter@Setter // private String comment; // @Getter@Setter // private PropertyType type; // // public void setColumnName(String columnName) { // this.columnName = columnName; // this.name = StringUtils.uncapitalizeCamelBySeparator(columnName, "_"); // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setName(String name) { // this.name = name; // this.columnName = name.replaceAll("([A-Z])", "_$0").toUpperCase(); // this.capitalizeName = StringUtils.capitalize(name); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // }
import chanedi.generator.model.Bean; import chanedi.generator.model.Property; import chanedi.generator.model.PropertyType; import chanedi.util.StringUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;
package chanedi.generator; /** * Created by jijingyu625 on 2016/4/18. */ public class CodeGenerator { private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); public static void generateSetter(File file, String className) throws IOException { String variableName = StringUtils.uncapitalize(className); System.out.println(className + " " + variableName + " = new " + className + "();"); BufferedReader fileReader = new BufferedReader(new FileReader(file)); while (true) { String line = fileReader.readLine(); if (line == null) { break; } if (!line.contains(";")) { continue; } String[] splits = line.split(";")[0].split(" "); String attrName = splits[splits.length - 1]; System.out.println(variableName + ".set" + StringUtils.capitalize(attrName) + "(" + attrName + ");"); } } public static void generateDaoGetMethod(boolean isReturnList, String beanNameRegex, String tableName, String attrs) throws IOException, TemplateException { File dir = resourceLoader.getResource("classpath:/tmpl/code").getFile(); Bean bean = new Bean(); bean.setTableName(tableName); String[] attrArray = attrs.replace(", ", ",").split(","); for (String attr : attrArray) { try { String[] splits = attr.split(" "); Property property = new Property();
// Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java // public class Bean { // // @Getter@Setter // private String name; // @Getter@Setter // private String capitalizeName; // @Getter // private String tableName; // @Getter@Setter // private String comment; // private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 // private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 // // public void addProperty(Property property) { // propertyColumnNameMap.put(property.getColumnName(), property); // propertyList.add(property); // } // // public Property getPropertyByColumnName(String columnName) { // return propertyColumnNameMap.get(columnName); // } // // public Collection<Property> getProperties() { // return propertyList; // } // // public void setTableName(String tableName) { // this.tableName = tableName; // setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_")); // } // // public void setName(String name) { // this.name = name; // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setCapitalizeName(String capitalizeName) { // this.capitalizeName = capitalizeName; // this.name = StringUtils.uncapitalize(capitalizeName);; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Property.java // public class Property { // // @Getter // private String name; // @Getter // private String capitalizeName; // @Getter // private String columnName; // @Getter@Setter // private String comment; // @Getter@Setter // private PropertyType type; // // public void setColumnName(String columnName) { // this.columnName = columnName; // this.name = StringUtils.uncapitalizeCamelBySeparator(columnName, "_"); // this.capitalizeName = StringUtils.capitalize(name); // } // // public void setName(String name) { // this.name = name; // this.columnName = name.replaceAll("([A-Z])", "_$0").toUpperCase(); // this.capitalizeName = StringUtils.capitalize(name); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/CodeGenerator.java import chanedi.generator.model.Bean; import chanedi.generator.model.Property; import chanedi.generator.model.PropertyType; import chanedi.util.StringUtils; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.*; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; package chanedi.generator; /** * Created by jijingyu625 on 2016/4/18. */ public class CodeGenerator { private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); public static void generateSetter(File file, String className) throws IOException { String variableName = StringUtils.uncapitalize(className); System.out.println(className + " " + variableName + " = new " + className + "();"); BufferedReader fileReader = new BufferedReader(new FileReader(file)); while (true) { String line = fileReader.readLine(); if (line == null) { break; } if (!line.contains(";")) { continue; } String[] splits = line.split(";")[0].split(" "); String attrName = splits[splits.length - 1]; System.out.println(variableName + ".set" + StringUtils.capitalize(attrName) + "(" + attrName + ");"); } } public static void generateDaoGetMethod(boolean isReturnList, String beanNameRegex, String tableName, String attrs) throws IOException, TemplateException { File dir = resourceLoader.getResource("classpath:/tmpl/code").getFile(); Bean bean = new Bean(); bean.setTableName(tableName); String[] attrArray = attrs.replace(", ", ",").split(","); for (String attr : attrArray) { try { String[] splits = attr.split(" "); Property property = new Property();
property.setType(new PropertyType(splits[0]));
chanedi/QuickProject
QuickProject-Generator/src/test/java/chanedi/generator/LoggerGeneratorTest.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/log/LoggerGenerator.java // public class LoggerGenerator { // // private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); // // public static void generateLogger(File file) throws IOException, TemplateException { // File tmplDir = resourceLoader.getResource("classpath:/tmpl/log").getFile(); // Configuration cfg = new Configuration(); // cfg.setDirectoryForTemplateLoading(tmplDir); // cfg.setObjectWrapper(new DefaultObjectWrapper()); // Template logTmplIn = cfg.getTemplate("methodIn.ftl"); // Template logTmplOut = cfg.getTemplate("methodOut.ftl"); // Template logTmplDaoResult = cfg.getTemplate("daoResult.ftl"); // Template logTmplCondition = cfg.getTemplate("condition.ftl"); // // String filePath = file.getPath(); // File tempFile = new File(filePath + ".tmp"); // // BufferedWriter fileWriter = null; // BufferedReader fileReader = null; // try { // fileWriter = new BufferedWriter(new FileWriter(tempFile)); // fileReader = new BufferedReader(new FileReader(file)); // // MethodToLog methodToLog = null; // LineMatcher lastLineMatcher = null; // while (true) { // String line = fileReader.readLine(); // if (line == null) { // break; // } // // LineMatcher currentLineMatcher = LineMatcher.matcher(line); // // if (lastLineMatcher != null && methodToLog != null && (currentLineMatcher == null || currentLineMatcher.getMatcherType() != LineMatcher.MatcherType.LOG)) { // if (lastLineMatcher.getMatcherType() == LineMatcher.MatcherType.METHOD) { // 方法入口 // logTmplIn.process(methodToLog, fileWriter); // fileWriter.newLine(); // } else if (lastLineMatcher.getMatcherType() == LineMatcher.MatcherType.DAO_RESULT) { // MatchResult matcher = lastLineMatcher.getMatcher(); // logTmplDaoResult.process(new DaoReturnToLog(matcher.group(1), matcher.group(2), methodToLog.getMethodName()), fileWriter); // fileWriter.newLine(); // } else if (lastLineMatcher.getMatcherType() == LineMatcher.MatcherType.CONDITION_IF) { // MatchResult matcher = lastLineMatcher.getMatcher(); // logTmplCondition.process(new ConditionToLog(matcher.group(2), methodToLog.getMethodName()), fileWriter); // fileWriter.newLine(); // } else if (lastLineMatcher.getMatcherType() == LineMatcher.MatcherType.CONDITION_ELSE) { // logTmplCondition.process(new ConditionToLog("else", methodToLog.getMethodName()), fileWriter); // fileWriter.newLine(); // } // } // // if (currentLineMatcher != null) { // Matcher matcher = currentLineMatcher.getMatcher(); // if (currentLineMatcher.getMatcherType() == LineMatcher.MatcherType.METHOD) { // methodToLog = new MethodToLog(matcher.group(1), matcher.group(2), matcher.group(3)); // } else if (currentLineMatcher.getMatcherType() == LineMatcher.MatcherType.METHOD) { // methodToLog = null; // } else if (currentLineMatcher.getMatcherType() == LineMatcher.MatcherType.RETURN) { // 方法出口 // if (methodToLog != null) { // methodToLog.setReturnValue(matcher.group(1)); // logTmplOut.process(methodToLog, fileWriter); // fileWriter.newLine(); // } // } else if (currentLineMatcher.getMatcherType() == LineMatcher.MatcherType.END_METHOD) { // 方法出口 // if (methodToLog != null) { // logTmplOut.process(methodToLog, fileWriter); // fileWriter.newLine(); // } // } // } // // fileWriter.write(line); // fileWriter.newLine(); // // lastLineMatcher = currentLineMatcher; // } // } finally { // if (fileWriter != null) { // try { // fileWriter.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // if (fileReader != null) { // try { // fileReader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // file.delete(); // tempFile.renameTo(file); // } // // }
import chanedi.generator.log.LoggerGenerator; import org.junit.Test; import java.io.File;
package chanedi.generator; /** * Created by jijingyu625 on 2016/4/24. */ public class LoggerGeneratorTest { @Test public void generateLogger() throws Exception { File file = new File("D:\\IdeaProjects\\yeb-app\\src\\main\\java\\com\\lufax\\common\\file\\batch\\validate\\validator\\fileinfo\\FileInfoFileRecordCountValidator.java");
// Path: QuickProject-Generator/src/main/java/chanedi/generator/log/LoggerGenerator.java // public class LoggerGenerator { // // private static ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); // // public static void generateLogger(File file) throws IOException, TemplateException { // File tmplDir = resourceLoader.getResource("classpath:/tmpl/log").getFile(); // Configuration cfg = new Configuration(); // cfg.setDirectoryForTemplateLoading(tmplDir); // cfg.setObjectWrapper(new DefaultObjectWrapper()); // Template logTmplIn = cfg.getTemplate("methodIn.ftl"); // Template logTmplOut = cfg.getTemplate("methodOut.ftl"); // Template logTmplDaoResult = cfg.getTemplate("daoResult.ftl"); // Template logTmplCondition = cfg.getTemplate("condition.ftl"); // // String filePath = file.getPath(); // File tempFile = new File(filePath + ".tmp"); // // BufferedWriter fileWriter = null; // BufferedReader fileReader = null; // try { // fileWriter = new BufferedWriter(new FileWriter(tempFile)); // fileReader = new BufferedReader(new FileReader(file)); // // MethodToLog methodToLog = null; // LineMatcher lastLineMatcher = null; // while (true) { // String line = fileReader.readLine(); // if (line == null) { // break; // } // // LineMatcher currentLineMatcher = LineMatcher.matcher(line); // // if (lastLineMatcher != null && methodToLog != null && (currentLineMatcher == null || currentLineMatcher.getMatcherType() != LineMatcher.MatcherType.LOG)) { // if (lastLineMatcher.getMatcherType() == LineMatcher.MatcherType.METHOD) { // 方法入口 // logTmplIn.process(methodToLog, fileWriter); // fileWriter.newLine(); // } else if (lastLineMatcher.getMatcherType() == LineMatcher.MatcherType.DAO_RESULT) { // MatchResult matcher = lastLineMatcher.getMatcher(); // logTmplDaoResult.process(new DaoReturnToLog(matcher.group(1), matcher.group(2), methodToLog.getMethodName()), fileWriter); // fileWriter.newLine(); // } else if (lastLineMatcher.getMatcherType() == LineMatcher.MatcherType.CONDITION_IF) { // MatchResult matcher = lastLineMatcher.getMatcher(); // logTmplCondition.process(new ConditionToLog(matcher.group(2), methodToLog.getMethodName()), fileWriter); // fileWriter.newLine(); // } else if (lastLineMatcher.getMatcherType() == LineMatcher.MatcherType.CONDITION_ELSE) { // logTmplCondition.process(new ConditionToLog("else", methodToLog.getMethodName()), fileWriter); // fileWriter.newLine(); // } // } // // if (currentLineMatcher != null) { // Matcher matcher = currentLineMatcher.getMatcher(); // if (currentLineMatcher.getMatcherType() == LineMatcher.MatcherType.METHOD) { // methodToLog = new MethodToLog(matcher.group(1), matcher.group(2), matcher.group(3)); // } else if (currentLineMatcher.getMatcherType() == LineMatcher.MatcherType.METHOD) { // methodToLog = null; // } else if (currentLineMatcher.getMatcherType() == LineMatcher.MatcherType.RETURN) { // 方法出口 // if (methodToLog != null) { // methodToLog.setReturnValue(matcher.group(1)); // logTmplOut.process(methodToLog, fileWriter); // fileWriter.newLine(); // } // } else if (currentLineMatcher.getMatcherType() == LineMatcher.MatcherType.END_METHOD) { // 方法出口 // if (methodToLog != null) { // logTmplOut.process(methodToLog, fileWriter); // fileWriter.newLine(); // } // } // } // // fileWriter.write(line); // fileWriter.newLine(); // // lastLineMatcher = currentLineMatcher; // } // } finally { // if (fileWriter != null) { // try { // fileWriter.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // if (fileReader != null) { // try { // fileReader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // file.delete(); // tempFile.renameTo(file); // } // // } // Path: QuickProject-Generator/src/test/java/chanedi/generator/LoggerGeneratorTest.java import chanedi.generator.log.LoggerGenerator; import org.junit.Test; import java.io.File; package chanedi.generator; /** * Created by jijingyu625 on 2016/4/24. */ public class LoggerGeneratorTest { @Test public void generateLogger() throws Exception { File file = new File("D:\\IdeaProjects\\yeb-app\\src\\main\\java\\com\\lufax\\common\\file\\batch\\validate\\validator\\fileinfo\\FileInfoFileRecordCountValidator.java");
LoggerGenerator.generateLogger(file);
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java // public class H2Dialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java // public class MySql5Dialect extends Dialect { // // public String getLimitString(String sql, boolean hasOffset) { // return MySql5PageHepler.addLimitString(sql, -1, -1); // } // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // public boolean supportsLimit() { // return true; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java // public class OracleDialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // sql = sql.trim(); // boolean isForUpdate = false; // if (sql.toLowerCase().endsWith(" FOR UPDATE")) { // sql = sql.substring(0, sql.length() - 11); // isForUpdate = true; // } // // StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); // // pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); // // pagingSelect.append(sql); // // pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); // // if (isForUpdate) { // pagingSelect.append(" FOR UPDATE"); // } // // return pagingSelect.toString(); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // }
import chanedi.dao.dialect.Dialect; import chanedi.dao.dialect.H2Dialect; import chanedi.dao.dialect.MySql5Dialect; import chanedi.dao.dialect.OracleDialect; import chanedi.enums.DBDialectType; import org.apache.ibatis.session.Configuration;
package chanedi.dao.impl.mybatis; /** * @author Chanedi */ public class DialectParser { public static Dialect parse(Configuration configuration) {
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java // public class H2Dialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java // public class MySql5Dialect extends Dialect { // // public String getLimitString(String sql, boolean hasOffset) { // return MySql5PageHepler.addLimitString(sql, -1, -1); // } // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // public boolean supportsLimit() { // return true; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java // public class OracleDialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // sql = sql.trim(); // boolean isForUpdate = false; // if (sql.toLowerCase().endsWith(" FOR UPDATE")) { // sql = sql.substring(0, sql.length() - 11); // isForUpdate = true; // } // // StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); // // pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); // // pagingSelect.append(sql); // // pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); // // if (isForUpdate) { // pagingSelect.append(" FOR UPDATE"); // } // // return pagingSelect.toString(); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java import chanedi.dao.dialect.Dialect; import chanedi.dao.dialect.H2Dialect; import chanedi.dao.dialect.MySql5Dialect; import chanedi.dao.dialect.OracleDialect; import chanedi.enums.DBDialectType; import org.apache.ibatis.session.Configuration; package chanedi.dao.impl.mybatis; /** * @author Chanedi */ public class DialectParser { public static Dialect parse(Configuration configuration) {
DBDialectType databaseType = null;
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java // public class H2Dialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java // public class MySql5Dialect extends Dialect { // // public String getLimitString(String sql, boolean hasOffset) { // return MySql5PageHepler.addLimitString(sql, -1, -1); // } // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // public boolean supportsLimit() { // return true; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java // public class OracleDialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // sql = sql.trim(); // boolean isForUpdate = false; // if (sql.toLowerCase().endsWith(" FOR UPDATE")) { // sql = sql.substring(0, sql.length() - 11); // isForUpdate = true; // } // // StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); // // pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); // // pagingSelect.append(sql); // // pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); // // if (isForUpdate) { // pagingSelect.append(" FOR UPDATE"); // } // // return pagingSelect.toString(); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // }
import chanedi.dao.dialect.Dialect; import chanedi.dao.dialect.H2Dialect; import chanedi.dao.dialect.MySql5Dialect; import chanedi.dao.dialect.OracleDialect; import chanedi.enums.DBDialectType; import org.apache.ibatis.session.Configuration;
package chanedi.dao.impl.mybatis; /** * @author Chanedi */ public class DialectParser { public static Dialect parse(Configuration configuration) { DBDialectType databaseType = null; try { databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); } catch (Exception e) { // ignore } if (databaseType == null) { throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); } Dialect dialect = null; switch (databaseType) { case MYSQL:
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java // public class H2Dialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java // public class MySql5Dialect extends Dialect { // // public String getLimitString(String sql, boolean hasOffset) { // return MySql5PageHepler.addLimitString(sql, -1, -1); // } // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // public boolean supportsLimit() { // return true; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java // public class OracleDialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // sql = sql.trim(); // boolean isForUpdate = false; // if (sql.toLowerCase().endsWith(" FOR UPDATE")) { // sql = sql.substring(0, sql.length() - 11); // isForUpdate = true; // } // // StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); // // pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); // // pagingSelect.append(sql); // // pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); // // if (isForUpdate) { // pagingSelect.append(" FOR UPDATE"); // } // // return pagingSelect.toString(); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java import chanedi.dao.dialect.Dialect; import chanedi.dao.dialect.H2Dialect; import chanedi.dao.dialect.MySql5Dialect; import chanedi.dao.dialect.OracleDialect; import chanedi.enums.DBDialectType; import org.apache.ibatis.session.Configuration; package chanedi.dao.impl.mybatis; /** * @author Chanedi */ public class DialectParser { public static Dialect parse(Configuration configuration) { DBDialectType databaseType = null; try { databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); } catch (Exception e) { // ignore } if (databaseType == null) { throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); } Dialect dialect = null; switch (databaseType) { case MYSQL:
dialect = new MySql5Dialect();
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java // public class H2Dialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java // public class MySql5Dialect extends Dialect { // // public String getLimitString(String sql, boolean hasOffset) { // return MySql5PageHepler.addLimitString(sql, -1, -1); // } // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // public boolean supportsLimit() { // return true; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java // public class OracleDialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // sql = sql.trim(); // boolean isForUpdate = false; // if (sql.toLowerCase().endsWith(" FOR UPDATE")) { // sql = sql.substring(0, sql.length() - 11); // isForUpdate = true; // } // // StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); // // pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); // // pagingSelect.append(sql); // // pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); // // if (isForUpdate) { // pagingSelect.append(" FOR UPDATE"); // } // // return pagingSelect.toString(); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // }
import chanedi.dao.dialect.Dialect; import chanedi.dao.dialect.H2Dialect; import chanedi.dao.dialect.MySql5Dialect; import chanedi.dao.dialect.OracleDialect; import chanedi.enums.DBDialectType; import org.apache.ibatis.session.Configuration;
package chanedi.dao.impl.mybatis; /** * @author Chanedi */ public class DialectParser { public static Dialect parse(Configuration configuration) { DBDialectType databaseType = null; try { databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); } catch (Exception e) { // ignore } if (databaseType == null) { throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); } Dialect dialect = null; switch (databaseType) { case MYSQL: dialect = new MySql5Dialect(); break; case ORACLE:
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java // public class H2Dialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java // public class MySql5Dialect extends Dialect { // // public String getLimitString(String sql, boolean hasOffset) { // return MySql5PageHepler.addLimitString(sql, -1, -1); // } // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // public boolean supportsLimit() { // return true; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java // public class OracleDialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // sql = sql.trim(); // boolean isForUpdate = false; // if (sql.toLowerCase().endsWith(" FOR UPDATE")) { // sql = sql.substring(0, sql.length() - 11); // isForUpdate = true; // } // // StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); // // pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); // // pagingSelect.append(sql); // // pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); // // if (isForUpdate) { // pagingSelect.append(" FOR UPDATE"); // } // // return pagingSelect.toString(); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java import chanedi.dao.dialect.Dialect; import chanedi.dao.dialect.H2Dialect; import chanedi.dao.dialect.MySql5Dialect; import chanedi.dao.dialect.OracleDialect; import chanedi.enums.DBDialectType; import org.apache.ibatis.session.Configuration; package chanedi.dao.impl.mybatis; /** * @author Chanedi */ public class DialectParser { public static Dialect parse(Configuration configuration) { DBDialectType databaseType = null; try { databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); } catch (Exception e) { // ignore } if (databaseType == null) { throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); } Dialect dialect = null; switch (databaseType) { case MYSQL: dialect = new MySql5Dialect(); break; case ORACLE:
dialect = new OracleDialect();
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java // public class H2Dialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java // public class MySql5Dialect extends Dialect { // // public String getLimitString(String sql, boolean hasOffset) { // return MySql5PageHepler.addLimitString(sql, -1, -1); // } // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // public boolean supportsLimit() { // return true; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java // public class OracleDialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // sql = sql.trim(); // boolean isForUpdate = false; // if (sql.toLowerCase().endsWith(" FOR UPDATE")) { // sql = sql.substring(0, sql.length() - 11); // isForUpdate = true; // } // // StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); // // pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); // // pagingSelect.append(sql); // // pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); // // if (isForUpdate) { // pagingSelect.append(" FOR UPDATE"); // } // // return pagingSelect.toString(); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // }
import chanedi.dao.dialect.Dialect; import chanedi.dao.dialect.H2Dialect; import chanedi.dao.dialect.MySql5Dialect; import chanedi.dao.dialect.OracleDialect; import chanedi.enums.DBDialectType; import org.apache.ibatis.session.Configuration;
package chanedi.dao.impl.mybatis; /** * @author Chanedi */ public class DialectParser { public static Dialect parse(Configuration configuration) { DBDialectType databaseType = null; try { databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); } catch (Exception e) { // ignore } if (databaseType == null) { throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); } Dialect dialect = null; switch (databaseType) { case MYSQL: dialect = new MySql5Dialect(); break; case ORACLE: dialect = new OracleDialect(); break; case H2:
// Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java // public abstract class Dialect { // // public abstract String addLimitString(String sql, int skipResults, int maxResults); // // public abstract String addSortString(String sql, List<Sort> sortList); // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java // public class H2Dialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/MySql5Dialect.java // public class MySql5Dialect extends Dialect { // // public String getLimitString(String sql, boolean hasOffset) { // return MySql5PageHepler.addLimitString(sql, -1, -1); // } // // @Override // public String addLimitString(String sql, int offset, int limit) { // return MySql5PageHepler.addLimitString(sql, offset, limit); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // public boolean supportsLimit() { // return true; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java // public class OracleDialect extends Dialect { // // @Override // public String addLimitString(String sql, int offset, int limit) { // sql = sql.trim(); // boolean isForUpdate = false; // if (sql.toLowerCase().endsWith(" FOR UPDATE")) { // sql = sql.substring(0, sql.length() - 11); // isForUpdate = true; // } // // StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); // // pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); // // pagingSelect.append(sql); // // pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); // // if (isForUpdate) { // pagingSelect.append(" FOR UPDATE"); // } // // return pagingSelect.toString(); // } // // @Override // public String addSortString(String sql, List<Sort> sortList) { // return SortHelper.addSortString(sql, sortList); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/DialectParser.java import chanedi.dao.dialect.Dialect; import chanedi.dao.dialect.H2Dialect; import chanedi.dao.dialect.MySql5Dialect; import chanedi.dao.dialect.OracleDialect; import chanedi.enums.DBDialectType; import org.apache.ibatis.session.Configuration; package chanedi.dao.impl.mybatis; /** * @author Chanedi */ public class DialectParser { public static Dialect parse(Configuration configuration) { DBDialectType databaseType = null; try { databaseType = DBDialectType.valueOf(configuration.getVariables().getProperty("dialect").toUpperCase()); } catch (Exception e) { // ignore } if (databaseType == null) { throw new RuntimeException("the value of the dialect property in configuration.xml is not defined : " + configuration.getVariables().getProperty("dialect")); } Dialect dialect = null; switch (databaseType) { case MYSQL: dialect = new MySql5Dialect(); break; case ORACLE: dialect = new OracleDialect(); break; case H2:
dialect = new H2Dialect();
chanedi/QuickProject
QuickProject-Core/src/test/java/chanedi/test/DaoTest.java
// Path: QuickProject-Core/src/test/java/chanedi/bas/dao/EventProcessDAO.java // public interface EventProcessDAO extends EntityDAO<EventProcess> { // } // // Path: QuickProject-Core/src/test/java/chanedi/bas/model/EventProcess.java // @Data // @Table(name = "T_EVE_EVENT_PROCESS") // public class EventProcess extends Entity { // // private static final long serialVersionUID = -5227564951878481064L; // // private String modifyUserCode; // private String processType; // private Double stepInterval; // private Date modifyTime; // private Date createTime; // private Integer processSeq; // private String eventTypeId; // private Object id; // private String status; // private String createUserCode; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // }
import chanedi.bas.dao.EventProcessDAO; import chanedi.bas.model.EventProcess; import chanedi.dao.complexQuery.Sort; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DataSourceUtils; import javax.annotation.Resource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List;
package chanedi.test; /** * @author Chanedi */ public class DaoTest extends BaseTest { @Resource
// Path: QuickProject-Core/src/test/java/chanedi/bas/dao/EventProcessDAO.java // public interface EventProcessDAO extends EntityDAO<EventProcess> { // } // // Path: QuickProject-Core/src/test/java/chanedi/bas/model/EventProcess.java // @Data // @Table(name = "T_EVE_EVENT_PROCESS") // public class EventProcess extends Entity { // // private static final long serialVersionUID = -5227564951878481064L; // // private String modifyUserCode; // private String processType; // private Double stepInterval; // private Date modifyTime; // private Date createTime; // private Integer processSeq; // private String eventTypeId; // private Object id; // private String status; // private String createUserCode; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // Path: QuickProject-Core/src/test/java/chanedi/test/DaoTest.java import chanedi.bas.dao.EventProcessDAO; import chanedi.bas.model.EventProcess; import chanedi.dao.complexQuery.Sort; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DataSourceUtils; import javax.annotation.Resource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; package chanedi.test; /** * @author Chanedi */ public class DaoTest extends BaseTest { @Resource
private EventProcessDAO eventProcessDAO;
chanedi/QuickProject
QuickProject-Core/src/test/java/chanedi/test/DaoTest.java
// Path: QuickProject-Core/src/test/java/chanedi/bas/dao/EventProcessDAO.java // public interface EventProcessDAO extends EntityDAO<EventProcess> { // } // // Path: QuickProject-Core/src/test/java/chanedi/bas/model/EventProcess.java // @Data // @Table(name = "T_EVE_EVENT_PROCESS") // public class EventProcess extends Entity { // // private static final long serialVersionUID = -5227564951878481064L; // // private String modifyUserCode; // private String processType; // private Double stepInterval; // private Date modifyTime; // private Date createTime; // private Integer processSeq; // private String eventTypeId; // private Object id; // private String status; // private String createUserCode; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // }
import chanedi.bas.dao.EventProcessDAO; import chanedi.bas.model.EventProcess; import chanedi.dao.complexQuery.Sort; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DataSourceUtils; import javax.annotation.Resource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List;
package chanedi.test; /** * @author Chanedi */ public class DaoTest extends BaseTest { @Resource private EventProcessDAO eventProcessDAO; @Resource private DataSource dataSource; @Before public void setUp() throws SQLException { Connection conn = DataSourceUtils.getConnection(dataSource); Statement statement = conn.createStatement(); statement.execute("DROP TABLE T_EVE_EVENT_PROCESS IF EXISTS;"); statement.execute("create table T_EVE_EVENT_PROCESS \n" + "(\n" + " ID VARCHAR2(50) not null,\n" + " EVENT_TYPE_ID VARCHAR2(50),\n" + " PROCESS_SEQ NUMERIC(2),\n" + " PROCESS_TYPE VARCHAR2(50),\n" + " CREATE_USER_CODE VARCHAR2(50),\n" + " CREATE_TIME TIMESTAMP,\n" + " MODIFY_USER_CODE VARCHAR2(50),\n" + " MODIFY_TIME TIMESTAMP,\n" + " STEP_INTERVAL NUMERIC(8,2),\n" + " STATUS VARCHAR2(50),\n" + " constraint PK_EVE_EVENT_PROCESS_ID primary key (ID)\n" + ");");
// Path: QuickProject-Core/src/test/java/chanedi/bas/dao/EventProcessDAO.java // public interface EventProcessDAO extends EntityDAO<EventProcess> { // } // // Path: QuickProject-Core/src/test/java/chanedi/bas/model/EventProcess.java // @Data // @Table(name = "T_EVE_EVENT_PROCESS") // public class EventProcess extends Entity { // // private static final long serialVersionUID = -5227564951878481064L; // // private String modifyUserCode; // private String processType; // private Double stepInterval; // private Date modifyTime; // private Date createTime; // private Integer processSeq; // private String eventTypeId; // private Object id; // private String status; // private String createUserCode; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // Path: QuickProject-Core/src/test/java/chanedi/test/DaoTest.java import chanedi.bas.dao.EventProcessDAO; import chanedi.bas.model.EventProcess; import chanedi.dao.complexQuery.Sort; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DataSourceUtils; import javax.annotation.Resource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; package chanedi.test; /** * @author Chanedi */ public class DaoTest extends BaseTest { @Resource private EventProcessDAO eventProcessDAO; @Resource private DataSource dataSource; @Before public void setUp() throws SQLException { Connection conn = DataSourceUtils.getConnection(dataSource); Statement statement = conn.createStatement(); statement.execute("DROP TABLE T_EVE_EVENT_PROCESS IF EXISTS;"); statement.execute("create table T_EVE_EVENT_PROCESS \n" + "(\n" + " ID VARCHAR2(50) not null,\n" + " EVENT_TYPE_ID VARCHAR2(50),\n" + " PROCESS_SEQ NUMERIC(2),\n" + " PROCESS_TYPE VARCHAR2(50),\n" + " CREATE_USER_CODE VARCHAR2(50),\n" + " CREATE_TIME TIMESTAMP,\n" + " MODIFY_USER_CODE VARCHAR2(50),\n" + " MODIFY_TIME TIMESTAMP,\n" + " STEP_INTERVAL NUMERIC(8,2),\n" + " STATUS VARCHAR2(50),\n" + " constraint PK_EVE_EVENT_PROCESS_ID primary key (ID)\n" + ");");
EventProcess eventProcess = new EventProcess();
chanedi/QuickProject
QuickProject-Core/src/test/java/chanedi/test/DaoTest.java
// Path: QuickProject-Core/src/test/java/chanedi/bas/dao/EventProcessDAO.java // public interface EventProcessDAO extends EntityDAO<EventProcess> { // } // // Path: QuickProject-Core/src/test/java/chanedi/bas/model/EventProcess.java // @Data // @Table(name = "T_EVE_EVENT_PROCESS") // public class EventProcess extends Entity { // // private static final long serialVersionUID = -5227564951878481064L; // // private String modifyUserCode; // private String processType; // private Double stepInterval; // private Date modifyTime; // private Date createTime; // private Integer processSeq; // private String eventTypeId; // private Object id; // private String status; // private String createUserCode; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // }
import chanedi.bas.dao.EventProcessDAO; import chanedi.bas.model.EventProcess; import chanedi.dao.complexQuery.Sort; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DataSourceUtils; import javax.annotation.Resource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List;
" EVENT_TYPE_ID VARCHAR2(50),\n" + " PROCESS_SEQ NUMERIC(2),\n" + " PROCESS_TYPE VARCHAR2(50),\n" + " CREATE_USER_CODE VARCHAR2(50),\n" + " CREATE_TIME TIMESTAMP,\n" + " MODIFY_USER_CODE VARCHAR2(50),\n" + " MODIFY_TIME TIMESTAMP,\n" + " STEP_INTERVAL NUMERIC(8,2),\n" + " STATUS VARCHAR2(50),\n" + " constraint PK_EVE_EVENT_PROCESS_ID primary key (ID)\n" + ");"); EventProcess eventProcess = new EventProcess(); eventProcess.setId("test"); eventProcess.setProcessType("test"); eventProcessDAO.insert(eventProcess); eventProcess.setId("test1"); eventProcess.setProcessType("test"); eventProcessDAO.insert(eventProcess); } @Test public void testGetAll() { eventProcessDAO.getAll(); } @Test public void testGet() { EventProcess params = new EventProcess(); params.setProcessType("test"); logger.info(eventProcessDAO.get(params, null, 0, 1).toString());
// Path: QuickProject-Core/src/test/java/chanedi/bas/dao/EventProcessDAO.java // public interface EventProcessDAO extends EntityDAO<EventProcess> { // } // // Path: QuickProject-Core/src/test/java/chanedi/bas/model/EventProcess.java // @Data // @Table(name = "T_EVE_EVENT_PROCESS") // public class EventProcess extends Entity { // // private static final long serialVersionUID = -5227564951878481064L; // // private String modifyUserCode; // private String processType; // private Double stepInterval; // private Date modifyTime; // private Date createTime; // private Integer processSeq; // private String eventTypeId; // private Object id; // private String status; // private String createUserCode; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // Path: QuickProject-Core/src/test/java/chanedi/test/DaoTest.java import chanedi.bas.dao.EventProcessDAO; import chanedi.bas.model.EventProcess; import chanedi.dao.complexQuery.Sort; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DataSourceUtils; import javax.annotation.Resource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; " EVENT_TYPE_ID VARCHAR2(50),\n" + " PROCESS_SEQ NUMERIC(2),\n" + " PROCESS_TYPE VARCHAR2(50),\n" + " CREATE_USER_CODE VARCHAR2(50),\n" + " CREATE_TIME TIMESTAMP,\n" + " MODIFY_USER_CODE VARCHAR2(50),\n" + " MODIFY_TIME TIMESTAMP,\n" + " STEP_INTERVAL NUMERIC(8,2),\n" + " STATUS VARCHAR2(50),\n" + " constraint PK_EVE_EVENT_PROCESS_ID primary key (ID)\n" + ");"); EventProcess eventProcess = new EventProcess(); eventProcess.setId("test"); eventProcess.setProcessType("test"); eventProcessDAO.insert(eventProcess); eventProcess.setId("test1"); eventProcess.setProcessType("test"); eventProcessDAO.insert(eventProcess); } @Test public void testGetAll() { eventProcessDAO.getAll(); } @Test public void testGet() { EventProcess params = new EventProcess(); params.setProcessType("test"); logger.info(eventProcessDAO.get(params, null, 0, 1).toString());
List<Sort> sortList = new ArrayList<Sort>();
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java
// Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // }
import chanedi.util.StringUtils; import lombok.Getter; import lombok.Setter; import java.util.*;
package chanedi.generator.model; /** * @author Chanedi */ public class Bean { @Getter@Setter private String name; @Getter@Setter private String capitalizeName; @Getter private String tableName; @Getter@Setter private String comment; private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 public void addProperty(Property property) { propertyColumnNameMap.put(property.getColumnName(), property); propertyList.add(property); } public Property getPropertyByColumnName(String columnName) { return propertyColumnNameMap.get(columnName); } public Collection<Property> getProperties() { return propertyList; } public void setTableName(String tableName) { this.tableName = tableName;
// Path: QuickProject-Util/src/main/java/chanedi/util/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // public static String capitalizeCamelBySeparator(String str, String separatorChars) { // if (str == null || str.length() == 0) { // return str; // } // String[] splits = str.toLowerCase().split(separatorChars); // StringBuffer result = new StringBuffer(); // for (String split : splits) { // result.append(capitalize(split)); // } // return result.toString(); // } // // public static String uncapitalizeCamelBySeparator(String str, String separatorChars) { // return uncapitalize(capitalizeCamelBySeparator(str, separatorChars)); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/Bean.java import chanedi.util.StringUtils; import lombok.Getter; import lombok.Setter; import java.util.*; package chanedi.generator.model; /** * @author Chanedi */ public class Bean { @Getter@Setter private String name; @Getter@Setter private String capitalizeName; @Getter private String tableName; @Getter@Setter private String comment; private Map<String, Property> propertyColumnNameMap = new HashMap<String, Property>(); // 乱序 private List<Property> propertyList = new ArrayList<Property>(); // 按加入的顺序 public void addProperty(Property property) { propertyColumnNameMap.put(property.getColumnName(), property); propertyList.add(property); } public Property getPropertyByColumnName(String columnName) { return propertyColumnNameMap.get(columnName); } public Collection<Property> getProperties() { return propertyList; } public void setTableName(String tableName) { this.tableName = tableName;
setName(StringUtils.uncapitalizeCamelBySeparator(tableName, "_"));
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/PropertyTypeContext.java
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/ConfigException.java // public class ConfigException extends Exception { // // public ConfigException() { // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/PropertiesWithOrder.java // public class PropertiesWithOrder extends Properties { // // private List<Object> keyList = new ArrayList<Object>(); // // @Override // public synchronized Object put(Object key, Object value) { // if (!keyList.contains(key)) { // keyList.add(key); // } // return super.put(key, value); // } // // /** // * 返回key值,该key值顺序与文件中的顺序相同。 // * @return // */ // public List<Object> keysInOrder() { // return keyList; // } // // }
import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.ConfigException; import chanedi.generator.model.PropertyType; import chanedi.util.PropertiesWithOrder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties;
package chanedi.generator.file; /** * 单例。 * @author Chanedi */ @NotThreadSafe public final class PropertyTypeContext { private Logger logger = LoggerFactory.getLogger(getClass()); private static PropertyTypeContext instance; private static final String DB_CONVERT_FILE_NAME = "dbToJava_"; private static final String TYPE_DEF_FILE_NAME = "typeDefinition"; private static final String CONFIG_FILE_SUFFIX = ".properties"; private String typeMatchConfigPath = "classpath:/typeMatch/";
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/ConfigException.java // public class ConfigException extends Exception { // // public ConfigException() { // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/PropertiesWithOrder.java // public class PropertiesWithOrder extends Properties { // // private List<Object> keyList = new ArrayList<Object>(); // // @Override // public synchronized Object put(Object key, Object value) { // if (!keyList.contains(key)) { // keyList.add(key); // } // return super.put(key, value); // } // // /** // * 返回key值,该key值顺序与文件中的顺序相同。 // * @return // */ // public List<Object> keysInOrder() { // return keyList; // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/PropertyTypeContext.java import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.ConfigException; import chanedi.generator.model.PropertyType; import chanedi.util.PropertiesWithOrder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; package chanedi.generator.file; /** * 单例。 * @author Chanedi */ @NotThreadSafe public final class PropertyTypeContext { private Logger logger = LoggerFactory.getLogger(getClass()); private static PropertyTypeContext instance; private static final String DB_CONVERT_FILE_NAME = "dbToJava_"; private static final String TYPE_DEF_FILE_NAME = "typeDefinition"; private static final String CONFIG_FILE_SUFFIX = ".properties"; private String typeMatchConfigPath = "classpath:/typeMatch/";
private Map<String, PropertyType> propertyTypes = new HashMap<String, PropertyType>(); // key 为 javaType
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/PropertyTypeContext.java
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/ConfigException.java // public class ConfigException extends Exception { // // public ConfigException() { // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/PropertiesWithOrder.java // public class PropertiesWithOrder extends Properties { // // private List<Object> keyList = new ArrayList<Object>(); // // @Override // public synchronized Object put(Object key, Object value) { // if (!keyList.contains(key)) { // keyList.add(key); // } // return super.put(key, value); // } // // /** // * 返回key值,该key值顺序与文件中的顺序相同。 // * @return // */ // public List<Object> keysInOrder() { // return keyList; // } // // }
import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.ConfigException; import chanedi.generator.model.PropertyType; import chanedi.util.PropertiesWithOrder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties;
package chanedi.generator.file; /** * 单例。 * @author Chanedi */ @NotThreadSafe public final class PropertyTypeContext { private Logger logger = LoggerFactory.getLogger(getClass()); private static PropertyTypeContext instance; private static final String DB_CONVERT_FILE_NAME = "dbToJava_"; private static final String TYPE_DEF_FILE_NAME = "typeDefinition"; private static final String CONFIG_FILE_SUFFIX = ".properties"; private String typeMatchConfigPath = "classpath:/typeMatch/"; private Map<String, PropertyType> propertyTypes = new HashMap<String, PropertyType>(); // key 为 javaType
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/ConfigException.java // public class ConfigException extends Exception { // // public ConfigException() { // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/PropertiesWithOrder.java // public class PropertiesWithOrder extends Properties { // // private List<Object> keyList = new ArrayList<Object>(); // // @Override // public synchronized Object put(Object key, Object value) { // if (!keyList.contains(key)) { // keyList.add(key); // } // return super.put(key, value); // } // // /** // * 返回key值,该key值顺序与文件中的顺序相同。 // * @return // */ // public List<Object> keysInOrder() { // return keyList; // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/PropertyTypeContext.java import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.ConfigException; import chanedi.generator.model.PropertyType; import chanedi.util.PropertiesWithOrder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; package chanedi.generator.file; /** * 单例。 * @author Chanedi */ @NotThreadSafe public final class PropertyTypeContext { private Logger logger = LoggerFactory.getLogger(getClass()); private static PropertyTypeContext instance; private static final String DB_CONVERT_FILE_NAME = "dbToJava_"; private static final String TYPE_DEF_FILE_NAME = "typeDefinition"; private static final String CONFIG_FILE_SUFFIX = ".properties"; private String typeMatchConfigPath = "classpath:/typeMatch/"; private Map<String, PropertyType> propertyTypes = new HashMap<String, PropertyType>(); // key 为 javaType
private PropertiesWithOrder dbConvertProp = new PropertiesWithOrder();
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/PropertyTypeContext.java
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/ConfigException.java // public class ConfigException extends Exception { // // public ConfigException() { // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/PropertiesWithOrder.java // public class PropertiesWithOrder extends Properties { // // private List<Object> keyList = new ArrayList<Object>(); // // @Override // public synchronized Object put(Object key, Object value) { // if (!keyList.contains(key)) { // keyList.add(key); // } // return super.put(key, value); // } // // /** // * 返回key值,该key值顺序与文件中的顺序相同。 // * @return // */ // public List<Object> keysInOrder() { // return keyList; // } // // }
import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.ConfigException; import chanedi.generator.model.PropertyType; import chanedi.util.PropertiesWithOrder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties;
package chanedi.generator.file; /** * 单例。 * @author Chanedi */ @NotThreadSafe public final class PropertyTypeContext { private Logger logger = LoggerFactory.getLogger(getClass()); private static PropertyTypeContext instance; private static final String DB_CONVERT_FILE_NAME = "dbToJava_"; private static final String TYPE_DEF_FILE_NAME = "typeDefinition"; private static final String CONFIG_FILE_SUFFIX = ".properties"; private String typeMatchConfigPath = "classpath:/typeMatch/"; private Map<String, PropertyType> propertyTypes = new HashMap<String, PropertyType>(); // key 为 javaType private PropertiesWithOrder dbConvertProp = new PropertiesWithOrder(); private ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver();
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/ConfigException.java // public class ConfigException extends Exception { // // public ConfigException() { // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/PropertiesWithOrder.java // public class PropertiesWithOrder extends Properties { // // private List<Object> keyList = new ArrayList<Object>(); // // @Override // public synchronized Object put(Object key, Object value) { // if (!keyList.contains(key)) { // keyList.add(key); // } // return super.put(key, value); // } // // /** // * 返回key值,该key值顺序与文件中的顺序相同。 // * @return // */ // public List<Object> keysInOrder() { // return keyList; // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/PropertyTypeContext.java import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.ConfigException; import chanedi.generator.model.PropertyType; import chanedi.util.PropertiesWithOrder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; package chanedi.generator.file; /** * 单例。 * @author Chanedi */ @NotThreadSafe public final class PropertyTypeContext { private Logger logger = LoggerFactory.getLogger(getClass()); private static PropertyTypeContext instance; private static final String DB_CONVERT_FILE_NAME = "dbToJava_"; private static final String TYPE_DEF_FILE_NAME = "typeDefinition"; private static final String CONFIG_FILE_SUFFIX = ".properties"; private String typeMatchConfigPath = "classpath:/typeMatch/"; private Map<String, PropertyType> propertyTypes = new HashMap<String, PropertyType>(); // key 为 javaType private PropertiesWithOrder dbConvertProp = new PropertiesWithOrder(); private ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver();
private PropertyTypeContext() throws ConfigException {
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/PropertyTypeContext.java
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/ConfigException.java // public class ConfigException extends Exception { // // public ConfigException() { // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/PropertiesWithOrder.java // public class PropertiesWithOrder extends Properties { // // private List<Object> keyList = new ArrayList<Object>(); // // @Override // public synchronized Object put(Object key, Object value) { // if (!keyList.contains(key)) { // keyList.add(key); // } // return super.put(key, value); // } // // /** // * 返回key值,该key值顺序与文件中的顺序相同。 // * @return // */ // public List<Object> keysInOrder() { // return keyList; // } // // }
import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.ConfigException; import chanedi.generator.model.PropertyType; import chanedi.util.PropertiesWithOrder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties;
package chanedi.generator.file; /** * 单例。 * @author Chanedi */ @NotThreadSafe public final class PropertyTypeContext { private Logger logger = LoggerFactory.getLogger(getClass()); private static PropertyTypeContext instance; private static final String DB_CONVERT_FILE_NAME = "dbToJava_"; private static final String TYPE_DEF_FILE_NAME = "typeDefinition"; private static final String CONFIG_FILE_SUFFIX = ".properties"; private String typeMatchConfigPath = "classpath:/typeMatch/"; private Map<String, PropertyType> propertyTypes = new HashMap<String, PropertyType>(); // key 为 javaType private PropertiesWithOrder dbConvertProp = new PropertiesWithOrder(); private ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); private PropertyTypeContext() throws ConfigException { super(); GlobalConfig globalConfig = GlobalConfig.getInstance();
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/ConfigException.java // public class ConfigException extends Exception { // // public ConfigException() { // } // // public ConfigException(String message) { // super(message); // } // // public ConfigException(String message, Throwable cause) { // super(message, cause); // } // // public ConfigException(Throwable cause) { // super(cause); // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/PropertyType.java // public class PropertyType extends HashMap { // // public PropertyType(String javaType) { // super(); // addType("java", javaType); // } // // public void addType(String typeKey, String type) { // put(typeKey, type); // } // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/PropertiesWithOrder.java // public class PropertiesWithOrder extends Properties { // // private List<Object> keyList = new ArrayList<Object>(); // // @Override // public synchronized Object put(Object key, Object value) { // if (!keyList.contains(key)) { // keyList.add(key); // } // return super.put(key, value); // } // // /** // * 返回key值,该key值顺序与文件中的顺序相同。 // * @return // */ // public List<Object> keysInOrder() { // return keyList; // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/PropertyTypeContext.java import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.ConfigException; import chanedi.generator.model.PropertyType; import chanedi.util.PropertiesWithOrder; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; package chanedi.generator.file; /** * 单例。 * @author Chanedi */ @NotThreadSafe public final class PropertyTypeContext { private Logger logger = LoggerFactory.getLogger(getClass()); private static PropertyTypeContext instance; private static final String DB_CONVERT_FILE_NAME = "dbToJava_"; private static final String TYPE_DEF_FILE_NAME = "typeDefinition"; private static final String CONFIG_FILE_SUFFIX = ".properties"; private String typeMatchConfigPath = "classpath:/typeMatch/"; private Map<String, PropertyType> propertyTypes = new HashMap<String, PropertyType>(); // key 为 javaType private PropertiesWithOrder dbConvertProp = new PropertiesWithOrder(); private ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); private PropertyTypeContext() throws ConfigException { super(); GlobalConfig globalConfig = GlobalConfig.getInstance();
DBDialectType dialect = globalConfig.getDbDialectType();
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/GlobalConfig.java
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // }
import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.GlobalConfigException; import lombok.Getter; import lombok.Setter; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.File; import java.io.IOException;
package chanedi.generator.file; /** * @author Chanedi * 单例 */ public final class GlobalConfig { @Getter private static GlobalConfig instance = new GlobalConfig(); private ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); @Setter@Getter private String outProjectPath = "D:/gen"; @Setter private String inputSqlPath = "classpath:/sql"; @Setter private String tmplPath = "classpath:/tmpl/file"; @Setter@Getter private String javaPackageName = "com."; @Setter@Getter private String javaPackagePath = "com/"; @Setter@Getter private String typeMatchConfigPath = "classpath:/typeMatch"; /** 表名命名法则(正则表达式),java类名请用"(\\w+)"表示。如:"^T_(\w+)$"则表名为T_USER_INFO,java类名为UserInfo。默认为"(\\w+)$"(表名即类名,没有前缀) */ @Setter@Getter private String beanNameRegex = "(\\w+)$"; /** 为true则已存在的文件不重新生成。默认为true。 */ @Setter@Getter private boolean ignoreExists = true; /** * 数据库方言,默认为ORACLE。 * @see DBDialectType */ @Setter@Getter
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/GlobalConfig.java import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.GlobalConfigException; import lombok.Getter; import lombok.Setter; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.File; import java.io.IOException; package chanedi.generator.file; /** * @author Chanedi * 单例 */ public final class GlobalConfig { @Getter private static GlobalConfig instance = new GlobalConfig(); private ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); @Setter@Getter private String outProjectPath = "D:/gen"; @Setter private String inputSqlPath = "classpath:/sql"; @Setter private String tmplPath = "classpath:/tmpl/file"; @Setter@Getter private String javaPackageName = "com."; @Setter@Getter private String javaPackagePath = "com/"; @Setter@Getter private String typeMatchConfigPath = "classpath:/typeMatch"; /** 表名命名法则(正则表达式),java类名请用"(\\w+)"表示。如:"^T_(\w+)$"则表名为T_USER_INFO,java类名为UserInfo。默认为"(\\w+)$"(表名即类名,没有前缀) */ @Setter@Getter private String beanNameRegex = "(\\w+)$"; /** 为true则已存在的文件不重新生成。默认为true。 */ @Setter@Getter private boolean ignoreExists = true; /** * 数据库方言,默认为ORACLE。 * @see DBDialectType */ @Setter@Getter
private DBDialectType dbDialectType = DBDialectType.ORACLE;
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/file/GlobalConfig.java
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // }
import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.GlobalConfigException; import lombok.Getter; import lombok.Setter; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.File; import java.io.IOException;
package chanedi.generator.file; /** * @author Chanedi * 单例 */ public final class GlobalConfig { @Getter private static GlobalConfig instance = new GlobalConfig(); private ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); @Setter@Getter private String outProjectPath = "D:/gen"; @Setter private String inputSqlPath = "classpath:/sql"; @Setter private String tmplPath = "classpath:/tmpl/file"; @Setter@Getter private String javaPackageName = "com."; @Setter@Getter private String javaPackagePath = "com/"; @Setter@Getter private String typeMatchConfigPath = "classpath:/typeMatch"; /** 表名命名法则(正则表达式),java类名请用"(\\w+)"表示。如:"^T_(\w+)$"则表名为T_USER_INFO,java类名为UserInfo。默认为"(\\w+)$"(表名即类名,没有前缀) */ @Setter@Getter private String beanNameRegex = "(\\w+)$"; /** 为true则已存在的文件不重新生成。默认为true。 */ @Setter@Getter private boolean ignoreExists = true; /** * 数据库方言,默认为ORACLE。 * @see DBDialectType */ @Setter@Getter private DBDialectType dbDialectType = DBDialectType.ORACLE; private GlobalConfig() { super(); }
// Path: QuickProject-Util/src/main/java/chanedi/enums/DBDialectType.java // public enum DBDialectType { // // MYSQL("mysql"), ORACLE("oracle"), H2("h2"); // // private String type; // // private DBDialectType(String type) { // this.type = type; // } // // @Override // public String toString() { // return type; // } // // } // // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/exception/GlobalConfigException.java // public class GlobalConfigException extends ConfigException { // // private static final String errorMessage = "全局配置参数错误:"; // // public GlobalConfigException(String configParam) { // super(errorMessage + configParam); // } // // public GlobalConfigException(String configParam, String message) { // super(errorMessage + configParam + "(" + message + ")"); // } // // public GlobalConfigException(String configParam, Throwable cause) { // super(errorMessage + configParam, cause); // } // // public GlobalConfigException(String configParam, String message, Throwable cause) { // super(errorMessage + configParam + "(" + message + ")", cause); // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/file/GlobalConfig.java import chanedi.enums.DBDialectType; import chanedi.generator.file.exception.GlobalConfigException; import lombok.Getter; import lombok.Setter; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.File; import java.io.IOException; package chanedi.generator.file; /** * @author Chanedi * 单例 */ public final class GlobalConfig { @Getter private static GlobalConfig instance = new GlobalConfig(); private ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver(); @Setter@Getter private String outProjectPath = "D:/gen"; @Setter private String inputSqlPath = "classpath:/sql"; @Setter private String tmplPath = "classpath:/tmpl/file"; @Setter@Getter private String javaPackageName = "com."; @Setter@Getter private String javaPackagePath = "com/"; @Setter@Getter private String typeMatchConfigPath = "classpath:/typeMatch"; /** 表名命名法则(正则表达式),java类名请用"(\\w+)"表示。如:"^T_(\w+)$"则表名为T_USER_INFO,java类名为UserInfo。默认为"(\\w+)$"(表名即类名,没有前缀) */ @Setter@Getter private String beanNameRegex = "(\\w+)$"; /** 为true则已存在的文件不重新生成。默认为true。 */ @Setter@Getter private boolean ignoreExists = true; /** * 数据库方言,默认为ORACLE。 * @see DBDialectType */ @Setter@Getter private DBDialectType dbDialectType = DBDialectType.ORACLE; private GlobalConfig() { super(); }
public File getInputSqlFile() throws GlobalConfigException {
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // }
import chanedi.dao.complexQuery.Sort; import java.util.List;
package chanedi.dao.dialect; /** * Created by unknown * Modify by Chanedi */ public class OracleDialect extends Dialect { @Override public String addLimitString(String sql, int offset, int limit) { sql = sql.trim(); boolean isForUpdate = false; if (sql.toLowerCase().endsWith(" FOR UPDATE")) { sql = sql.substring(0, sql.length() - 11); isForUpdate = true; } StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); pagingSelect.append(sql); pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); if (isForUpdate) { pagingSelect.append(" FOR UPDATE"); } return pagingSelect.toString(); } @Override
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/OracleDialect.java import chanedi.dao.complexQuery.Sort; import java.util.List; package chanedi.dao.dialect; /** * Created by unknown * Modify by Chanedi */ public class OracleDialect extends Dialect { @Override public String addLimitString(String sql, int offset, int limit) { sql = sql.trim(); boolean isForUpdate = false; if (sql.toLowerCase().endsWith(" FOR UPDATE")) { sql = sql.substring(0, sql.length() - 11); isForUpdate = true; } StringBuffer pagingSelect = new StringBuffer(sql.length() + 100); pagingSelect.append("SELECT * FROM ( SELECT ROW_.*, ROWNUM ROWNUM_ FROM ( "); pagingSelect.append(sql); pagingSelect.append(" ) ROW_ ) WHERE ROWNUM_ > " + offset + " AND ROWNUM_ <= " + (offset + limit)); if (isForUpdate) { pagingSelect.append(" FOR UPDATE"); } return pagingSelect.toString(); } @Override
public String addSortString(String sql, List<Sort> sortList) {
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // }
import chanedi.dao.complexQuery.Sort; import java.util.List;
package chanedi.dao.dialect; /** * 数据库方言。 * Created by unknown * Modify by Chanedi */ public abstract class Dialect { public abstract String addLimitString(String sql, int skipResults, int maxResults);
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/Dialect.java import chanedi.dao.complexQuery.Sort; import java.util.List; package chanedi.dao.dialect; /** * 数据库方言。 * Created by unknown * Modify by Chanedi */ public abstract class Dialect { public abstract String addLimitString(String sql, int skipResults, int maxResults);
public abstract String addSortString(String sql, List<Sort> sortList);
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/service/EntityService.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/CustomQueryParam.java // public class CustomQueryParam implements Serializable { // // private static final long serialVersionUID = -825693104603690276L; // @Getter // protected String property; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // }
import chanedi.dao.complexQuery.CustomQueryParam; import chanedi.dao.complexQuery.Sort; import chanedi.model.Entity; import org.springframework.transaction.annotation.Transactional; import java.util.List;
package chanedi.service; /** * Created by Chanedi */ //@Transactional(rollbackFor = { Exception.class }, readOnly = true) public interface EntityService<T extends Entity> { public List<T> getAll(); public T getById(Object id); public int countGet(T findParams); public List<T> get(T findParams);
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/CustomQueryParam.java // public class CustomQueryParam implements Serializable { // // private static final long serialVersionUID = -825693104603690276L; // @Getter // protected String property; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // } // Path: QuickProject-Core/src/main/java/chanedi/service/EntityService.java import chanedi.dao.complexQuery.CustomQueryParam; import chanedi.dao.complexQuery.Sort; import chanedi.model.Entity; import org.springframework.transaction.annotation.Transactional; import java.util.List; package chanedi.service; /** * Created by Chanedi */ //@Transactional(rollbackFor = { Exception.class }, readOnly = true) public interface EntityService<T extends Entity> { public List<T> getAll(); public T getById(Object id); public int countGet(T findParams); public List<T> get(T findParams);
public List<T> get(T findParams, List<Sort> sortList, Integer start, Integer limit);
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/service/EntityService.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/CustomQueryParam.java // public class CustomQueryParam implements Serializable { // // private static final long serialVersionUID = -825693104603690276L; // @Getter // protected String property; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // }
import chanedi.dao.complexQuery.CustomQueryParam; import chanedi.dao.complexQuery.Sort; import chanedi.model.Entity; import org.springframework.transaction.annotation.Transactional; import java.util.List;
package chanedi.service; /** * Created by Chanedi */ //@Transactional(rollbackFor = { Exception.class }, readOnly = true) public interface EntityService<T extends Entity> { public List<T> getAll(); public T getById(Object id); public int countGet(T findParams); public List<T> get(T findParams); public List<T> get(T findParams, List<Sort> sortList, Integer start, Integer limit); public int countFind(T findParams); public List<T> find(T findParams); public List<T> find(T findParams, List<Sort> sortList, Integer start, Integer limit);
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/CustomQueryParam.java // public class CustomQueryParam implements Serializable { // // private static final long serialVersionUID = -825693104603690276L; // @Getter // protected String property; // // } // // Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // // Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // } // Path: QuickProject-Core/src/main/java/chanedi/service/EntityService.java import chanedi.dao.complexQuery.CustomQueryParam; import chanedi.dao.complexQuery.Sort; import chanedi.model.Entity; import org.springframework.transaction.annotation.Transactional; import java.util.List; package chanedi.service; /** * Created by Chanedi */ //@Transactional(rollbackFor = { Exception.class }, readOnly = true) public interface EntityService<T extends Entity> { public List<T> getAll(); public T getById(Object id); public int countGet(T findParams); public List<T> get(T findParams); public List<T> get(T findParams, List<Sort> sortList, Integer start, Integer limit); public int countFind(T findParams); public List<T> find(T findParams); public List<T> find(T findParams, List<Sort> sortList, Integer start, Integer limit);
public int countQuery(List<CustomQueryParam> customQueryParams);
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/exception/MessageKeyException.java
// Path: QuickProject-Util/src/main/java/chanedi/context/ContextUtils.java // @Slf4j // public class ContextUtils { // // private static ApplicationContext applicationContext; // // public static ApplicationContext getApplicationContext() { // synchronized (ContextUtils.class) { // while (applicationContext == null) { // try { // ContextUtils.class.wait(60000); // if (applicationContext == null) { // log.warn("Have been waiting for ApplicationContext to be set for 1 minute", new Exception()); // } // } catch (InterruptedException ex) { // log.debug("getApplicationContext, wait interrupted"); // } // } // return applicationContext; // } // } // // public static Object getBean(Class<?> beanType) { // return getApplicationContext().getBean(beanType); // } // // public static Object getBean(String name) { // return getApplicationContext().getBean(name); // } // // protected static void setApplicationContext(ApplicationContext applicationContext) { // synchronized (ContextUtils.class) { // ContextUtils.applicationContext = applicationContext; // ContextUtils.class.notifyAll(); // } // } // // }
import chanedi.context.ContextUtils; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder;
package chanedi.exception; public class MessageKeyException extends RuntimeException { private Object[] messageArgs; public MessageKeyException() { super("unknown"); } public MessageKeyException(String messageKey, Throwable cause, Object... messageArgs) { super(messageKey, cause); this.messageArgs = messageArgs; } public MessageKeyException(String messageKey, Object... messageArgs) { super(messageKey); this.messageArgs = messageArgs; } public MessageKeyException(Throwable cause) { super("unknown", cause); } public String getLocalizedMessage() {
// Path: QuickProject-Util/src/main/java/chanedi/context/ContextUtils.java // @Slf4j // public class ContextUtils { // // private static ApplicationContext applicationContext; // // public static ApplicationContext getApplicationContext() { // synchronized (ContextUtils.class) { // while (applicationContext == null) { // try { // ContextUtils.class.wait(60000); // if (applicationContext == null) { // log.warn("Have been waiting for ApplicationContext to be set for 1 minute", new Exception()); // } // } catch (InterruptedException ex) { // log.debug("getApplicationContext, wait interrupted"); // } // } // return applicationContext; // } // } // // public static Object getBean(Class<?> beanType) { // return getApplicationContext().getBean(beanType); // } // // public static Object getBean(String name) { // return getApplicationContext().getBean(name); // } // // protected static void setApplicationContext(ApplicationContext applicationContext) { // synchronized (ContextUtils.class) { // ContextUtils.applicationContext = applicationContext; // ContextUtils.class.notifyAll(); // } // } // // } // Path: QuickProject-Core/src/main/java/chanedi/exception/MessageKeyException.java import chanedi.context.ContextUtils; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; package chanedi.exception; public class MessageKeyException extends RuntimeException { private Object[] messageArgs; public MessageKeyException() { super("unknown"); } public MessageKeyException(String messageKey, Throwable cause, Object... messageArgs) { super(messageKey, cause); this.messageArgs = messageArgs; } public MessageKeyException(String messageKey, Object... messageArgs) { super(messageKey); this.messageArgs = messageArgs; } public MessageKeyException(Throwable cause) { super("unknown", cause); } public String getLocalizedMessage() {
MessageSource messageSource = (MessageSource) ContextUtils.getBean("messageSource");
chanedi/QuickProject
QuickProject-Generator/src/main/java/chanedi/generator/model/TemplateRoot.java
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/TemplateRootConfig.java // @Data // public final class TemplateRootConfig { // // public static final String CONFIG_FILE_NAME = "config.properties"; // private static final Logger logger = LoggerFactory.getLogger(TemplateRootConfig.class); // private String rootPath = "src"; // private String fileExtension = "java"; // // private TemplateRootConfig() { // super(); // } // // public static TemplateRootConfig getInstance(String path) throws IOException { // Properties properties = new Properties(); // properties.load(new FileInputStream(path + "/" + CONFIG_FILE_NAME)); // // TemplateRootConfig config = new TemplateRootConfig(); // // Set<Map.Entry<Object, Object>> entrySet = properties.entrySet(); // for (Map.Entry<Object, Object> entry : entrySet) { // String key = (String) entry.getKey(); // String value = (String) entry.getValue(); // Method setter = null; // try { // setter = ReflectUtils.getBeanSetter(TemplateRootConfig.class, key); // setter.invoke(config, value); // } catch (Exception e) { // logger.warn("config.properties中有无法处理的配置项:{}, 已忽略"); // continue; // } // } // // return config; // } // // }
import chanedi.generator.file.TemplateRootConfig; import lombok.Getter; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package chanedi.generator.model; /** * @author Chanedi */ public class TemplateRoot { @Getter
// Path: QuickProject-Generator/src/main/java/chanedi/generator/file/TemplateRootConfig.java // @Data // public final class TemplateRootConfig { // // public static final String CONFIG_FILE_NAME = "config.properties"; // private static final Logger logger = LoggerFactory.getLogger(TemplateRootConfig.class); // private String rootPath = "src"; // private String fileExtension = "java"; // // private TemplateRootConfig() { // super(); // } // // public static TemplateRootConfig getInstance(String path) throws IOException { // Properties properties = new Properties(); // properties.load(new FileInputStream(path + "/" + CONFIG_FILE_NAME)); // // TemplateRootConfig config = new TemplateRootConfig(); // // Set<Map.Entry<Object, Object>> entrySet = properties.entrySet(); // for (Map.Entry<Object, Object> entry : entrySet) { // String key = (String) entry.getKey(); // String value = (String) entry.getValue(); // Method setter = null; // try { // setter = ReflectUtils.getBeanSetter(TemplateRootConfig.class, key); // setter.invoke(config, value); // } catch (Exception e) { // logger.warn("config.properties中有无法处理的配置项:{}, 已忽略"); // continue; // } // } // // return config; // } // // } // Path: QuickProject-Generator/src/main/java/chanedi/generator/model/TemplateRoot.java import chanedi.generator.file.TemplateRootConfig; import lombok.Getter; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; package chanedi.generator.model; /** * @author Chanedi */ public class TemplateRoot { @Getter
private TemplateRootConfig config;
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // }
import chanedi.dao.complexQuery.Sort; import java.util.List;
package chanedi.dao.dialect; /** * @author Chanedi */ public class H2Dialect extends Dialect { @Override public String addLimitString(String sql, int offset, int limit) { return MySql5PageHepler.addLimitString(sql, offset, limit); } @Override
// Path: QuickProject-Core/src/main/java/chanedi/dao/complexQuery/Sort.java // @Data // public class Sort implements Serializable { // // private static final long serialVersionUID = 7026434198845897214L; // private String property; // private String tableAlias; // private String column; // private Direction direction; // // public Sort() { // super(); // direction = Direction.ASC; // } // // public Sort(String property) { // this(); // this.property = property; // } // // public Sort(String property, Direction direction) { // this(); // this.property = property; // this.direction = direction; // } // // public static enum Direction { // ASC, DESC; // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/dialect/H2Dialect.java import chanedi.dao.complexQuery.Sort; import java.util.List; package chanedi.dao.dialect; /** * @author Chanedi */ public class H2Dialect extends Dialect { @Override public String addLimitString(String sql, int offset, int limit) { return MySql5PageHepler.addLimitString(sql, offset, limit); } @Override
public String addSortString(String sql, List<Sort> sortList) {
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/modelParser/ModelUtils.java
// Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/ReflectUtils.java // public class ReflectUtils { // // public static PropertyDescriptor[] getBeanSetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanSetters(type); // } // // public static PropertyDescriptor[] getBeanGetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanGetters(type); // } // // public static Method getBeanGetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getReadMethod(); // } // // public static Method getBeanSetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getWriteMethod(); // } // // public static Field getFieldByGetter(Class<?> modelClass, String getterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(getterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // public static Field getFieldBySetter(Class<?> modelClass, String setterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(setterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // }
import chanedi.model.Entity; import chanedi.util.ReflectUtils; import lombok.extern.slf4j.Slf4j; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map;
package chanedi.dao.impl.mybatis.modelParser; /** * @author Chanedi */ @Slf4j public class ModelUtils {
// Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/ReflectUtils.java // public class ReflectUtils { // // public static PropertyDescriptor[] getBeanSetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanSetters(type); // } // // public static PropertyDescriptor[] getBeanGetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanGetters(type); // } // // public static Method getBeanGetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getReadMethod(); // } // // public static Method getBeanSetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getWriteMethod(); // } // // public static Field getFieldByGetter(Class<?> modelClass, String getterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(getterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // public static Field getFieldBySetter(Class<?> modelClass, String setterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(setterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/modelParser/ModelUtils.java import chanedi.model.Entity; import chanedi.util.ReflectUtils; import lombok.extern.slf4j.Slf4j; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map; package chanedi.dao.impl.mybatis.modelParser; /** * @author Chanedi */ @Slf4j public class ModelUtils {
public static Map<String, Property> getProperties(Entity entity, ColumnTarget columnTarget) {
chanedi/QuickProject
QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/modelParser/ModelUtils.java
// Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/ReflectUtils.java // public class ReflectUtils { // // public static PropertyDescriptor[] getBeanSetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanSetters(type); // } // // public static PropertyDescriptor[] getBeanGetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanGetters(type); // } // // public static Method getBeanGetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getReadMethod(); // } // // public static Method getBeanSetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getWriteMethod(); // } // // public static Field getFieldByGetter(Class<?> modelClass, String getterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(getterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // public static Field getFieldBySetter(Class<?> modelClass, String setterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(setterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // }
import chanedi.model.Entity; import chanedi.util.ReflectUtils; import lombok.extern.slf4j.Slf4j; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map;
package chanedi.dao.impl.mybatis.modelParser; /** * @author Chanedi */ @Slf4j public class ModelUtils { public static Map<String, Property> getProperties(Entity entity, ColumnTarget columnTarget) { Class<?> modelClass = entity.getClass(); Map<String, Property> properties = getProperties(modelClass, columnTarget); Map<String, Property> results = new HashMap<String, Property>(properties.size()); for (Map.Entry<String, Property> propertyEntry : properties.entrySet()) { Property property = propertyEntry.getValue(); if (columnTarget == ColumnTarget.INSERT || columnTarget == ColumnTarget.UPDATE || columnTarget == ColumnTarget.WHERE) { boolean isIgnore; try { isIgnore = property.isNullValue(entity); } catch (Exception e) { isIgnore = true; } if (isIgnore) { // 空值忽略 continue; } } results.put(propertyEntry.getKey(), property); } return results; } /** * @param columnTarget 允许为null */ public static Map<String, Property> getProperties(Class<?> modelClass, ColumnTarget columnTarget) {
// Path: QuickProject-Core/src/main/java/chanedi/model/Entity.java // @Data // public abstract class Entity implements Serializable { // // private static final long serialVersionUID = 4212679023438415647L; // // public abstract Object getId(); // // public abstract void setId(Object id); // // } // // Path: QuickProject-Util/src/main/java/chanedi/util/ReflectUtils.java // public class ReflectUtils { // // public static PropertyDescriptor[] getBeanSetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanSetters(type); // } // // public static PropertyDescriptor[] getBeanGetters(Class<?> type) { // return org.springframework.cglib.core.ReflectUtils.getBeanGetters(type); // } // // public static Method getBeanGetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getReadMethod(); // } // // public static Method getBeanSetter(Class<?> beanClass, String propertyName) throws IntrospectionException { // return new PropertyDescriptor(propertyName, beanClass).getWriteMethod(); // } // // public static Field getFieldByGetter(Class<?> modelClass, String getterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(getterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // public static Field getFieldBySetter(Class<?> modelClass, String setterName) throws NoSuchFieldException { // String propName = org.apache.commons.lang3.StringUtils.uncapitalize(setterName.substring(3)); // return modelClass.getDeclaredField(propName); // } // // } // Path: QuickProject-Core/src/main/java/chanedi/dao/impl/mybatis/modelParser/ModelUtils.java import chanedi.model.Entity; import chanedi.util.ReflectUtils; import lombok.extern.slf4j.Slf4j; import java.beans.PropertyDescriptor; import java.util.HashMap; import java.util.Map; package chanedi.dao.impl.mybatis.modelParser; /** * @author Chanedi */ @Slf4j public class ModelUtils { public static Map<String, Property> getProperties(Entity entity, ColumnTarget columnTarget) { Class<?> modelClass = entity.getClass(); Map<String, Property> properties = getProperties(modelClass, columnTarget); Map<String, Property> results = new HashMap<String, Property>(properties.size()); for (Map.Entry<String, Property> propertyEntry : properties.entrySet()) { Property property = propertyEntry.getValue(); if (columnTarget == ColumnTarget.INSERT || columnTarget == ColumnTarget.UPDATE || columnTarget == ColumnTarget.WHERE) { boolean isIgnore; try { isIgnore = property.isNullValue(entity); } catch (Exception e) { isIgnore = true; } if (isIgnore) { // 空值忽略 continue; } } results.put(propertyEntry.getKey(), property); } return results; } /** * @param columnTarget 允许为null */ public static Map<String, Property> getProperties(Class<?> modelClass, ColumnTarget columnTarget) {
PropertyDescriptor[] propDescriptors = ReflectUtils.getBeanGetters(modelClass);
hschott/ready-websocket-plugin
src/main/java/com/tsystems/readyapi/plugin/websocket/Connection.java
// Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static String bytesToHexString(byte[] buf) { // final String decimals = "0123456789ABCDEF"; // if (buf == null) // return null; // char[] r = new char[buf.length * 2]; // for (int i = 0; i < buf.length; ++i) { // r[i * 2] = decimals.charAt((buf[i] & 0xf0) >> 4); // r[i * 2 + 1] = decimals.charAt(buf[i] & 0x0f); // } // return new String(r); // } // // Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static byte[] hexStringToBytes(String str) { // if (str == null) // return null; // if (str.length() % 2 != 0) // throw new IllegalArgumentException(); // byte[] result = new byte[str.length() / 2]; // try { // for (int i = 0; i < result.length; ++i) // result[i] = (byte) Short.parseShort(str.substring(i * 2, i * 2 + 2), 16); // } catch (NumberFormatException e) { // throw new IllegalArgumentException(e); // } // return result; // }
import static com.tsystems.readyapi.plugin.websocket.Utils.bytesToHexString; import static com.tsystems.readyapi.plugin.websocket.Utils.hexStringToBytes; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Objects; import org.apache.commons.ssl.OpenSSL; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlObject; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContext; import com.eviware.soapui.support.PropertyChangeNotifier; import com.eviware.soapui.support.xml.XmlObjectConfigurationReader;
} public ConnectionParams getParams() { return new ConnectionParams(getServerUri(), getLogin(), getPassword(), getSubprotocols()); } public String getPassword() { return password; } public String getServerUri() { return originalServerUri; } public String getSubprotocols() { return subprotocols; } public boolean hasCredentials() { return login != null && !"".equals(login); } public void load(XmlObject xml) { XmlObjectConfigurationReader reader = new XmlObjectConfigurationReader(xml); name = reader.readString(NAME_SETTING_NAME, null); originalServerUri = reader.readString(SERVER_URI_SETTING_NAME, null); login = reader.readString(LOGIN_SETTING_NAME, null); password = null; String encodedPasswordString = reader.readString(ENCR_PASSWORD_SETTING_NAME, null); if (encodedPasswordString != null && encodedPasswordString.length() != 0) {
// Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static String bytesToHexString(byte[] buf) { // final String decimals = "0123456789ABCDEF"; // if (buf == null) // return null; // char[] r = new char[buf.length * 2]; // for (int i = 0; i < buf.length; ++i) { // r[i * 2] = decimals.charAt((buf[i] & 0xf0) >> 4); // r[i * 2 + 1] = decimals.charAt(buf[i] & 0x0f); // } // return new String(r); // } // // Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static byte[] hexStringToBytes(String str) { // if (str == null) // return null; // if (str.length() % 2 != 0) // throw new IllegalArgumentException(); // byte[] result = new byte[str.length() / 2]; // try { // for (int i = 0; i < result.length; ++i) // result[i] = (byte) Short.parseShort(str.substring(i * 2, i * 2 + 2), 16); // } catch (NumberFormatException e) { // throw new IllegalArgumentException(e); // } // return result; // } // Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Connection.java import static com.tsystems.readyapi.plugin.websocket.Utils.bytesToHexString; import static com.tsystems.readyapi.plugin.websocket.Utils.hexStringToBytes; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Objects; import org.apache.commons.ssl.OpenSSL; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlObject; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContext; import com.eviware.soapui.support.PropertyChangeNotifier; import com.eviware.soapui.support.xml.XmlObjectConfigurationReader; } public ConnectionParams getParams() { return new ConnectionParams(getServerUri(), getLogin(), getPassword(), getSubprotocols()); } public String getPassword() { return password; } public String getServerUri() { return originalServerUri; } public String getSubprotocols() { return subprotocols; } public boolean hasCredentials() { return login != null && !"".equals(login); } public void load(XmlObject xml) { XmlObjectConfigurationReader reader = new XmlObjectConfigurationReader(xml); name = reader.readString(NAME_SETTING_NAME, null); originalServerUri = reader.readString(SERVER_URI_SETTING_NAME, null); login = reader.readString(LOGIN_SETTING_NAME, null); password = null; String encodedPasswordString = reader.readString(ENCR_PASSWORD_SETTING_NAME, null); if (encodedPasswordString != null && encodedPasswordString.length() != 0) {
byte[] encodedPassword = hexStringToBytes(encodedPasswordString);
hschott/ready-websocket-plugin
src/main/java/com/tsystems/readyapi/plugin/websocket/Connection.java
// Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static String bytesToHexString(byte[] buf) { // final String decimals = "0123456789ABCDEF"; // if (buf == null) // return null; // char[] r = new char[buf.length * 2]; // for (int i = 0; i < buf.length; ++i) { // r[i * 2] = decimals.charAt((buf[i] & 0xf0) >> 4); // r[i * 2 + 1] = decimals.charAt(buf[i] & 0x0f); // } // return new String(r); // } // // Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static byte[] hexStringToBytes(String str) { // if (str == null) // return null; // if (str.length() % 2 != 0) // throw new IllegalArgumentException(); // byte[] result = new byte[str.length() / 2]; // try { // for (int i = 0; i < result.length; ++i) // result[i] = (byte) Short.parseShort(str.substring(i * 2, i * 2 + 2), 16); // } catch (NumberFormatException e) { // throw new IllegalArgumentException(e); // } // return result; // }
import static com.tsystems.readyapi.plugin.websocket.Utils.bytesToHexString; import static com.tsystems.readyapi.plugin.websocket.Utils.hexStringToBytes; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Objects; import org.apache.commons.ssl.OpenSSL; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlObject; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContext; import com.eviware.soapui.support.PropertyChangeNotifier; import com.eviware.soapui.support.xml.XmlObjectConfigurationReader;
try { propertyChangeSupport.removePropertyChangeListener(listener); } catch (Throwable t) { LOGGER.error(t); } } @Override public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { try { propertyChangeSupport.removePropertyChangeListener(propertyName, listener); } catch (Throwable t) { LOGGER.error(t); } } public XmlObject save() { XmlObjectBuilder builder = new XmlObjectBuilder(); builder.add(NAME_SETTING_NAME, name); builder.add(SERVER_URI_SETTING_NAME, originalServerUri); if (login != null) { builder.add(LOGIN_SETTING_NAME, login); if (password != null && password.length() != 0) { byte[] encodedPassword = null; try { encodedPassword = OpenSSL.encrypt(ENCRYPTION_METHOD, PASSWORD_FOR_ENCODING.toCharArray(), password.getBytes()); } catch (IOException | GeneralSecurityException e) { LOGGER.error(e); }
// Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static String bytesToHexString(byte[] buf) { // final String decimals = "0123456789ABCDEF"; // if (buf == null) // return null; // char[] r = new char[buf.length * 2]; // for (int i = 0; i < buf.length; ++i) { // r[i * 2] = decimals.charAt((buf[i] & 0xf0) >> 4); // r[i * 2 + 1] = decimals.charAt(buf[i] & 0x0f); // } // return new String(r); // } // // Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static byte[] hexStringToBytes(String str) { // if (str == null) // return null; // if (str.length() % 2 != 0) // throw new IllegalArgumentException(); // byte[] result = new byte[str.length() / 2]; // try { // for (int i = 0; i < result.length; ++i) // result[i] = (byte) Short.parseShort(str.substring(i * 2, i * 2 + 2), 16); // } catch (NumberFormatException e) { // throw new IllegalArgumentException(e); // } // return result; // } // Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Connection.java import static com.tsystems.readyapi.plugin.websocket.Utils.bytesToHexString; import static com.tsystems.readyapi.plugin.websocket.Utils.hexStringToBytes; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Objects; import org.apache.commons.ssl.OpenSSL; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlObject; import com.eviware.soapui.model.propertyexpansion.PropertyExpansionContext; import com.eviware.soapui.support.PropertyChangeNotifier; import com.eviware.soapui.support.xml.XmlObjectConfigurationReader; try { propertyChangeSupport.removePropertyChangeListener(listener); } catch (Throwable t) { LOGGER.error(t); } } @Override public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { try { propertyChangeSupport.removePropertyChangeListener(propertyName, listener); } catch (Throwable t) { LOGGER.error(t); } } public XmlObject save() { XmlObjectBuilder builder = new XmlObjectBuilder(); builder.add(NAME_SETTING_NAME, name); builder.add(SERVER_URI_SETTING_NAME, originalServerUri); if (login != null) { builder.add(LOGIN_SETTING_NAME, login); if (password != null && password.length() != 0) { byte[] encodedPassword = null; try { encodedPassword = OpenSSL.encrypt(ENCRYPTION_METHOD, PASSWORD_FOR_ENCODING.toCharArray(), password.getBytes()); } catch (IOException | GeneralSecurityException e) { LOGGER.error(e); }
builder.add(ENCR_PASSWORD_SETTING_NAME, bytesToHexString(encodedPassword));
hschott/ready-websocket-plugin
src/main/java/com/tsystems/readyapi/plugin/websocket/ReceiveTestStep.java
// Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static String bytesToHexString(byte[] buf) { // final String decimals = "0123456789ABCDEF"; // if (buf == null) // return null; // char[] r = new char[buf.length * 2]; // for (int i = 0; i < buf.length; ++i) { // r[i * 2] = decimals.charAt((buf[i] & 0xf0) >> 4); // r[i * 2 + 1] = decimals.charAt(buf[i] & 0x0f); // } // return new String(r); // }
import static com.tsystems.readyapi.plugin.websocket.Utils.bytesToHexString; import java.beans.PropertyChangeEvent; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import javax.swing.ImageIcon; import javax.swing.SwingUtilities; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import com.eviware.soapui.SoapUI; import com.eviware.soapui.config.TestAssertionConfig; import com.eviware.soapui.config.TestStepConfig; import com.eviware.soapui.impl.wsdl.WsdlSubmitContext; import com.eviware.soapui.impl.wsdl.support.AbstractNonHttpMessageExchange; import com.eviware.soapui.impl.wsdl.support.IconAnimator; import com.eviware.soapui.impl.wsdl.support.assertions.AssertableConfig; import com.eviware.soapui.impl.wsdl.support.assertions.AssertionsSupport; import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase; import com.eviware.soapui.impl.wsdl.teststeps.WsdlMessageAssertion; import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestStepResult; import com.eviware.soapui.impl.wsdl.teststeps.assertions.TestAssertionRegistry; import com.eviware.soapui.model.iface.Interface; import com.eviware.soapui.model.iface.Response; import com.eviware.soapui.model.iface.SubmitContext; import com.eviware.soapui.model.support.DefaultTestStepProperty; import com.eviware.soapui.model.support.TestStepBeanProperty; import com.eviware.soapui.model.testsuite.Assertable; import com.eviware.soapui.model.testsuite.AssertionsListener; import com.eviware.soapui.model.testsuite.TestAssertion; import com.eviware.soapui.model.testsuite.TestCaseRunContext; import com.eviware.soapui.model.testsuite.TestCaseRunner; import com.eviware.soapui.model.testsuite.TestStep; import com.eviware.soapui.model.testsuite.TestStepResult; import com.eviware.soapui.monitor.TestMonitor; import com.eviware.soapui.plugins.auto.PluginTestStep; import com.eviware.soapui.support.StringUtils; import com.eviware.soapui.support.UISupport; import com.eviware.soapui.support.xml.XmlObjectConfigurationReader; import com.google.common.base.Charsets;
disabledStepIcon = UISupport.createImageIcon("com/tsystems/readyapi/plugin/websocket/disabled_receive_step.png"); iconAnimator = new IconAnimator<ReceiveTestStep>(this, "com/tsystems/readyapi/plugin/websocket/receive_step_base.png", "com/tsystems/readyapi/plugin/websocket/receive_step.png", 5); } @Override public TestAssertion moveAssertion(int ix, int offset) { WsdlMessageAssertion assertion = assertionsSupport.getAssertionAt(ix); try { return assertionsSupport.moveAssertion(ix, offset); } finally { assertion.release(); updateState(); } } private void onInvalidPayload(byte[] payload, WsdlTestStepResult errors) { if (payload == null || payload.length == 0) { setReceivedMessage(null); errors.addMessage(String.format( "Unable to extract a content of \"%s\" type from the message, because its payload is empty.", expectedMessageType)); return; } String text; String actualFormat = "hexadecimal digits sequence"; if (payload.length >= 3 && payload[0] == (byte) 0xef && payload[1] == (byte) 0xbb && payload[2] == (byte) 0xbf) { text = bytesToString(payload, 3, Charsets.UTF_8); if (text == null)
// Path: src/main/java/com/tsystems/readyapi/plugin/websocket/Utils.java // public static String bytesToHexString(byte[] buf) { // final String decimals = "0123456789ABCDEF"; // if (buf == null) // return null; // char[] r = new char[buf.length * 2]; // for (int i = 0; i < buf.length; ++i) { // r[i * 2] = decimals.charAt((buf[i] & 0xf0) >> 4); // r[i * 2 + 1] = decimals.charAt(buf[i] & 0x0f); // } // return new String(r); // } // Path: src/main/java/com/tsystems/readyapi/plugin/websocket/ReceiveTestStep.java import static com.tsystems.readyapi.plugin.websocket.Utils.bytesToHexString; import java.beans.PropertyChangeEvent; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import javax.swing.ImageIcon; import javax.swing.SwingUtilities; import org.apache.log4j.Logger; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import com.eviware.soapui.SoapUI; import com.eviware.soapui.config.TestAssertionConfig; import com.eviware.soapui.config.TestStepConfig; import com.eviware.soapui.impl.wsdl.WsdlSubmitContext; import com.eviware.soapui.impl.wsdl.support.AbstractNonHttpMessageExchange; import com.eviware.soapui.impl.wsdl.support.IconAnimator; import com.eviware.soapui.impl.wsdl.support.assertions.AssertableConfig; import com.eviware.soapui.impl.wsdl.support.assertions.AssertionsSupport; import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase; import com.eviware.soapui.impl.wsdl.teststeps.WsdlMessageAssertion; import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestStepResult; import com.eviware.soapui.impl.wsdl.teststeps.assertions.TestAssertionRegistry; import com.eviware.soapui.model.iface.Interface; import com.eviware.soapui.model.iface.Response; import com.eviware.soapui.model.iface.SubmitContext; import com.eviware.soapui.model.support.DefaultTestStepProperty; import com.eviware.soapui.model.support.TestStepBeanProperty; import com.eviware.soapui.model.testsuite.Assertable; import com.eviware.soapui.model.testsuite.AssertionsListener; import com.eviware.soapui.model.testsuite.TestAssertion; import com.eviware.soapui.model.testsuite.TestCaseRunContext; import com.eviware.soapui.model.testsuite.TestCaseRunner; import com.eviware.soapui.model.testsuite.TestStep; import com.eviware.soapui.model.testsuite.TestStepResult; import com.eviware.soapui.monitor.TestMonitor; import com.eviware.soapui.plugins.auto.PluginTestStep; import com.eviware.soapui.support.StringUtils; import com.eviware.soapui.support.UISupport; import com.eviware.soapui.support.xml.XmlObjectConfigurationReader; import com.google.common.base.Charsets; disabledStepIcon = UISupport.createImageIcon("com/tsystems/readyapi/plugin/websocket/disabled_receive_step.png"); iconAnimator = new IconAnimator<ReceiveTestStep>(this, "com/tsystems/readyapi/plugin/websocket/receive_step_base.png", "com/tsystems/readyapi/plugin/websocket/receive_step.png", 5); } @Override public TestAssertion moveAssertion(int ix, int offset) { WsdlMessageAssertion assertion = assertionsSupport.getAssertionAt(ix); try { return assertionsSupport.moveAssertion(ix, offset); } finally { assertion.release(); updateState(); } } private void onInvalidPayload(byte[] payload, WsdlTestStepResult errors) { if (payload == null || payload.length == 0) { setReceivedMessage(null); errors.addMessage(String.format( "Unable to extract a content of \"%s\" type from the message, because its payload is empty.", expectedMessageType)); return; } String text; String actualFormat = "hexadecimal digits sequence"; if (payload.length >= 3 && payload[0] == (byte) 0xef && payload[1] == (byte) 0xbb && payload[2] == (byte) 0xbf) { text = bytesToString(payload, 3, Charsets.UTF_8); if (text == null)
text = bytesToHexString(payload);
apache/commons-csv
src/test/java/org/apache/commons/csv/LexerTest.java
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // }
import static org.apache.commons.csv.Constants.BACKSPACE; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.FF; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; import static org.apache.commons.csv.Token.Type.COMMENT; import static org.apache.commons.csv.Token.Type.EOF; import static org.apache.commons.csv.Token.Type.EORECORD; import static org.apache.commons.csv.Token.Type.TOKEN; import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.matches; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.StringReader; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; /** * */ public class LexerTest { private CSVFormat formatWithEscaping; @SuppressWarnings("resource") private Lexer createLexer(final String input, final CSVFormat format) { return new Lexer(format, new ExtendedBufferedReader(new StringReader(input))); } @BeforeEach public void setUp() { formatWithEscaping = CSVFormat.DEFAULT.withEscape('\\'); } // simple token with escaping enabled @Test public void testBackslashWithEscaping() throws IOException { /* * file: a,\,,b \,, */ final String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; final CSVFormat format = formatWithEscaping.withIgnoreEmptyLines(false); assertTrue(format.isEscapeCharacterSet()); try (final Lexer parser = createLexer(code, format)) {
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // } // Path: src/test/java/org/apache/commons/csv/LexerTest.java import static org.apache.commons.csv.Constants.BACKSPACE; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.FF; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; import static org.apache.commons.csv.Token.Type.COMMENT; import static org.apache.commons.csv.Token.Type.EOF; import static org.apache.commons.csv.Token.Type.EORECORD; import static org.apache.commons.csv.Token.Type.TOKEN; import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.matches; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.StringReader; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; /** * */ public class LexerTest { private CSVFormat formatWithEscaping; @SuppressWarnings("resource") private Lexer createLexer(final String input, final CSVFormat format) { return new Lexer(format, new ExtendedBufferedReader(new StringReader(input))); } @BeforeEach public void setUp() { formatWithEscaping = CSVFormat.DEFAULT.withEscape('\\'); } // simple token with escaping enabled @Test public void testBackslashWithEscaping() throws IOException { /* * file: a,\,,b \,, */ final String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; final CSVFormat format = formatWithEscaping.withIgnoreEmptyLines(false); assertTrue(format.isEscapeCharacterSet()); try (final Lexer parser = createLexer(code, format)) {
assertThat(parser.nextToken(new Token()), matches(TOKEN, "a"));
apache/commons-csv
src/test/java/org/apache/commons/csv/LexerTest.java
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // }
import static org.apache.commons.csv.Constants.BACKSPACE; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.FF; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; import static org.apache.commons.csv.Token.Type.COMMENT; import static org.apache.commons.csv.Token.Type.EOF; import static org.apache.commons.csv.Token.Type.EORECORD; import static org.apache.commons.csv.Token.Type.TOKEN; import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.matches; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.StringReader; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test;
assertThat(parser.nextToken(new Token()), matches(EORECORD, "d\r")); assertThat(parser.nextToken(new Token()), matches(EOF, "e")); } } // simple token with escaping not enabled @Test public void testBackslashWithoutEscaping() throws IOException { /* * file: a,\,,b \,, */ final String code = "a,\\,,b\\\n\\,,"; final CSVFormat format = CSVFormat.DEFAULT; assertFalse(format.isEscapeCharacterSet()); try (final Lexer parser = createLexer(code, format)) { assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); // an unquoted single backslash is not an escape char assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); // an unquoted single backslash is not an escape char assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } } @Test public void testBackspace() throws Exception { try (final Lexer lexer = createLexer("character" + BACKSPACE + "NotEscaped", formatWithEscaping)) {
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // } // Path: src/test/java/org/apache/commons/csv/LexerTest.java import static org.apache.commons.csv.Constants.BACKSPACE; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.FF; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; import static org.apache.commons.csv.Token.Type.COMMENT; import static org.apache.commons.csv.Token.Type.EOF; import static org.apache.commons.csv.Token.Type.EORECORD; import static org.apache.commons.csv.Token.Type.TOKEN; import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.matches; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.StringReader; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; assertThat(parser.nextToken(new Token()), matches(EORECORD, "d\r")); assertThat(parser.nextToken(new Token()), matches(EOF, "e")); } } // simple token with escaping not enabled @Test public void testBackslashWithoutEscaping() throws IOException { /* * file: a,\,,b \,, */ final String code = "a,\\,,b\\\n\\,,"; final CSVFormat format = CSVFormat.DEFAULT; assertFalse(format.isEscapeCharacterSet()); try (final Lexer parser = createLexer(code, format)) { assertThat(parser.nextToken(new Token()), matches(TOKEN, "a")); // an unquoted single backslash is not an escape char assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EORECORD, "b\\")); // an unquoted single backslash is not an escape char assertThat(parser.nextToken(new Token()), matches(TOKEN, "\\")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(EOF, "")); } } @Test public void testBackspace() throws Exception { try (final Lexer lexer = createLexer("character" + BACKSPACE + "NotEscaped", formatWithEscaping)) {
assertThat(lexer.nextToken(new Token()), hasContent("character" + BACKSPACE + "NotEscaped"));
apache/commons-csv
src/test/java/org/apache/commons/csv/CSVFormatTest.java
// Path: src/main/java/org/apache/commons/csv/CSVFormat.java // public static final CSVFormat RFC4180 = DEFAULT.builder().setIgnoreEmptyLines(false).build();
import static org.apache.commons.csv.CSVFormat.RFC4180; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.CRLF; import static org.apache.commons.csv.Constants.LF; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Objects; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test;
@SuppressWarnings("deprecation") @Test public void testEscapeSameAsCommentStartThrowsExceptionForWrapperType_Deprecated() { // Cannot assume that callers won't use different Character objects assertThrows( IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withEscape(Character.valueOf('!')).withCommentMarker(Character.valueOf('!'))); } @Test public void testFormat() { final CSVFormat format = CSVFormat.DEFAULT; assertEquals("", format.format()); assertEquals("a,b,c", format.format("a", "b", "c")); assertEquals("\"x,y\",z", format.format("x,y", "z")); } @Test //I assume this to be a defect. public void testFormatThrowsNullPointerException() { final CSVFormat csvFormat = CSVFormat.MYSQL; final NullPointerException e = assertThrows(NullPointerException.class, () -> csvFormat.format((Object[]) null)); assertEquals(Objects.class.getName(), e.getStackTrace()[0].getClassName()); } @Test public void testFormatToString() {
// Path: src/main/java/org/apache/commons/csv/CSVFormat.java // public static final CSVFormat RFC4180 = DEFAULT.builder().setIgnoreEmptyLines(false).build(); // Path: src/test/java/org/apache/commons/csv/CSVFormatTest.java import static org.apache.commons.csv.CSVFormat.RFC4180; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.CRLF; import static org.apache.commons.csv.Constants.LF; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.io.StringReader; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Objects; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") @Test public void testEscapeSameAsCommentStartThrowsExceptionForWrapperType_Deprecated() { // Cannot assume that callers won't use different Character objects assertThrows( IllegalArgumentException.class, () -> CSVFormat.DEFAULT.withEscape(Character.valueOf('!')).withCommentMarker(Character.valueOf('!'))); } @Test public void testFormat() { final CSVFormat format = CSVFormat.DEFAULT; assertEquals("", format.format()); assertEquals("a,b,c", format.format("a", "b", "c")); assertEquals("\"x,y\",z", format.format("x,y", "z")); } @Test //I assume this to be a defect. public void testFormatThrowsNullPointerException() { final CSVFormat csvFormat = CSVFormat.MYSQL; final NullPointerException e = assertThrows(NullPointerException.class, () -> csvFormat.format((Object[]) null)); assertEquals(Objects.class.getName(), e.getStackTrace()[0].getClassName()); } @Test public void testFormatToString() {
final CSVFormat format = CSVFormat.RFC4180.withEscape('?').withDelimiter(',')
apache/commons-csv
src/test/java/org/apache/commons/csv/TokenMatchersTest.java
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasType(final Token.Type expectedType) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has type "); // description.appendValue(expectedType); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token type is "); // mismatchDescription.appendValue(item.type); // return item.type == expectedType; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> isReady() { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token is ready "); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token is not ready "); // return item.isReady; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // }
import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.hasType; import static org.apache.commons.csv.TokenMatchers.isReady; import static org.apache.commons.csv.TokenMatchers.matches; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; public class TokenMatchersTest { private Token token; @BeforeEach public void setUp() { token = new Token(); token.type = Token.Type.TOKEN;
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasType(final Token.Type expectedType) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has type "); // description.appendValue(expectedType); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token type is "); // mismatchDescription.appendValue(item.type); // return item.type == expectedType; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> isReady() { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token is ready "); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token is not ready "); // return item.isReady; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // } // Path: src/test/java/org/apache/commons/csv/TokenMatchersTest.java import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.hasType; import static org.apache.commons.csv.TokenMatchers.isReady; import static org.apache.commons.csv.TokenMatchers.matches; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; public class TokenMatchersTest { private Token token; @BeforeEach public void setUp() { token = new Token(); token.type = Token.Type.TOKEN;
token.isReady = true;
apache/commons-csv
src/test/java/org/apache/commons/csv/TokenMatchersTest.java
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasType(final Token.Type expectedType) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has type "); // description.appendValue(expectedType); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token type is "); // mismatchDescription.appendValue(item.type); // return item.type == expectedType; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> isReady() { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token is ready "); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token is not ready "); // return item.isReady; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // }
import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.hasType; import static org.apache.commons.csv.TokenMatchers.isReady; import static org.apache.commons.csv.TokenMatchers.matches; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; public class TokenMatchersTest { private Token token; @BeforeEach public void setUp() { token = new Token(); token.type = Token.Type.TOKEN; token.isReady = true; token.content.append("content"); } @Test public void testHasContent() {
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasType(final Token.Type expectedType) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has type "); // description.appendValue(expectedType); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token type is "); // mismatchDescription.appendValue(item.type); // return item.type == expectedType; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> isReady() { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token is ready "); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token is not ready "); // return item.isReady; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // } // Path: src/test/java/org/apache/commons/csv/TokenMatchersTest.java import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.hasType; import static org.apache.commons.csv.TokenMatchers.isReady; import static org.apache.commons.csv.TokenMatchers.matches; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; public class TokenMatchersTest { private Token token; @BeforeEach public void setUp() { token = new Token(); token.type = Token.Type.TOKEN; token.isReady = true; token.content.append("content"); } @Test public void testHasContent() {
assertFalse(hasContent("This is not the token's content").matches(token));
apache/commons-csv
src/test/java/org/apache/commons/csv/TokenMatchersTest.java
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasType(final Token.Type expectedType) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has type "); // description.appendValue(expectedType); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token type is "); // mismatchDescription.appendValue(item.type); // return item.type == expectedType; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> isReady() { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token is ready "); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token is not ready "); // return item.isReady; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // }
import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.hasType; import static org.apache.commons.csv.TokenMatchers.isReady; import static org.apache.commons.csv.TokenMatchers.matches; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; public class TokenMatchersTest { private Token token; @BeforeEach public void setUp() { token = new Token(); token.type = Token.Type.TOKEN; token.isReady = true; token.content.append("content"); } @Test public void testHasContent() {
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasType(final Token.Type expectedType) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has type "); // description.appendValue(expectedType); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token type is "); // mismatchDescription.appendValue(item.type); // return item.type == expectedType; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> isReady() { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token is ready "); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token is not ready "); // return item.isReady; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // } // Path: src/test/java/org/apache/commons/csv/TokenMatchersTest.java import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.hasType; import static org.apache.commons.csv.TokenMatchers.isReady; import static org.apache.commons.csv.TokenMatchers.matches; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; public class TokenMatchersTest { private Token token; @BeforeEach public void setUp() { token = new Token(); token.type = Token.Type.TOKEN; token.isReady = true; token.content.append("content"); } @Test public void testHasContent() {
assertFalse(hasContent("This is not the token's content").matches(token));
apache/commons-csv
src/test/java/org/apache/commons/csv/TokenMatchersTest.java
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasType(final Token.Type expectedType) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has type "); // description.appendValue(expectedType); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token type is "); // mismatchDescription.appendValue(item.type); // return item.type == expectedType; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> isReady() { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token is ready "); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token is not ready "); // return item.isReady; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // }
import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.hasType; import static org.apache.commons.csv.TokenMatchers.isReady; import static org.apache.commons.csv.TokenMatchers.matches; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; public class TokenMatchersTest { private Token token; @BeforeEach public void setUp() { token = new Token(); token.type = Token.Type.TOKEN; token.isReady = true; token.content.append("content"); } @Test public void testHasContent() { assertFalse(hasContent("This is not the token's content").matches(token)); assertTrue(hasContent("content").matches(token)); } @Test public void testHasType() {
// Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasContent(final String expectedContent) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has content "); // description.appendValue(expectedContent); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token content is "); // mismatchDescription.appendValue(item.content.toString()); // return expectedContent.equals(item.content.toString()); // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> hasType(final Token.Type expectedType) { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token has type "); // description.appendValue(expectedType); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token type is "); // mismatchDescription.appendValue(item.type); // return item.type == expectedType; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> isReady() { // return new TypeSafeDiagnosingMatcher<Token>() { // // @Override // public void describeTo(final Description description) { // description.appendText("token is ready "); // } // // @Override // protected boolean matchesSafely(final Token item, // final Description mismatchDescription) { // mismatchDescription.appendText("token is not ready "); // return item.isReady; // } // }; // } // // Path: src/test/java/org/apache/commons/csv/TokenMatchers.java // public static Matcher<Token> matches(final Token.Type expectedType, final String expectedContent) { // return allOf(hasType(expectedType), hasContent(expectedContent)); // } // Path: src/test/java/org/apache/commons/csv/TokenMatchersTest.java import static org.apache.commons.csv.TokenMatchers.hasContent; import static org.apache.commons.csv.TokenMatchers.hasType; import static org.apache.commons.csv.TokenMatchers.isReady; import static org.apache.commons.csv.TokenMatchers.matches; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.csv; public class TokenMatchersTest { private Token token; @BeforeEach public void setUp() { token = new Token(); token.type = Token.Type.TOKEN; token.isReady = true; token.content.append("content"); } @Test public void testHasContent() { assertFalse(hasContent("This is not the token's content").matches(token)); assertTrue(hasContent("content").matches(token)); } @Test public void testHasType() {
assertFalse(hasType(Token.Type.COMMENT).matches(token));
copygirl/WearableBackpacks
src/main/java/net/mcft/copy/backpacks/config/Status.java
// Path: src/main/java/net/mcft/copy/backpacks/WearableBackpacks.java // @Mod(modid = WearableBackpacks.MOD_ID, name = WearableBackpacks.MOD_NAME, // version = WearableBackpacks.VERSION, dependencies = "required-after:forge@[14.21.0.2375,)", // guiFactory = "net.mcft.copy.backpacks.client.BackpacksGuiFactory") // public class WearableBackpacks { // // public static final String MOD_ID = "wearablebackpacks"; // public static final String MOD_NAME = "Wearable Backpacks"; // public static final String VERSION = "@VERSION@"; // // @Instance // public static WearableBackpacks INSTANCE; // // @SidedProxy(serverSide = "net.mcft.copy.backpacks.ProxyCommon", // clientSide = "net.mcft.copy.backpacks.ProxyClient") // public static ProxyCommon PROXY; // // public static Logger LOG; // public static BackpacksChannel CHANNEL; // public static BackpacksConfig CONFIG; // public static BackpacksContent CONTENT; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // CHANNEL = new BackpacksChannel(); // // CONFIG = new BackpacksConfig(event.getSuggestedConfigurationFile()); // CONFIG.load(); // CONFIG.save(); // // CONTENT = new BackpacksContent(); // CONTENT.registerRecipes(); // // PROXY.preInit(); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // CONFIG.init(); // PROXY.init(); // } // // }
import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.config.GuiUtils; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.mcft.copy.backpacks.WearableBackpacks;
package net.mcft.copy.backpacks.config; /** Represent a status about a setting or its * config GUI entry: A hint, warning or error. */ public class Status { public static final Status NONE = FINE(); public static final Status EMPTY = ERROR(); public static final Status INVALID = ERROR(); public static Status OUT_OF_RANGE(Object min, Object max) { return ERROR("general", "outOfRange", min, max); } public static Status REQUIRED(Setting<?> value) { return ERROR("general", "required", value.getFullName()); } public static Status RECOMMENDED(Setting<?> value, String key) { return HINT("general", key, value.getFullName()); } public final Severity severity; private final String _translateKey; private final Object[] _translateParams; private Status(Severity severity, String translateKey, Object[] translateParams) { this.severity = severity; _translateKey = translateKey; _translateParams = translateParams; } private static Status constructStatus(Severity severity, String category, String key, Object... args)
// Path: src/main/java/net/mcft/copy/backpacks/WearableBackpacks.java // @Mod(modid = WearableBackpacks.MOD_ID, name = WearableBackpacks.MOD_NAME, // version = WearableBackpacks.VERSION, dependencies = "required-after:forge@[14.21.0.2375,)", // guiFactory = "net.mcft.copy.backpacks.client.BackpacksGuiFactory") // public class WearableBackpacks { // // public static final String MOD_ID = "wearablebackpacks"; // public static final String MOD_NAME = "Wearable Backpacks"; // public static final String VERSION = "@VERSION@"; // // @Instance // public static WearableBackpacks INSTANCE; // // @SidedProxy(serverSide = "net.mcft.copy.backpacks.ProxyCommon", // clientSide = "net.mcft.copy.backpacks.ProxyClient") // public static ProxyCommon PROXY; // // public static Logger LOG; // public static BackpacksChannel CHANNEL; // public static BackpacksConfig CONFIG; // public static BackpacksContent CONTENT; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // CHANNEL = new BackpacksChannel(); // // CONFIG = new BackpacksConfig(event.getSuggestedConfigurationFile()); // CONFIG.load(); // CONFIG.save(); // // CONTENT = new BackpacksContent(); // CONTENT.registerRecipes(); // // PROXY.preInit(); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // CONFIG.init(); // PROXY.init(); // } // // } // Path: src/main/java/net/mcft/copy/backpacks/config/Status.java import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import net.minecraft.client.resources.I18n; import net.minecraftforge.fml.client.config.GuiUtils; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.mcft.copy.backpacks.WearableBackpacks; package net.mcft.copy.backpacks.config; /** Represent a status about a setting or its * config GUI entry: A hint, warning or error. */ public class Status { public static final Status NONE = FINE(); public static final Status EMPTY = ERROR(); public static final Status INVALID = ERROR(); public static Status OUT_OF_RANGE(Object min, Object max) { return ERROR("general", "outOfRange", min, max); } public static Status REQUIRED(Setting<?> value) { return ERROR("general", "required", value.getFullName()); } public static Status RECOMMENDED(Setting<?> value, String key) { return HINT("general", key, value.getFullName()); } public final Severity severity; private final String _translateKey; private final Object[] _translateParams; private Status(Severity severity, String translateKey, Object[] translateParams) { this.severity = severity; _translateKey = translateKey; _translateParams = translateParams; } private static Status constructStatus(Severity severity, String category, String key, Object... args)
{ return new Status(severity, "config." + WearableBackpacks.MOD_ID + "." + category + ".status." + key, args); }
copygirl/WearableBackpacks
src/main/java/net/mcft/copy/backpacks/client/GuiTextureResource.java
// Path: src/main/java/net/mcft/copy/backpacks/WearableBackpacks.java // @Mod(modid = WearableBackpacks.MOD_ID, name = WearableBackpacks.MOD_NAME, // version = WearableBackpacks.VERSION, dependencies = "required-after:forge@[14.21.0.2375,)", // guiFactory = "net.mcft.copy.backpacks.client.BackpacksGuiFactory") // public class WearableBackpacks { // // public static final String MOD_ID = "wearablebackpacks"; // public static final String MOD_NAME = "Wearable Backpacks"; // public static final String VERSION = "@VERSION@"; // // @Instance // public static WearableBackpacks INSTANCE; // // @SidedProxy(serverSide = "net.mcft.copy.backpacks.ProxyCommon", // clientSide = "net.mcft.copy.backpacks.ProxyClient") // public static ProxyCommon PROXY; // // public static Logger LOG; // public static BackpacksChannel CHANNEL; // public static BackpacksConfig CONFIG; // public static BackpacksContent CONTENT; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // CHANNEL = new BackpacksChannel(); // // CONFIG = new BackpacksConfig(event.getSuggestedConfigurationFile()); // CONFIG.load(); // CONFIG.save(); // // CONTENT = new BackpacksContent(); // CONTENT.registerRecipes(); // // PROXY.preInit(); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // CONFIG.init(); // PROXY.init(); // } // // }
import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.mcft.copy.backpacks.WearableBackpacks;
package net.mcft.copy.backpacks.client; @SideOnly(Side.CLIENT) public class GuiTextureResource extends ResourceLocation { public final int defaultWidth; public final int defaultHeight; public GuiTextureResource(String location, int defaultWidth, int defaultHeight) {
// Path: src/main/java/net/mcft/copy/backpacks/WearableBackpacks.java // @Mod(modid = WearableBackpacks.MOD_ID, name = WearableBackpacks.MOD_NAME, // version = WearableBackpacks.VERSION, dependencies = "required-after:forge@[14.21.0.2375,)", // guiFactory = "net.mcft.copy.backpacks.client.BackpacksGuiFactory") // public class WearableBackpacks { // // public static final String MOD_ID = "wearablebackpacks"; // public static final String MOD_NAME = "Wearable Backpacks"; // public static final String VERSION = "@VERSION@"; // // @Instance // public static WearableBackpacks INSTANCE; // // @SidedProxy(serverSide = "net.mcft.copy.backpacks.ProxyCommon", // clientSide = "net.mcft.copy.backpacks.ProxyClient") // public static ProxyCommon PROXY; // // public static Logger LOG; // public static BackpacksChannel CHANNEL; // public static BackpacksConfig CONFIG; // public static BackpacksContent CONTENT; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // CHANNEL = new BackpacksChannel(); // // CONFIG = new BackpacksConfig(event.getSuggestedConfigurationFile()); // CONFIG.load(); // CONFIG.save(); // // CONTENT = new BackpacksContent(); // CONTENT.registerRecipes(); // // PROXY.preInit(); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // CONFIG.init(); // PROXY.init(); // } // // } // Path: src/main/java/net/mcft/copy/backpacks/client/GuiTextureResource.java import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.mcft.copy.backpacks.WearableBackpacks; package net.mcft.copy.backpacks.client; @SideOnly(Side.CLIENT) public class GuiTextureResource extends ResourceLocation { public final int defaultWidth; public final int defaultHeight; public GuiTextureResource(String location, int defaultWidth, int defaultHeight) {
super(WearableBackpacks.MOD_ID, "textures/gui/" + location + ".png");
copygirl/WearableBackpacks
src/main/java/net/mcft/copy/backpacks/client/gui/GuiImage.java
// Path: src/main/java/net/mcft/copy/backpacks/client/GuiTextureResource.java // @SideOnly(Side.CLIENT) // public class GuiTextureResource extends ResourceLocation { // // public final int defaultWidth; // public final int defaultHeight; // // public GuiTextureResource(String location, int defaultWidth, int defaultHeight) { // super(WearableBackpacks.MOD_ID, "textures/gui/" + location + ".png"); // this.defaultWidth = defaultWidth; // this.defaultHeight = defaultHeight; // } // // public void bind() { // Minecraft.getMinecraft().getTextureManager().bindTexture(this); // } // // /** Draws part of the texture to the screen. */ // public void drawQuad(int x, int y, int u, int v, int w, int h, float zLevel) { // float scaleX = 1.0F / defaultWidth; // float scaleY = 1.0F / defaultHeight; // Tessellator tess = Tessellator.getInstance(); // BufferBuilder vb = tess.getBuffer(); // vb.begin(7, DefaultVertexFormats.POSITION_TEX); // vb.pos(x + 0, y + h, zLevel).tex((u + 0) * scaleX, (v + h) * scaleY).endVertex(); // vb.pos(x + w, y + h, zLevel).tex((u + w) * scaleX, (v + h) * scaleY).endVertex(); // vb.pos(x + w, y + 0, zLevel).tex((u + w) * scaleX, (v + 0) * scaleY).endVertex(); // vb.pos(x + 0, y + 0, zLevel).tex((u + 0) * scaleX, (v + 0) * scaleY).endVertex(); // tess.draw(); // } // // /** Draws part of the texture to the screen. */ // public void drawQuad(int x, int y, int u, int v, int w, int h) { // drawQuad(x, y, u, v, w, h, 0); // } // // }
import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.mcft.copy.backpacks.client.GuiTextureResource;
package net.mcft.copy.backpacks.client.gui; @SideOnly(Side.CLIENT) public class GuiImage extends GuiElementBase {
// Path: src/main/java/net/mcft/copy/backpacks/client/GuiTextureResource.java // @SideOnly(Side.CLIENT) // public class GuiTextureResource extends ResourceLocation { // // public final int defaultWidth; // public final int defaultHeight; // // public GuiTextureResource(String location, int defaultWidth, int defaultHeight) { // super(WearableBackpacks.MOD_ID, "textures/gui/" + location + ".png"); // this.defaultWidth = defaultWidth; // this.defaultHeight = defaultHeight; // } // // public void bind() { // Minecraft.getMinecraft().getTextureManager().bindTexture(this); // } // // /** Draws part of the texture to the screen. */ // public void drawQuad(int x, int y, int u, int v, int w, int h, float zLevel) { // float scaleX = 1.0F / defaultWidth; // float scaleY = 1.0F / defaultHeight; // Tessellator tess = Tessellator.getInstance(); // BufferBuilder vb = tess.getBuffer(); // vb.begin(7, DefaultVertexFormats.POSITION_TEX); // vb.pos(x + 0, y + h, zLevel).tex((u + 0) * scaleX, (v + h) * scaleY).endVertex(); // vb.pos(x + w, y + h, zLevel).tex((u + w) * scaleX, (v + h) * scaleY).endVertex(); // vb.pos(x + w, y + 0, zLevel).tex((u + w) * scaleX, (v + 0) * scaleY).endVertex(); // vb.pos(x + 0, y + 0, zLevel).tex((u + 0) * scaleX, (v + 0) * scaleY).endVertex(); // tess.draw(); // } // // /** Draws part of the texture to the screen. */ // public void drawQuad(int x, int y, int u, int v, int w, int h) { // drawQuad(x, y, u, v, w, h, 0); // } // // } // Path: src/main/java/net/mcft/copy/backpacks/client/gui/GuiImage.java import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.mcft.copy.backpacks.client.GuiTextureResource; package net.mcft.copy.backpacks.client.gui; @SideOnly(Side.CLIENT) public class GuiImage extends GuiElementBase {
private GuiTextureResource _texture;
copygirl/WearableBackpacks
src/main/java/net/mcft/copy/backpacks/misc/util/IntermodUtils.java
// Path: src/main/java/net/mcft/copy/backpacks/WearableBackpacks.java // @Mod(modid = WearableBackpacks.MOD_ID, name = WearableBackpacks.MOD_NAME, // version = WearableBackpacks.VERSION, dependencies = "required-after:forge@[14.21.0.2375,)", // guiFactory = "net.mcft.copy.backpacks.client.BackpacksGuiFactory") // public class WearableBackpacks { // // public static final String MOD_ID = "wearablebackpacks"; // public static final String MOD_NAME = "Wearable Backpacks"; // public static final String VERSION = "@VERSION@"; // // @Instance // public static WearableBackpacks INSTANCE; // // @SidedProxy(serverSide = "net.mcft.copy.backpacks.ProxyCommon", // clientSide = "net.mcft.copy.backpacks.ProxyClient") // public static ProxyCommon PROXY; // // public static Logger LOG; // public static BackpacksChannel CHANNEL; // public static BackpacksConfig CONFIG; // public static BackpacksContent CONTENT; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // CHANNEL = new BackpacksChannel(); // // CONFIG = new BackpacksConfig(event.getSuggestedConfigurationFile()); // CONFIG.load(); // CONFIG.save(); // // CONTENT = new BackpacksContent(); // CONTENT.registerRecipes(); // // PROXY.preInit(); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // CONFIG.init(); // PROXY.init(); // } // // }
import java.lang.reflect.Method; import java.util.Arrays; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.Loader; import net.mcft.copy.backpacks.WearableBackpacks;
package net.mcft.copy.backpacks.misc.util; public final class IntermodUtils { private IntermodUtils() { } private static final int DEFAULT_ENCHANTMENT_COLOR = 0xFF8040CC; private static boolean getRuneColorCached = false; private static Method setTargetStackMethod = null; private static Method getColorMethod = null; /** Returns the Quark rune color for this item or the default enchant glint * color if Quark isn't present or the item doesn't have a custom rune color. */ public static int getRuneColor(ItemStack stack) { if (!getRuneColorCached) { if (Loader.isModLoaded("quark")) { try { Class<?> clazz = Class.forName("vazkii.quark.misc.feature.ColorRunes"); setTargetStackMethod = clazz.getMethod("setTargetStack", ItemStack.class); getColorMethod = Arrays.stream(clazz.getMethods()) .filter(m -> "getColor".equals(m.getName())) .findAny().orElse(null); } catch (ClassNotFoundException | NoSuchMethodException ex) {
// Path: src/main/java/net/mcft/copy/backpacks/WearableBackpacks.java // @Mod(modid = WearableBackpacks.MOD_ID, name = WearableBackpacks.MOD_NAME, // version = WearableBackpacks.VERSION, dependencies = "required-after:forge@[14.21.0.2375,)", // guiFactory = "net.mcft.copy.backpacks.client.BackpacksGuiFactory") // public class WearableBackpacks { // // public static final String MOD_ID = "wearablebackpacks"; // public static final String MOD_NAME = "Wearable Backpacks"; // public static final String VERSION = "@VERSION@"; // // @Instance // public static WearableBackpacks INSTANCE; // // @SidedProxy(serverSide = "net.mcft.copy.backpacks.ProxyCommon", // clientSide = "net.mcft.copy.backpacks.ProxyClient") // public static ProxyCommon PROXY; // // public static Logger LOG; // public static BackpacksChannel CHANNEL; // public static BackpacksConfig CONFIG; // public static BackpacksContent CONTENT; // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // LOG = event.getModLog(); // CHANNEL = new BackpacksChannel(); // // CONFIG = new BackpacksConfig(event.getSuggestedConfigurationFile()); // CONFIG.load(); // CONFIG.save(); // // CONTENT = new BackpacksContent(); // CONTENT.registerRecipes(); // // PROXY.preInit(); // } // // @EventHandler // public void init(FMLInitializationEvent event) { // CONFIG.init(); // PROXY.init(); // } // // } // Path: src/main/java/net/mcft/copy/backpacks/misc/util/IntermodUtils.java import java.lang.reflect.Method; import java.util.Arrays; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.Loader; import net.mcft.copy.backpacks.WearableBackpacks; package net.mcft.copy.backpacks.misc.util; public final class IntermodUtils { private IntermodUtils() { } private static final int DEFAULT_ENCHANTMENT_COLOR = 0xFF8040CC; private static boolean getRuneColorCached = false; private static Method setTargetStackMethod = null; private static Method getColorMethod = null; /** Returns the Quark rune color for this item or the default enchant glint * color if Quark isn't present or the item doesn't have a custom rune color. */ public static int getRuneColor(ItemStack stack) { if (!getRuneColorCached) { if (Loader.isModLoaded("quark")) { try { Class<?> clazz = Class.forName("vazkii.quark.misc.feature.ColorRunes"); setTargetStackMethod = clazz.getMethod("setTargetStack", ItemStack.class); getColorMethod = Arrays.stream(clazz.getMethods()) .filter(m -> "getColor".equals(m.getName())) .findAny().orElse(null); } catch (ClassNotFoundException | NoSuchMethodException ex) {
WearableBackpacks.LOG.error("Error while fetching Quark ColorRunes methods", ex);
copygirl/WearableBackpacks
src/main/java/net/mcft/copy/backpacks/client/gui/test/GuiTestScreen.java
// Path: src/main/java/net/mcft/copy/backpacks/client/GuiTextureResource.java // @SideOnly(Side.CLIENT) // public class GuiTextureResource extends ResourceLocation { // // public final int defaultWidth; // public final int defaultHeight; // // public GuiTextureResource(String location, int defaultWidth, int defaultHeight) { // super(WearableBackpacks.MOD_ID, "textures/gui/" + location + ".png"); // this.defaultWidth = defaultWidth; // this.defaultHeight = defaultHeight; // } // // public void bind() { // Minecraft.getMinecraft().getTextureManager().bindTexture(this); // } // // /** Draws part of the texture to the screen. */ // public void drawQuad(int x, int y, int u, int v, int w, int h, float zLevel) { // float scaleX = 1.0F / defaultWidth; // float scaleY = 1.0F / defaultHeight; // Tessellator tess = Tessellator.getInstance(); // BufferBuilder vb = tess.getBuffer(); // vb.begin(7, DefaultVertexFormats.POSITION_TEX); // vb.pos(x + 0, y + h, zLevel).tex((u + 0) * scaleX, (v + h) * scaleY).endVertex(); // vb.pos(x + w, y + h, zLevel).tex((u + w) * scaleX, (v + h) * scaleY).endVertex(); // vb.pos(x + w, y + 0, zLevel).tex((u + w) * scaleX, (v + 0) * scaleY).endVertex(); // vb.pos(x + 0, y + 0, zLevel).tex((u + 0) * scaleX, (v + 0) * scaleY).endVertex(); // tess.draw(); // } // // /** Draws part of the texture to the screen. */ // public void drawQuad(int x, int y, int u, int v, int w, int h) { // drawQuad(x, y, u, v, w, h, 0); // } // // } // // Path: src/main/java/net/mcft/copy/backpacks/client/gui/control/GuiButtonIcon.java // public static final class Icon { // public final GuiTextureResource texture; // public final int u, v, width, height; // // public Icon(GuiTextureResource texture, int u, int v, int width, int height) // { this.texture = texture; this.u = u; this.v = v; this.width = width; this.height = height; } // }
import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.mcft.copy.backpacks.client.GuiTextureResource; import net.mcft.copy.backpacks.client.gui.*; import net.mcft.copy.backpacks.client.gui.control.*; import net.mcft.copy.backpacks.client.gui.control.GuiButtonIcon.Icon;
setText(element.isVisible() ? "yes" : "no"); }); }}); addFixed(new GuiLabel(" Enabled: ") {{ setCenteredVertical(); }}); addWeighted(new GuiButton("yes") {{ setAction(() -> { element.setEnabled(!element.isEnabled()); setText(element.isEnabled() ? "yes" : "no"); }); }}); }}); layout.addFixed(element); } } public class ControlsScreen extends GuiContainerScreen { public ControlsScreen() { container.add(new GuiLayout(Direction.VERTICAL) {{ setCenteredHorizontal(); setFillVertical(8); addFixed(new GuiSlider(Direction.HORIZONTAL) {{ setFillHorizontal(); setRange(0, 10); setStepSize(1); }}); addFixed(new GuiField() {{ setFillHorizontal(); }}); addFixed(new GuiScrollable() {{ setFillHorizontal(); setHeight(100); setPadding(8);
// Path: src/main/java/net/mcft/copy/backpacks/client/GuiTextureResource.java // @SideOnly(Side.CLIENT) // public class GuiTextureResource extends ResourceLocation { // // public final int defaultWidth; // public final int defaultHeight; // // public GuiTextureResource(String location, int defaultWidth, int defaultHeight) { // super(WearableBackpacks.MOD_ID, "textures/gui/" + location + ".png"); // this.defaultWidth = defaultWidth; // this.defaultHeight = defaultHeight; // } // // public void bind() { // Minecraft.getMinecraft().getTextureManager().bindTexture(this); // } // // /** Draws part of the texture to the screen. */ // public void drawQuad(int x, int y, int u, int v, int w, int h, float zLevel) { // float scaleX = 1.0F / defaultWidth; // float scaleY = 1.0F / defaultHeight; // Tessellator tess = Tessellator.getInstance(); // BufferBuilder vb = tess.getBuffer(); // vb.begin(7, DefaultVertexFormats.POSITION_TEX); // vb.pos(x + 0, y + h, zLevel).tex((u + 0) * scaleX, (v + h) * scaleY).endVertex(); // vb.pos(x + w, y + h, zLevel).tex((u + w) * scaleX, (v + h) * scaleY).endVertex(); // vb.pos(x + w, y + 0, zLevel).tex((u + w) * scaleX, (v + 0) * scaleY).endVertex(); // vb.pos(x + 0, y + 0, zLevel).tex((u + 0) * scaleX, (v + 0) * scaleY).endVertex(); // tess.draw(); // } // // /** Draws part of the texture to the screen. */ // public void drawQuad(int x, int y, int u, int v, int w, int h) { // drawQuad(x, y, u, v, w, h, 0); // } // // } // // Path: src/main/java/net/mcft/copy/backpacks/client/gui/control/GuiButtonIcon.java // public static final class Icon { // public final GuiTextureResource texture; // public final int u, v, width, height; // // public Icon(GuiTextureResource texture, int u, int v, int width, int height) // { this.texture = texture; this.u = u; this.v = v; this.width = width; this.height = height; } // } // Path: src/main/java/net/mcft/copy/backpacks/client/gui/test/GuiTestScreen.java import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.mcft.copy.backpacks.client.GuiTextureResource; import net.mcft.copy.backpacks.client.gui.*; import net.mcft.copy.backpacks.client.gui.control.*; import net.mcft.copy.backpacks.client.gui.control.GuiButtonIcon.Icon; setText(element.isVisible() ? "yes" : "no"); }); }}); addFixed(new GuiLabel(" Enabled: ") {{ setCenteredVertical(); }}); addWeighted(new GuiButton("yes") {{ setAction(() -> { element.setEnabled(!element.isEnabled()); setText(element.isEnabled() ? "yes" : "no"); }); }}); }}); layout.addFixed(element); } } public class ControlsScreen extends GuiContainerScreen { public ControlsScreen() { container.add(new GuiLayout(Direction.VERTICAL) {{ setCenteredHorizontal(); setFillVertical(8); addFixed(new GuiSlider(Direction.HORIZONTAL) {{ setFillHorizontal(); setRange(0, 10); setStepSize(1); }}); addFixed(new GuiField() {{ setFillHorizontal(); }}); addFixed(new GuiScrollable() {{ setFillHorizontal(); setHeight(100); setPadding(8);
Icon icon = new Icon(new GuiTextureResource("config_icons", 64, 64), 36, 0, 8, 16);