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
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-shared/src/main/java/darwino/AppDatabaseDef.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/bean/UserInfoBean.java // @RequestScoped // @Named("userInfo") // public class UserInfoBean { // public static final String ROLE_ADMIN = "admin"; //$NON-NLS-1$ // // @Inject @Named("darwinoContext") // DarwinoContext context; // // @SneakyThrows // public String getImageUrl(final String userName) { // String md5 = StringUtil.md5Hex(StringUtil.toString(userName).toLowerCase()); // return StringUtil.format(DarwinoHttpConstants.SOCIAL_USERS_PATH + "/users/{0}/content/photo", URLEncoder.encode(md5, "UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ // } // // public boolean isAdmin() { // return context.getUser().hasRole(ROLE_ADMIN); // } // // public boolean isAnonymous() { // return context.getUser().isAnonymous(); // } // // public String getCn() { // return context.getUser().getCn(); // } // // public String getDn() { // return context.getUser().getDn(); // } // // public String getEmailAddress() throws UserException { // Object mail = context.getUser().getAttribute(User.ATTR_EMAIL); // return StringUtil.toString(mail); // } // }
import com.darwino.commons.Platform; import com.darwino.commons.json.JsonException; import com.darwino.commons.util.StringUtil; import com.darwino.jsonstore.Base; import com.darwino.jsonstore.impl.DatabaseFactoryImpl; import com.darwino.jsonstore.meta._Database; import com.darwino.jsonstore.meta._DatabaseACL; import com.darwino.jsonstore.meta._FtSearch; import com.darwino.jsonstore.meta._Store; import bean.UserInfoBean;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 darwino; public class AppDatabaseDef extends DatabaseFactoryImpl { public static final int DATABASE_VERSION = 17; public static final String DATABASE_NAME = "frostillicus_blog"; //$NON-NLS-1$ public static final String STORE_POSTS = "posts"; //$NON-NLS-1$ public static final String STORE_COMMENTS = "comments"; //$NON-NLS-1$ public static final String STORE_CONFIG = "config"; //$NON-NLS-1$ public static final String STORE_MEDIA = "media"; //$NON-NLS-1$ /** @since 2.3.0 */ public static final String STORE_MICROPOSTS = "microposts"; //$NON-NLS-1$ /** @since 2.3.0 */ public static final String STORE_TOKENS = "tokens"; //$NON-NLS-1$ /** @since 2.3.0 */ public static final String STORE_WEBMENTIONS = "webmentions"; //$NON-NLS-1$ // The list of instances is defined through a property for the DB public static String[] getInstances() { String inst = Platform.getProperty("frostillicus_blog.instances"); //$NON-NLS-1$ if(StringUtil.isNotEmpty(inst)) { return StringUtil.splitString(inst, ',', true); } return null; } @Override public int getDatabaseVersion(final String databaseName) throws JsonException { if(!StringUtil.equalsIgnoreCase(databaseName, DATABASE_NAME)) { return -1; } return DATABASE_VERSION; } @Override public _Database loadDatabase(final String databaseName) throws JsonException { if(!StringUtil.equalsIgnoreCase(databaseName, DATABASE_NAME)) { return null; } _Database db = new _Database(DATABASE_NAME, "frostillic.us Blog", DATABASE_VERSION); //$NON-NLS-1$ db.setDocumentSecurity(Base.DOCSEC_NOTESLIKE | Base.DOCSEC_INCLUDE | Base.DOCSEC_DYNAMIC); _DatabaseACL acl = new _DatabaseACL();
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/bean/UserInfoBean.java // @RequestScoped // @Named("userInfo") // public class UserInfoBean { // public static final String ROLE_ADMIN = "admin"; //$NON-NLS-1$ // // @Inject @Named("darwinoContext") // DarwinoContext context; // // @SneakyThrows // public String getImageUrl(final String userName) { // String md5 = StringUtil.md5Hex(StringUtil.toString(userName).toLowerCase()); // return StringUtil.format(DarwinoHttpConstants.SOCIAL_USERS_PATH + "/users/{0}/content/photo", URLEncoder.encode(md5, "UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ // } // // public boolean isAdmin() { // return context.getUser().hasRole(ROLE_ADMIN); // } // // public boolean isAnonymous() { // return context.getUser().isAnonymous(); // } // // public String getCn() { // return context.getUser().getCn(); // } // // public String getDn() { // return context.getUser().getDn(); // } // // public String getEmailAddress() throws UserException { // Object mail = context.getUser().getAttribute(User.ATTR_EMAIL); // return StringUtil.toString(mail); // } // } // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/darwino/AppDatabaseDef.java import com.darwino.commons.Platform; import com.darwino.commons.json.JsonException; import com.darwino.commons.util.StringUtil; import com.darwino.jsonstore.Base; import com.darwino.jsonstore.impl.DatabaseFactoryImpl; import com.darwino.jsonstore.meta._Database; import com.darwino.jsonstore.meta._DatabaseACL; import com.darwino.jsonstore.meta._FtSearch; import com.darwino.jsonstore.meta._Store; import bean.UserInfoBean; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 darwino; public class AppDatabaseDef extends DatabaseFactoryImpl { public static final int DATABASE_VERSION = 17; public static final String DATABASE_NAME = "frostillicus_blog"; //$NON-NLS-1$ public static final String STORE_POSTS = "posts"; //$NON-NLS-1$ public static final String STORE_COMMENTS = "comments"; //$NON-NLS-1$ public static final String STORE_CONFIG = "config"; //$NON-NLS-1$ public static final String STORE_MEDIA = "media"; //$NON-NLS-1$ /** @since 2.3.0 */ public static final String STORE_MICROPOSTS = "microposts"; //$NON-NLS-1$ /** @since 2.3.0 */ public static final String STORE_TOKENS = "tokens"; //$NON-NLS-1$ /** @since 2.3.0 */ public static final String STORE_WEBMENTIONS = "webmentions"; //$NON-NLS-1$ // The list of instances is defined through a property for the DB public static String[] getInstances() { String inst = Platform.getProperty("frostillicus_blog.instances"); //$NON-NLS-1$ if(StringUtil.isNotEmpty(inst)) { return StringUtil.splitString(inst, ',', true); } return null; } @Override public int getDatabaseVersion(final String databaseName) throws JsonException { if(!StringUtil.equalsIgnoreCase(databaseName, DATABASE_NAME)) { return -1; } return DATABASE_VERSION; } @Override public _Database loadDatabase(final String databaseName) throws JsonException { if(!StringUtil.equalsIgnoreCase(databaseName, DATABASE_NAME)) { return null; } _Database db = new _Database(DATABASE_NAME, "frostillic.us Blog", DATABASE_VERSION); //$NON-NLS-1$ db.setDocumentSecurity(Base.DOCSEC_NOTESLIKE | Base.DOCSEC_INCLUDE | Base.DOCSEC_DYNAMIC); _DatabaseACL acl = new _DatabaseACL();
acl.addRole(UserInfoBean.ROLE_ADMIN, _DatabaseACL.ROLE_MANAGE);
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/AbstractPostListController.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/PostRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_POSTS) // public interface PostRepository extends DarwinoRepository<Post, String> { // @StoredCursor("FindPost") // Optional<Post> findPost(@Param("key") String key); // // @JSQL("select unid from posts where $.postIdInt::int=:postIdInt") // Optional<Post> findByPostIdInt(@Param("postIdInt") int postIdInt); // // @StoredCursor("PostsByTag") // List<Post> findByTag(@Param("tag") String tag); // // @StoredCursor("PostsByMonth") // List<Post> findByMonth(@Param("monthQuery") String monthQuery); // // @Search(orderBy="posted desc") // List<Post> search(String query); // // @JSQL("select unid from posts where $.form='Post' order by $.posted desc limit 10") // List<Post> homeList(); // // @JSQL("select unid from posts where $.form='Post' order by $.posted desc") // List<Post> homeList(@Param("skip") int skip, @Param("limit") int limit); // // @JSQL("select unid from posts where $.form='Post' and $.thread=:thread order by $.posted") // List<Post> findByThread(@Param("thread") String thread); // // Optional<Post> findByName(String name); // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/util/PostUtil.java // public enum PostUtil { // ; // public static final int PAGE_LENGTH = 10; // // public static int getPostCount() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // return store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .count(); // } // // public static Collection<String> getPostMonths() throws JsonException { // Collection<String> months = new TreeSet<>(); // // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .extract(JsonObject.of("posted", "posted")) //$NON-NLS-1$ //$NON-NLS-2$ // .find(entry -> { // String posted = entry.getString("posted"); //$NON-NLS-1$ // if(posted != null && posted.length() >= 7) { // months.add(posted.substring(0, 7)); // } // return true; // }); // // return months; // } // // public static Post createPost() { // Post post = new Post(); // post.setPosted(OffsetDateTime.now()); // post.setPostId(UUID.randomUUID().toString()); // // // It's not pretty, but it's CLOSER to replication-safe // Random random = new Random(); // PostRepository posts = CDI.current().select(PostRepository.class).get(); // int postIdInt; // do { // postIdInt = random.nextInt(); // } while(posts.findByPostIdInt(postIdInt).isPresent()); // post.setPostIdInt(postIdInt); // // return post; // } // // public static Collection<String> getCategories() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // JsonArray tags = (JsonArray)database.getStore(AppDatabaseDef.STORE_POSTS).getTags(Integer.MAX_VALUE, true); // return tags.stream() // .map(JsonObject.class::cast) // .map(tag -> tag.getAsString("name")) //$NON-NLS-1$ // .map(StringUtil::toString) // .collect(Collectors.toList()); // } // // public static int parseStartParam(final String startParam) { // int start; // if(StringUtil.isNotEmpty(startParam)) { // try { // start = Integer.parseInt(startParam); // } catch(NumberFormatException e) { // start = -1; // } // } else { // start = -1; // } // return start; // } // // /** // * Extracts the common name from the provided distinguished name, or returns // * the original value if the argument is not a valid DN. // * // * @param dn the LDAP-format distinguished name // * @return the common name component // * @since 2.2.0 // */ // public static String toCn(final String dn) { // if(StringUtil.isNotEmpty(dn)) { // try { // LdapName name = new LdapName(dn); // for(int i = name.size()-1; i >= 0; i--) { // String bit = name.get(i); // if(bit.toLowerCase().startsWith("cn=")) { //$NON-NLS-1$ // return bit.substring(3); // } // } // } catch(InvalidNameException e) { // return dn; // } // } // return StringUtil.EMPTY_STRING; // } // }
import static model.util.PostUtil.PAGE_LENGTH; import javax.inject.Inject; import javax.mvc.Models; import com.darwino.commons.json.JsonException; import model.PostRepository; import model.util.PostUtil;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 controller; public abstract class AbstractPostListController { @Inject Models models; @Inject
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/PostRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_POSTS) // public interface PostRepository extends DarwinoRepository<Post, String> { // @StoredCursor("FindPost") // Optional<Post> findPost(@Param("key") String key); // // @JSQL("select unid from posts where $.postIdInt::int=:postIdInt") // Optional<Post> findByPostIdInt(@Param("postIdInt") int postIdInt); // // @StoredCursor("PostsByTag") // List<Post> findByTag(@Param("tag") String tag); // // @StoredCursor("PostsByMonth") // List<Post> findByMonth(@Param("monthQuery") String monthQuery); // // @Search(orderBy="posted desc") // List<Post> search(String query); // // @JSQL("select unid from posts where $.form='Post' order by $.posted desc limit 10") // List<Post> homeList(); // // @JSQL("select unid from posts where $.form='Post' order by $.posted desc") // List<Post> homeList(@Param("skip") int skip, @Param("limit") int limit); // // @JSQL("select unid from posts where $.form='Post' and $.thread=:thread order by $.posted") // List<Post> findByThread(@Param("thread") String thread); // // Optional<Post> findByName(String name); // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/util/PostUtil.java // public enum PostUtil { // ; // public static final int PAGE_LENGTH = 10; // // public static int getPostCount() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // return store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .count(); // } // // public static Collection<String> getPostMonths() throws JsonException { // Collection<String> months = new TreeSet<>(); // // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .extract(JsonObject.of("posted", "posted")) //$NON-NLS-1$ //$NON-NLS-2$ // .find(entry -> { // String posted = entry.getString("posted"); //$NON-NLS-1$ // if(posted != null && posted.length() >= 7) { // months.add(posted.substring(0, 7)); // } // return true; // }); // // return months; // } // // public static Post createPost() { // Post post = new Post(); // post.setPosted(OffsetDateTime.now()); // post.setPostId(UUID.randomUUID().toString()); // // // It's not pretty, but it's CLOSER to replication-safe // Random random = new Random(); // PostRepository posts = CDI.current().select(PostRepository.class).get(); // int postIdInt; // do { // postIdInt = random.nextInt(); // } while(posts.findByPostIdInt(postIdInt).isPresent()); // post.setPostIdInt(postIdInt); // // return post; // } // // public static Collection<String> getCategories() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // JsonArray tags = (JsonArray)database.getStore(AppDatabaseDef.STORE_POSTS).getTags(Integer.MAX_VALUE, true); // return tags.stream() // .map(JsonObject.class::cast) // .map(tag -> tag.getAsString("name")) //$NON-NLS-1$ // .map(StringUtil::toString) // .collect(Collectors.toList()); // } // // public static int parseStartParam(final String startParam) { // int start; // if(StringUtil.isNotEmpty(startParam)) { // try { // start = Integer.parseInt(startParam); // } catch(NumberFormatException e) { // start = -1; // } // } else { // start = -1; // } // return start; // } // // /** // * Extracts the common name from the provided distinguished name, or returns // * the original value if the argument is not a valid DN. // * // * @param dn the LDAP-format distinguished name // * @return the common name component // * @since 2.2.0 // */ // public static String toCn(final String dn) { // if(StringUtil.isNotEmpty(dn)) { // try { // LdapName name = new LdapName(dn); // for(int i = name.size()-1; i >= 0; i--) { // String bit = name.get(i); // if(bit.toLowerCase().startsWith("cn=")) { //$NON-NLS-1$ // return bit.substring(3); // } // } // } catch(InvalidNameException e) { // return dn; // } // } // return StringUtil.EMPTY_STRING; // } // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/AbstractPostListController.java import static model.util.PostUtil.PAGE_LENGTH; import javax.inject.Inject; import javax.mvc.Models; import com.darwino.commons.json.JsonException; import model.PostRepository; import model.util.PostUtil; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 controller; public abstract class AbstractPostListController { @Inject Models models; @Inject
PostRepository posts;
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/AbstractPostListController.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/PostRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_POSTS) // public interface PostRepository extends DarwinoRepository<Post, String> { // @StoredCursor("FindPost") // Optional<Post> findPost(@Param("key") String key); // // @JSQL("select unid from posts where $.postIdInt::int=:postIdInt") // Optional<Post> findByPostIdInt(@Param("postIdInt") int postIdInt); // // @StoredCursor("PostsByTag") // List<Post> findByTag(@Param("tag") String tag); // // @StoredCursor("PostsByMonth") // List<Post> findByMonth(@Param("monthQuery") String monthQuery); // // @Search(orderBy="posted desc") // List<Post> search(String query); // // @JSQL("select unid from posts where $.form='Post' order by $.posted desc limit 10") // List<Post> homeList(); // // @JSQL("select unid from posts where $.form='Post' order by $.posted desc") // List<Post> homeList(@Param("skip") int skip, @Param("limit") int limit); // // @JSQL("select unid from posts where $.form='Post' and $.thread=:thread order by $.posted") // List<Post> findByThread(@Param("thread") String thread); // // Optional<Post> findByName(String name); // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/util/PostUtil.java // public enum PostUtil { // ; // public static final int PAGE_LENGTH = 10; // // public static int getPostCount() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // return store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .count(); // } // // public static Collection<String> getPostMonths() throws JsonException { // Collection<String> months = new TreeSet<>(); // // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .extract(JsonObject.of("posted", "posted")) //$NON-NLS-1$ //$NON-NLS-2$ // .find(entry -> { // String posted = entry.getString("posted"); //$NON-NLS-1$ // if(posted != null && posted.length() >= 7) { // months.add(posted.substring(0, 7)); // } // return true; // }); // // return months; // } // // public static Post createPost() { // Post post = new Post(); // post.setPosted(OffsetDateTime.now()); // post.setPostId(UUID.randomUUID().toString()); // // // It's not pretty, but it's CLOSER to replication-safe // Random random = new Random(); // PostRepository posts = CDI.current().select(PostRepository.class).get(); // int postIdInt; // do { // postIdInt = random.nextInt(); // } while(posts.findByPostIdInt(postIdInt).isPresent()); // post.setPostIdInt(postIdInt); // // return post; // } // // public static Collection<String> getCategories() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // JsonArray tags = (JsonArray)database.getStore(AppDatabaseDef.STORE_POSTS).getTags(Integer.MAX_VALUE, true); // return tags.stream() // .map(JsonObject.class::cast) // .map(tag -> tag.getAsString("name")) //$NON-NLS-1$ // .map(StringUtil::toString) // .collect(Collectors.toList()); // } // // public static int parseStartParam(final String startParam) { // int start; // if(StringUtil.isNotEmpty(startParam)) { // try { // start = Integer.parseInt(startParam); // } catch(NumberFormatException e) { // start = -1; // } // } else { // start = -1; // } // return start; // } // // /** // * Extracts the common name from the provided distinguished name, or returns // * the original value if the argument is not a valid DN. // * // * @param dn the LDAP-format distinguished name // * @return the common name component // * @since 2.2.0 // */ // public static String toCn(final String dn) { // if(StringUtil.isNotEmpty(dn)) { // try { // LdapName name = new LdapName(dn); // for(int i = name.size()-1; i >= 0; i--) { // String bit = name.get(i); // if(bit.toLowerCase().startsWith("cn=")) { //$NON-NLS-1$ // return bit.substring(3); // } // } // } catch(InvalidNameException e) { // return dn; // } // } // return StringUtil.EMPTY_STRING; // } // }
import static model.util.PostUtil.PAGE_LENGTH; import javax.inject.Inject; import javax.mvc.Models; import com.darwino.commons.json.JsonException; import model.PostRepository; import model.util.PostUtil;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 controller; public abstract class AbstractPostListController { @Inject Models models; @Inject PostRepository posts; protected String maybeList(final String startParam) throws JsonException {
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/PostRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_POSTS) // public interface PostRepository extends DarwinoRepository<Post, String> { // @StoredCursor("FindPost") // Optional<Post> findPost(@Param("key") String key); // // @JSQL("select unid from posts where $.postIdInt::int=:postIdInt") // Optional<Post> findByPostIdInt(@Param("postIdInt") int postIdInt); // // @StoredCursor("PostsByTag") // List<Post> findByTag(@Param("tag") String tag); // // @StoredCursor("PostsByMonth") // List<Post> findByMonth(@Param("monthQuery") String monthQuery); // // @Search(orderBy="posted desc") // List<Post> search(String query); // // @JSQL("select unid from posts where $.form='Post' order by $.posted desc limit 10") // List<Post> homeList(); // // @JSQL("select unid from posts where $.form='Post' order by $.posted desc") // List<Post> homeList(@Param("skip") int skip, @Param("limit") int limit); // // @JSQL("select unid from posts where $.form='Post' and $.thread=:thread order by $.posted") // List<Post> findByThread(@Param("thread") String thread); // // Optional<Post> findByName(String name); // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/util/PostUtil.java // public enum PostUtil { // ; // public static final int PAGE_LENGTH = 10; // // public static int getPostCount() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // return store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .count(); // } // // public static Collection<String> getPostMonths() throws JsonException { // Collection<String> months = new TreeSet<>(); // // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .extract(JsonObject.of("posted", "posted")) //$NON-NLS-1$ //$NON-NLS-2$ // .find(entry -> { // String posted = entry.getString("posted"); //$NON-NLS-1$ // if(posted != null && posted.length() >= 7) { // months.add(posted.substring(0, 7)); // } // return true; // }); // // return months; // } // // public static Post createPost() { // Post post = new Post(); // post.setPosted(OffsetDateTime.now()); // post.setPostId(UUID.randomUUID().toString()); // // // It's not pretty, but it's CLOSER to replication-safe // Random random = new Random(); // PostRepository posts = CDI.current().select(PostRepository.class).get(); // int postIdInt; // do { // postIdInt = random.nextInt(); // } while(posts.findByPostIdInt(postIdInt).isPresent()); // post.setPostIdInt(postIdInt); // // return post; // } // // public static Collection<String> getCategories() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // JsonArray tags = (JsonArray)database.getStore(AppDatabaseDef.STORE_POSTS).getTags(Integer.MAX_VALUE, true); // return tags.stream() // .map(JsonObject.class::cast) // .map(tag -> tag.getAsString("name")) //$NON-NLS-1$ // .map(StringUtil::toString) // .collect(Collectors.toList()); // } // // public static int parseStartParam(final String startParam) { // int start; // if(StringUtil.isNotEmpty(startParam)) { // try { // start = Integer.parseInt(startParam); // } catch(NumberFormatException e) { // start = -1; // } // } else { // start = -1; // } // return start; // } // // /** // * Extracts the common name from the provided distinguished name, or returns // * the original value if the argument is not a valid DN. // * // * @param dn the LDAP-format distinguished name // * @return the common name component // * @since 2.2.0 // */ // public static String toCn(final String dn) { // if(StringUtil.isNotEmpty(dn)) { // try { // LdapName name = new LdapName(dn); // for(int i = name.size()-1; i >= 0; i--) { // String bit = name.get(i); // if(bit.toLowerCase().startsWith("cn=")) { //$NON-NLS-1$ // return bit.substring(3); // } // } // } catch(InvalidNameException e) { // return dn; // } // } // return StringUtil.EMPTY_STRING; // } // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/AbstractPostListController.java import static model.util.PostUtil.PAGE_LENGTH; import javax.inject.Inject; import javax.mvc.Models; import com.darwino.commons.json.JsonException; import model.PostRepository; import model.util.PostUtil; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 controller; public abstract class AbstractPostListController { @Inject Models models; @Inject PostRepository posts; protected String maybeList(final String startParam) throws JsonException {
var start = PostUtil.parseStartParam(startParam);
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MicroPost.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/event/MicroPostEvent.java // @Value // public class MicroPostEvent { // MicroPost post; // }
import java.time.OffsetDateTime; import java.util.Date; import java.util.UUID; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.inject.Inject; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.darwino.jnosql.artemis.extension.converter.ISOOffsetDateTimeConverter; import com.darwino.commons.util.StringUtil; import jakarta.nosql.mapping.Column; import jakarta.nosql.mapping.Convert; import jakarta.nosql.mapping.Entity; import jakarta.nosql.mapping.EntityPostPersit; import jakarta.nosql.mapping.EntityPrePersist; import jakarta.nosql.mapping.Id; import lombok.Data; import lombok.NoArgsConstructor; import model.event.MicroPostEvent;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 model; @Entity @Data @NoArgsConstructor public class MicroPost { @Id @Column private String id; @Column @NotEmpty private String postId; @Column private String name; @Column @NotEmpty private String content; @Column @NotNull @Convert(ISOOffsetDateTimeConverter.class) private OffsetDateTime posted; @Column private boolean isConflict; // TODO attachments @Inject
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/event/MicroPostEvent.java // @Value // public class MicroPostEvent { // MicroPost post; // } // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MicroPost.java import java.time.OffsetDateTime; import java.util.Date; import java.util.UUID; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.inject.Inject; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import org.darwino.jnosql.artemis.extension.converter.ISOOffsetDateTimeConverter; import com.darwino.commons.util.StringUtil; import jakarta.nosql.mapping.Column; import jakarta.nosql.mapping.Convert; import jakarta.nosql.mapping.Entity; import jakarta.nosql.mapping.EntityPostPersit; import jakarta.nosql.mapping.EntityPrePersist; import jakarta.nosql.mapping.Id; import lombok.Data; import lombok.NoArgsConstructor; import model.event.MicroPostEvent; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 model; @Entity @Data @NoArgsConstructor public class MicroPost { @Id @Column private String id; @Column @NotEmpty private String postId; @Column private String name; @Column @NotEmpty private String content; @Column @NotNull @Convert(ISOOffsetDateTimeConverter.class) private OffsetDateTime posted; @Column private boolean isConflict; // TODO attachments @Inject
Event<MicroPostEvent> microPostEvent;
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-shared/src/main/java/model/event/PostEvent.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Post.java // @Entity @Data @NoArgsConstructor // public class Post { // public enum Status { // Posted, Draft; // // public static Status valueFor(final String optionalName) { // for(Status status : values()) { // if(StringUtil.equalsIgnoreCase(status.name(), optionalName)) { // return status; // } // } // return Draft; // } // } // // @Id @Column private String id; // @Column private int postIdInt; // @Column private String postId; // @Column private String title; // @Column @NotNull @Convert(ISOOffsetDateTimeConverter.class) private OffsetDateTime posted; // @Column private String postedBy; // @Column private String bodyMarkdown; // @Column private String bodyHtml; // @Column("_tags") private List<String> tags; // @Column private String thread; // @Column private Status status; // @Column private String name; // @Column(Document.SYSTEM_META_MDATE) @Convert(UtilDateOffsetConverter.class) private OffsetDateTime modified; // @Column private String modifiedBy; // @Column private boolean hasGoneLive; // @Column private boolean isConflict; // @Column private String summary; // // @Inject private Event<PostEvent> postEvent; // // void querySave(@Observes final EntityPrePersist entity) { // if(!(entity.getValue() instanceof Post)) { // return; // } // Post post = (Post)entity.getValue(); // // // Auto-generate a slug if not already present // if(StringUtil.isEmpty(post.getName()) && post.getStatus() == Status.Posted) { // PostRepository posts = CDI.current().select(PostRepository.class).get(); // // String baseName = StringUtil.toString(post.getTitle()).toLowerCase() // .replaceAll("[^\\w]", "-") //$NON-NLS-1$ //$NON-NLS-2$ // .replaceAll("--+", "-"); //$NON-NLS-1$ //$NON-NLS-2$ // int dedupe = 1; // String name = baseName; // // Optional<Post> existing = posts.findByName(name); // String id = post.getId(); // while(existing.isPresent() && (StringUtil.isEmpty(id) || !StringUtil.equals(id, existing.get().getId()))) { // name = baseName + ++dedupe; // existing = posts.findByName(name); // } // // post.setName(name); // } // // // Update the calculated HTML body // MarkdownBean markdown = CDI.current().select(MarkdownBean.class).get(); // post.setBodyHtml(markdown.toHtml(StringUtil.toString(post.getBodyMarkdown()))); // // // Set the posted time if this is the first time it's posted or has gone live // if(post.posted == null || (post.status == Status.Posted && !post.hasGoneLive)) { // post.setPosted(OffsetDateTime.now()); // } // if(post.status == Status.Posted && !post.hasGoneLive) { // post.setHasGoneLive(true); // // postEvent.fire(new PostEvent(this, Type.PUBLISH)); // } else if(post.status == Status.Posted) { // postEvent.fire(new PostEvent(this, Type.UPDATE)); // } // } // // // ******************************************************************************* // // * Utility getters // // ******************************************************************************* // // public int getCommentCount() { // CommentRepository comments = CDI.current().select(CommentRepository.class).get(); // return comments.findByPostId(getPostId()).size(); // } // // public int getPostedYear() { // return posted.get(ChronoField.YEAR); // } // public int getPostedMonth() { // return posted.get(ChronoField.MONTH_OF_YEAR); // } // public int getPostedDay() { // return posted.get(ChronoField.DAY_OF_MONTH); // } // // public Date getPostedDate() { // return Date.from(posted.toInstant()); // } // // public boolean matchesPostedDate(final int year, final int month, final int day) { // return year == getPostedYear() && month == getPostedMonth() && day == getPostedDay(); // } // // public String getSlug() { // if(StringUtil.isEmpty(name)) { // return postId; // } else { // return name; // } // } // // public List<Post> getThreadInfo() { // return CDI.current().select(PostRepository.class).get().findByThread(getThread()); // } // }
import lombok.Value; import model.Post;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 model.event; @Value public class PostEvent { public enum Type { PUBLISH, UPDATE, DELETE }
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Post.java // @Entity @Data @NoArgsConstructor // public class Post { // public enum Status { // Posted, Draft; // // public static Status valueFor(final String optionalName) { // for(Status status : values()) { // if(StringUtil.equalsIgnoreCase(status.name(), optionalName)) { // return status; // } // } // return Draft; // } // } // // @Id @Column private String id; // @Column private int postIdInt; // @Column private String postId; // @Column private String title; // @Column @NotNull @Convert(ISOOffsetDateTimeConverter.class) private OffsetDateTime posted; // @Column private String postedBy; // @Column private String bodyMarkdown; // @Column private String bodyHtml; // @Column("_tags") private List<String> tags; // @Column private String thread; // @Column private Status status; // @Column private String name; // @Column(Document.SYSTEM_META_MDATE) @Convert(UtilDateOffsetConverter.class) private OffsetDateTime modified; // @Column private String modifiedBy; // @Column private boolean hasGoneLive; // @Column private boolean isConflict; // @Column private String summary; // // @Inject private Event<PostEvent> postEvent; // // void querySave(@Observes final EntityPrePersist entity) { // if(!(entity.getValue() instanceof Post)) { // return; // } // Post post = (Post)entity.getValue(); // // // Auto-generate a slug if not already present // if(StringUtil.isEmpty(post.getName()) && post.getStatus() == Status.Posted) { // PostRepository posts = CDI.current().select(PostRepository.class).get(); // // String baseName = StringUtil.toString(post.getTitle()).toLowerCase() // .replaceAll("[^\\w]", "-") //$NON-NLS-1$ //$NON-NLS-2$ // .replaceAll("--+", "-"); //$NON-NLS-1$ //$NON-NLS-2$ // int dedupe = 1; // String name = baseName; // // Optional<Post> existing = posts.findByName(name); // String id = post.getId(); // while(existing.isPresent() && (StringUtil.isEmpty(id) || !StringUtil.equals(id, existing.get().getId()))) { // name = baseName + ++dedupe; // existing = posts.findByName(name); // } // // post.setName(name); // } // // // Update the calculated HTML body // MarkdownBean markdown = CDI.current().select(MarkdownBean.class).get(); // post.setBodyHtml(markdown.toHtml(StringUtil.toString(post.getBodyMarkdown()))); // // // Set the posted time if this is the first time it's posted or has gone live // if(post.posted == null || (post.status == Status.Posted && !post.hasGoneLive)) { // post.setPosted(OffsetDateTime.now()); // } // if(post.status == Status.Posted && !post.hasGoneLive) { // post.setHasGoneLive(true); // // postEvent.fire(new PostEvent(this, Type.PUBLISH)); // } else if(post.status == Status.Posted) { // postEvent.fire(new PostEvent(this, Type.UPDATE)); // } // } // // // ******************************************************************************* // // * Utility getters // // ******************************************************************************* // // public int getCommentCount() { // CommentRepository comments = CDI.current().select(CommentRepository.class).get(); // return comments.findByPostId(getPostId()).size(); // } // // public int getPostedYear() { // return posted.get(ChronoField.YEAR); // } // public int getPostedMonth() { // return posted.get(ChronoField.MONTH_OF_YEAR); // } // public int getPostedDay() { // return posted.get(ChronoField.DAY_OF_MONTH); // } // // public Date getPostedDate() { // return Date.from(posted.toInstant()); // } // // public boolean matchesPostedDate(final int year, final int month, final int day) { // return year == getPostedYear() && month == getPostedMonth() && day == getPostedDay(); // } // // public String getSlug() { // if(StringUtil.isEmpty(name)) { // return postId; // } else { // return name; // } // } // // public List<Post> getThreadInfo() { // return CDI.current().select(PostRepository.class).get().findByThread(getThread()); // } // } // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/event/PostEvent.java import lombok.Value; import model.Post; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 model.event; @Value public class PostEvent { public enum Type { PUBLISH, UPDATE, DELETE }
Post post;
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/app/MediaResource.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MediaRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_MEDIA) // public interface MediaRepository extends DarwinoRepository<Media, String> { // Optional<Media> findByName(String name); // // Stream<Media> findAll(); // }
import java.io.IOException; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import model.MediaRepository;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 app; @Path(MediaResource.PATH) public class MediaResource { public static final String PATH = "media"; //$NON-NLS-1$ @Context Request request; @Inject
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MediaRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_MEDIA) // public interface MediaRepository extends DarwinoRepository<Media, String> { // Optional<Media> findByName(String name); // // Stream<Media> findAll(); // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/app/MediaResource.java import java.io.IOException; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import model.MediaRepository; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 app; @Path(MediaResource.PATH) public class MediaResource { public static final String PATH = "media"; //$NON-NLS-1$ @Context Request request; @Inject
MediaRepository mediaRepository;
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/model/DocumentCollectionManagerProducer.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/darwino/AppDatabaseDef.java // public class AppDatabaseDef extends DatabaseFactoryImpl { // // public static final int DATABASE_VERSION = 17; // public static final String DATABASE_NAME = "frostillicus_blog"; //$NON-NLS-1$ // public static final String STORE_POSTS = "posts"; //$NON-NLS-1$ // public static final String STORE_COMMENTS = "comments"; //$NON-NLS-1$ // public static final String STORE_CONFIG = "config"; //$NON-NLS-1$ // public static final String STORE_MEDIA = "media"; //$NON-NLS-1$ // /** @since 2.3.0 */ // public static final String STORE_MICROPOSTS = "microposts"; //$NON-NLS-1$ // /** @since 2.3.0 */ // public static final String STORE_TOKENS = "tokens"; //$NON-NLS-1$ // /** @since 2.3.0 */ // public static final String STORE_WEBMENTIONS = "webmentions"; //$NON-NLS-1$ // // // The list of instances is defined through a property for the DB // public static String[] getInstances() { // String inst = Platform.getProperty("frostillicus_blog.instances"); //$NON-NLS-1$ // if(StringUtil.isNotEmpty(inst)) { // return StringUtil.splitString(inst, ',', true); // } // return null; // } // // @Override // public int getDatabaseVersion(final String databaseName) throws JsonException { // if(!StringUtil.equalsIgnoreCase(databaseName, DATABASE_NAME)) { // return -1; // } // return DATABASE_VERSION; // } // // @Override // public _Database loadDatabase(final String databaseName) throws JsonException { // if(!StringUtil.equalsIgnoreCase(databaseName, DATABASE_NAME)) { // return null; // } // _Database db = new _Database(DATABASE_NAME, "frostillic.us Blog", DATABASE_VERSION); //$NON-NLS-1$ // db.setDocumentSecurity(Base.DOCSEC_NOTESLIKE | Base.DOCSEC_INCLUDE | Base.DOCSEC_DYNAMIC); // // _DatabaseACL acl = new _DatabaseACL(); // acl.addRole(UserInfoBean.ROLE_ADMIN, _DatabaseACL.ROLE_MANAGE); // acl.addAnonymous(_DatabaseACL.ROLE_AUTHOR); // acl.addUser("anonymous", _DatabaseACL.ROLE_READER); //$NON-NLS-1$ // db.setACL(acl); // // db.setReplicationEnabled(true); // db.setDocumentLockEnabled(false); // // db.setInstanceEnabled(false); // // { // _Store posts = db.addStore(STORE_POSTS); // posts.setFtSearchEnabled(true); // posts.setTaggingEnabled(true); // _FtSearch ft = posts.setFTSearch(new _FtSearch()); // ft.setFields("$"); //$NON-NLS-1$ // } // { // _Store comments = db.addStore(STORE_COMMENTS); // comments.setFtSearchEnabled(true); // _FtSearch ft = comments.setFTSearch(new _FtSearch()); // ft.setFields("$"); //$NON-NLS-1$ // } // db.addStore(STORE_CONFIG); // db.addStore(STORE_MEDIA); // db.addStore(STORE_MICROPOSTS); // db.addStore(STORE_TOKENS); // db.addStore(STORE_WEBMENTIONS); // // return db; // } // }
import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import org.darwino.jnosql.diana.driver.DarwinoDocumentCollectionManager; import org.darwino.jnosql.diana.driver.DarwinoDocumentConfiguration; import darwino.AppDatabaseDef; import jakarta.nosql.document.DocumentCollectionManagerFactory; import jakarta.nosql.document.DocumentConfiguration; import jakarta.nosql.mapping.Database; import jakarta.nosql.mapping.DatabaseType;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 model; @ApplicationScoped public class DocumentCollectionManagerProducer { private DocumentConfiguration configuration; private DocumentCollectionManagerFactory managerFactory; @PostConstruct public void init() { configuration = new DarwinoDocumentConfiguration(); managerFactory = configuration.get(); } @Produces public DarwinoDocumentCollectionManager getManager() { return managerFactory.get(com.darwino.jsonstore.Database.STORE_DEFAULT); } @Produces
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/darwino/AppDatabaseDef.java // public class AppDatabaseDef extends DatabaseFactoryImpl { // // public static final int DATABASE_VERSION = 17; // public static final String DATABASE_NAME = "frostillicus_blog"; //$NON-NLS-1$ // public static final String STORE_POSTS = "posts"; //$NON-NLS-1$ // public static final String STORE_COMMENTS = "comments"; //$NON-NLS-1$ // public static final String STORE_CONFIG = "config"; //$NON-NLS-1$ // public static final String STORE_MEDIA = "media"; //$NON-NLS-1$ // /** @since 2.3.0 */ // public static final String STORE_MICROPOSTS = "microposts"; //$NON-NLS-1$ // /** @since 2.3.0 */ // public static final String STORE_TOKENS = "tokens"; //$NON-NLS-1$ // /** @since 2.3.0 */ // public static final String STORE_WEBMENTIONS = "webmentions"; //$NON-NLS-1$ // // // The list of instances is defined through a property for the DB // public static String[] getInstances() { // String inst = Platform.getProperty("frostillicus_blog.instances"); //$NON-NLS-1$ // if(StringUtil.isNotEmpty(inst)) { // return StringUtil.splitString(inst, ',', true); // } // return null; // } // // @Override // public int getDatabaseVersion(final String databaseName) throws JsonException { // if(!StringUtil.equalsIgnoreCase(databaseName, DATABASE_NAME)) { // return -1; // } // return DATABASE_VERSION; // } // // @Override // public _Database loadDatabase(final String databaseName) throws JsonException { // if(!StringUtil.equalsIgnoreCase(databaseName, DATABASE_NAME)) { // return null; // } // _Database db = new _Database(DATABASE_NAME, "frostillic.us Blog", DATABASE_VERSION); //$NON-NLS-1$ // db.setDocumentSecurity(Base.DOCSEC_NOTESLIKE | Base.DOCSEC_INCLUDE | Base.DOCSEC_DYNAMIC); // // _DatabaseACL acl = new _DatabaseACL(); // acl.addRole(UserInfoBean.ROLE_ADMIN, _DatabaseACL.ROLE_MANAGE); // acl.addAnonymous(_DatabaseACL.ROLE_AUTHOR); // acl.addUser("anonymous", _DatabaseACL.ROLE_READER); //$NON-NLS-1$ // db.setACL(acl); // // db.setReplicationEnabled(true); // db.setDocumentLockEnabled(false); // // db.setInstanceEnabled(false); // // { // _Store posts = db.addStore(STORE_POSTS); // posts.setFtSearchEnabled(true); // posts.setTaggingEnabled(true); // _FtSearch ft = posts.setFTSearch(new _FtSearch()); // ft.setFields("$"); //$NON-NLS-1$ // } // { // _Store comments = db.addStore(STORE_COMMENTS); // comments.setFtSearchEnabled(true); // _FtSearch ft = comments.setFTSearch(new _FtSearch()); // ft.setFields("$"); //$NON-NLS-1$ // } // db.addStore(STORE_CONFIG); // db.addStore(STORE_MEDIA); // db.addStore(STORE_MICROPOSTS); // db.addStore(STORE_TOKENS); // db.addStore(STORE_WEBMENTIONS); // // return db; // } // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/model/DocumentCollectionManagerProducer.java import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import org.darwino.jnosql.diana.driver.DarwinoDocumentCollectionManager; import org.darwino.jnosql.diana.driver.DarwinoDocumentConfiguration; import darwino.AppDatabaseDef; import jakarta.nosql.document.DocumentCollectionManagerFactory; import jakarta.nosql.document.DocumentConfiguration; import jakarta.nosql.mapping.Database; import jakarta.nosql.mapping.DatabaseType; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 model; @ApplicationScoped public class DocumentCollectionManagerProducer { private DocumentConfiguration configuration; private DocumentCollectionManagerFactory managerFactory; @PostConstruct public void init() { configuration = new DarwinoDocumentConfiguration(); managerFactory = configuration.get(); } @Produces public DarwinoDocumentCollectionManager getManager() { return managerFactory.get(com.darwino.jsonstore.Database.STORE_DEFAULT); } @Produces
@Database(value=DatabaseType.DOCUMENT, provider=AppDatabaseDef.STORE_POSTS)
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-shared/src/main/java/model/event/MicroPostEvent.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MicroPost.java // @Entity @Data @NoArgsConstructor // public class MicroPost { // @Id @Column private String id; // @Column @NotEmpty private String postId; // @Column private String name; // @Column @NotEmpty private String content; // @Column @NotNull @Convert(ISOOffsetDateTimeConverter.class) private OffsetDateTime posted; // @Column private boolean isConflict; // // // TODO attachments // // @Inject // Event<MicroPostEvent> microPostEvent; // // void querySave(@Observes final EntityPrePersist event) { // if(!(event.getValue() instanceof MicroPost)) { // return; // } // MicroPost post = (MicroPost)event.getValue(); // // if(StringUtil.isEmpty(post.getPostId())) { // post.setPostId(UUID.randomUUID().toString()); // } // if(post.getPosted() == null) { // post.setPosted(OffsetDateTime.now()); // } // } // // void postSave(@Observes final EntityPostPersit event) { // if(!(event.getValue() instanceof MicroPost)) { // return; // } // MicroPost post = (MicroPost)event.getValue(); // microPostEvent.fire(new MicroPostEvent(post)); // } // // public Date getPostedDate() { // return Date.from(posted.toInstant()); // } // }
import lombok.Value; import model.MicroPost;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 model.event; @Value public class MicroPostEvent {
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MicroPost.java // @Entity @Data @NoArgsConstructor // public class MicroPost { // @Id @Column private String id; // @Column @NotEmpty private String postId; // @Column private String name; // @Column @NotEmpty private String content; // @Column @NotNull @Convert(ISOOffsetDateTimeConverter.class) private OffsetDateTime posted; // @Column private boolean isConflict; // // // TODO attachments // // @Inject // Event<MicroPostEvent> microPostEvent; // // void querySave(@Observes final EntityPrePersist event) { // if(!(event.getValue() instanceof MicroPost)) { // return; // } // MicroPost post = (MicroPost)event.getValue(); // // if(StringUtil.isEmpty(post.getPostId())) { // post.setPostId(UUID.randomUUID().toString()); // } // if(post.getPosted() == null) { // post.setPosted(OffsetDateTime.now()); // } // } // // void postSave(@Observes final EntityPostPersit event) { // if(!(event.getValue() instanceof MicroPost)) { // return; // } // MicroPost post = (MicroPost)event.getValue(); // microPostEvent.fire(new MicroPostEvent(post)); // } // // public Date getPostedDate() { // return Date.from(posted.toInstant()); // } // } // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/event/MicroPostEvent.java import lombok.Value; import model.MicroPost; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 model.event; @Value public class MicroPostEvent {
MicroPost post;
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/api/atompub/MediaResource.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/bean/UserInfoBean.java // @RequestScoped // @Named("userInfo") // public class UserInfoBean { // public static final String ROLE_ADMIN = "admin"; //$NON-NLS-1$ // // @Inject @Named("darwinoContext") // DarwinoContext context; // // @SneakyThrows // public String getImageUrl(final String userName) { // String md5 = StringUtil.md5Hex(StringUtil.toString(userName).toLowerCase()); // return StringUtil.format(DarwinoHttpConstants.SOCIAL_USERS_PATH + "/users/{0}/content/photo", URLEncoder.encode(md5, "UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ // } // // public boolean isAdmin() { // return context.getUser().hasRole(ROLE_ADMIN); // } // // public boolean isAnonymous() { // return context.getUser().isAnonymous(); // } // // public String getCn() { // return context.getUser().getCn(); // } // // public String getDn() { // return context.getUser().getDn(); // } // // public String getEmailAddress() throws UserException { // Object mail = context.getUser().getAttribute(User.ATTR_EMAIL); // return StringUtil.toString(mail); // } // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Media.java // @Entity @Data @NoArgsConstructor // public class Media { // @Id @Column private String id; // @Column private String name; // @Column(EntityConverter.ATTACHMENT_FIELD) private List<EntityAttachment> attachments; // @Column(Document.SYSTEM_META_MDATE) private Date lastModificationDate; // @Column(Document.SYSTEM_META_CUSER) private String creationUser; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MediaRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_MEDIA) // public interface MediaRepository extends DarwinoRepository<Media, String> { // Optional<Media> findByName(String name); // // Stream<Media> findAll(); // }
import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.ResourceBundle; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.eclipse.jnosql.diana.driver.attachment.EntityAttachment; import org.w3c.dom.Element; import com.darwino.commons.util.DateTimeISO8601; import com.darwino.commons.util.PathUtil; import com.darwino.commons.xml.DomUtil; import bean.UserInfoBean; import lombok.SneakyThrows; import model.Media; import model.MediaRepository;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 api.atompub; @Path(AtomPubResource.BASE_PATH + "/{blogId}/" + MediaResource.PATH) @RolesAllowed(UserInfoBean.ROLE_ADMIN) public class MediaResource { public static final String PATH = "media"; //$NON-NLS-1$ @Inject @Named("translation") ResourceBundle translation; @Context UriInfo uriInfo; @Context HttpServletRequest request; @Inject
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/bean/UserInfoBean.java // @RequestScoped // @Named("userInfo") // public class UserInfoBean { // public static final String ROLE_ADMIN = "admin"; //$NON-NLS-1$ // // @Inject @Named("darwinoContext") // DarwinoContext context; // // @SneakyThrows // public String getImageUrl(final String userName) { // String md5 = StringUtil.md5Hex(StringUtil.toString(userName).toLowerCase()); // return StringUtil.format(DarwinoHttpConstants.SOCIAL_USERS_PATH + "/users/{0}/content/photo", URLEncoder.encode(md5, "UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ // } // // public boolean isAdmin() { // return context.getUser().hasRole(ROLE_ADMIN); // } // // public boolean isAnonymous() { // return context.getUser().isAnonymous(); // } // // public String getCn() { // return context.getUser().getCn(); // } // // public String getDn() { // return context.getUser().getDn(); // } // // public String getEmailAddress() throws UserException { // Object mail = context.getUser().getAttribute(User.ATTR_EMAIL); // return StringUtil.toString(mail); // } // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Media.java // @Entity @Data @NoArgsConstructor // public class Media { // @Id @Column private String id; // @Column private String name; // @Column(EntityConverter.ATTACHMENT_FIELD) private List<EntityAttachment> attachments; // @Column(Document.SYSTEM_META_MDATE) private Date lastModificationDate; // @Column(Document.SYSTEM_META_CUSER) private String creationUser; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MediaRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_MEDIA) // public interface MediaRepository extends DarwinoRepository<Media, String> { // Optional<Media> findByName(String name); // // Stream<Media> findAll(); // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/api/atompub/MediaResource.java import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.ResourceBundle; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.eclipse.jnosql.diana.driver.attachment.EntityAttachment; import org.w3c.dom.Element; import com.darwino.commons.util.DateTimeISO8601; import com.darwino.commons.util.PathUtil; import com.darwino.commons.xml.DomUtil; import bean.UserInfoBean; import lombok.SneakyThrows; import model.Media; import model.MediaRepository; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 api.atompub; @Path(AtomPubResource.BASE_PATH + "/{blogId}/" + MediaResource.PATH) @RolesAllowed(UserInfoBean.ROLE_ADMIN) public class MediaResource { public static final String PATH = "media"; //$NON-NLS-1$ @Inject @Named("translation") ResourceBundle translation; @Context UriInfo uriInfo; @Context HttpServletRequest request; @Inject
MediaRepository mediaRepository;
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/api/atompub/MediaResource.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/bean/UserInfoBean.java // @RequestScoped // @Named("userInfo") // public class UserInfoBean { // public static final String ROLE_ADMIN = "admin"; //$NON-NLS-1$ // // @Inject @Named("darwinoContext") // DarwinoContext context; // // @SneakyThrows // public String getImageUrl(final String userName) { // String md5 = StringUtil.md5Hex(StringUtil.toString(userName).toLowerCase()); // return StringUtil.format(DarwinoHttpConstants.SOCIAL_USERS_PATH + "/users/{0}/content/photo", URLEncoder.encode(md5, "UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ // } // // public boolean isAdmin() { // return context.getUser().hasRole(ROLE_ADMIN); // } // // public boolean isAnonymous() { // return context.getUser().isAnonymous(); // } // // public String getCn() { // return context.getUser().getCn(); // } // // public String getDn() { // return context.getUser().getDn(); // } // // public String getEmailAddress() throws UserException { // Object mail = context.getUser().getAttribute(User.ATTR_EMAIL); // return StringUtil.toString(mail); // } // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Media.java // @Entity @Data @NoArgsConstructor // public class Media { // @Id @Column private String id; // @Column private String name; // @Column(EntityConverter.ATTACHMENT_FIELD) private List<EntityAttachment> attachments; // @Column(Document.SYSTEM_META_MDATE) private Date lastModificationDate; // @Column(Document.SYSTEM_META_CUSER) private String creationUser; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MediaRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_MEDIA) // public interface MediaRepository extends DarwinoRepository<Media, String> { // Optional<Media> findByName(String name); // // Stream<Media> findAll(); // }
import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.ResourceBundle; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.eclipse.jnosql.diana.driver.attachment.EntityAttachment; import org.w3c.dom.Element; import com.darwino.commons.util.DateTimeISO8601; import com.darwino.commons.util.PathUtil; import com.darwino.commons.xml.DomUtil; import bean.UserInfoBean; import lombok.SneakyThrows; import model.Media; import model.MediaRepository;
@Context HttpServletRequest request; @Inject MediaRepository mediaRepository; @GET @Produces("application/atom+xml") public String list() { var xml = DomUtil.createDocument(); var feed = DomUtil.createRootElement(xml, "feed"); //$NON-NLS-1$ feed.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); //$NON-NLS-1$ //$NON-NLS-2$ mediaRepository.findAll().forEach(m -> { var entry = DomUtil.createElement(feed, "entry"); //$NON-NLS-1$ entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); //$NON-NLS-1$ //$NON-NLS-2$ populateAtomXml(entry, m); }); return DomUtil.getXMLString(xml); } @POST @Produces("application/atom+xml") public Response uploadMedia(final byte[] data) throws URISyntaxException { var contentType = request.getContentType(); var name = request.getHeader("Slug"); //$NON-NLS-1$ // TODO make sure it's not already there // This could use the name as the UNID, but it's kind of nice having a "real" UNID behind the scenes
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/bean/UserInfoBean.java // @RequestScoped // @Named("userInfo") // public class UserInfoBean { // public static final String ROLE_ADMIN = "admin"; //$NON-NLS-1$ // // @Inject @Named("darwinoContext") // DarwinoContext context; // // @SneakyThrows // public String getImageUrl(final String userName) { // String md5 = StringUtil.md5Hex(StringUtil.toString(userName).toLowerCase()); // return StringUtil.format(DarwinoHttpConstants.SOCIAL_USERS_PATH + "/users/{0}/content/photo", URLEncoder.encode(md5, "UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ // } // // public boolean isAdmin() { // return context.getUser().hasRole(ROLE_ADMIN); // } // // public boolean isAnonymous() { // return context.getUser().isAnonymous(); // } // // public String getCn() { // return context.getUser().getCn(); // } // // public String getDn() { // return context.getUser().getDn(); // } // // public String getEmailAddress() throws UserException { // Object mail = context.getUser().getAttribute(User.ATTR_EMAIL); // return StringUtil.toString(mail); // } // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Media.java // @Entity @Data @NoArgsConstructor // public class Media { // @Id @Column private String id; // @Column private String name; // @Column(EntityConverter.ATTACHMENT_FIELD) private List<EntityAttachment> attachments; // @Column(Document.SYSTEM_META_MDATE) private Date lastModificationDate; // @Column(Document.SYSTEM_META_CUSER) private String creationUser; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MediaRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_MEDIA) // public interface MediaRepository extends DarwinoRepository<Media, String> { // Optional<Media> findByName(String name); // // Stream<Media> findAll(); // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/api/atompub/MediaResource.java import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.ResourceBundle; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.eclipse.jnosql.diana.driver.attachment.EntityAttachment; import org.w3c.dom.Element; import com.darwino.commons.util.DateTimeISO8601; import com.darwino.commons.util.PathUtil; import com.darwino.commons.xml.DomUtil; import bean.UserInfoBean; import lombok.SneakyThrows; import model.Media; import model.MediaRepository; @Context HttpServletRequest request; @Inject MediaRepository mediaRepository; @GET @Produces("application/atom+xml") public String list() { var xml = DomUtil.createDocument(); var feed = DomUtil.createRootElement(xml, "feed"); //$NON-NLS-1$ feed.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); //$NON-NLS-1$ //$NON-NLS-2$ mediaRepository.findAll().forEach(m -> { var entry = DomUtil.createElement(feed, "entry"); //$NON-NLS-1$ entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); //$NON-NLS-1$ //$NON-NLS-2$ populateAtomXml(entry, m); }); return DomUtil.getXMLString(xml); } @POST @Produces("application/atom+xml") public Response uploadMedia(final byte[] data) throws URISyntaxException { var contentType = request.getContentType(); var name = request.getHeader("Slug"); //$NON-NLS-1$ // TODO make sure it's not already there // This could use the name as the UNID, but it's kind of nice having a "real" UNID behind the scenes
var media = mediaRepository.findByName(name).orElseGet(Media::new);
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/LinksBean.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Link.java // @Entity @Data @NoArgsConstructor // public class Link { // @Id @Column private String id; // @Column private String category; // @Column("link_url") @NotEmpty private String url; // @Column("link_name") @NotEmpty private String name; // @Column("link_visible") @Convert(BooleanYNConverter.class) private boolean visible; // @Column private String rel; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/LinkRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_CONFIG) // public interface LinkRepository extends DarwinoRepository<Link, String> { // Stream<Link> findAll(); // // @Query("select * from Link order by category name") // List<Link> findAllByCategoryAndName(); // }
import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import model.Link; import model.LinkRepository;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 bean; @ApplicationScoped @Named("links") public class LinksBean { @Inject
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Link.java // @Entity @Data @NoArgsConstructor // public class Link { // @Id @Column private String id; // @Column private String category; // @Column("link_url") @NotEmpty private String url; // @Column("link_name") @NotEmpty private String name; // @Column("link_visible") @Convert(BooleanYNConverter.class) private boolean visible; // @Column private String rel; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/LinkRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_CONFIG) // public interface LinkRepository extends DarwinoRepository<Link, String> { // Stream<Link> findAll(); // // @Query("select * from Link order by category name") // List<Link> findAllByCategoryAndName(); // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/LinksBean.java import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import model.Link; import model.LinkRepository; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 bean; @ApplicationScoped @Named("links") public class LinksBean { @Inject
LinkRepository links;
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/LinksBean.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Link.java // @Entity @Data @NoArgsConstructor // public class Link { // @Id @Column private String id; // @Column private String category; // @Column("link_url") @NotEmpty private String url; // @Column("link_name") @NotEmpty private String name; // @Column("link_visible") @Convert(BooleanYNConverter.class) private boolean visible; // @Column private String rel; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/LinkRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_CONFIG) // public interface LinkRepository extends DarwinoRepository<Link, String> { // Stream<Link> findAll(); // // @Query("select * from Link order by category name") // List<Link> findAllByCategoryAndName(); // }
import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import model.Link; import model.LinkRepository;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 bean; @ApplicationScoped @Named("links") public class LinksBean { @Inject LinkRepository links;
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/Link.java // @Entity @Data @NoArgsConstructor // public class Link { // @Id @Column private String id; // @Column private String category; // @Column("link_url") @NotEmpty private String url; // @Column("link_name") @NotEmpty private String name; // @Column("link_visible") @Convert(BooleanYNConverter.class) private boolean visible; // @Column private String rel; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/LinkRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_CONFIG) // public interface LinkRepository extends DarwinoRepository<Link, String> { // Stream<Link> findAll(); // // @Query("select * from Link order by category name") // List<Link> findAllByCategoryAndName(); // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/LinksBean.java import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import model.Link; import model.LinkRepository; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 bean; @ApplicationScoped @Named("links") public class LinksBean { @Inject LinkRepository links;
private static Comparator<Link> linkComparator = (o1, o2) -> String.valueOf(o1.getName()).compareTo(o2.getName());
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/test/java/test/bean/TestEncoderBean.java
// Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/EncoderBean.java // @ApplicationScoped @Named("encoder") // public class EncoderBean { // // /** // * URL-encodes the provided value, using {@link URLEncoder#encode(String, String)}. // * // * @param value the value to URL-encode // * @return the URL-encoded value // */ // @SneakyThrows // public String urlEncode(final String value) { // if(StringUtil.isEmpty(value)) { // return StringUtil.EMPTY_STRING; // } else { // return URLEncoder.encode(value, StringUtil.UTF_8.name()); // } // } // }
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import bean.EncoderBean;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 test.bean; @SuppressWarnings("nls") public class TestEncoderBean { @Test public void testUrlEncode() {
// Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/EncoderBean.java // @ApplicationScoped @Named("encoder") // public class EncoderBean { // // /** // * URL-encodes the provided value, using {@link URLEncoder#encode(String, String)}. // * // * @param value the value to URL-encode // * @return the URL-encoded value // */ // @SneakyThrows // public String urlEncode(final String value) { // if(StringUtil.isEmpty(value)) { // return StringUtil.EMPTY_STRING; // } else { // return URLEncoder.encode(value, StringUtil.UTF_8.name()); // } // } // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/test/java/test/bean/TestEncoderBean.java import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import bean.EncoderBean; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 test.bean; @SuppressWarnings("nls") public class TestEncoderBean { @Test public void testUrlEncode() {
EncoderBean encoder = new EncoderBean();
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/AccessTokensBean.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/AccessToken.java // @Entity @Data @NoArgsConstructor // public class AccessToken { // @Id @Column private String id; // @Column private String userName; // @Column private String name; // @Column private String token; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/AccessTokenRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_TOKENS) // public interface AccessTokenRepository extends DarwinoRepository<AccessToken, String> { // Stream<AccessToken> findAll(); // // Optional<AccessToken> findByToken(String token); // }
import java.util.Collection; import java.util.stream.Collectors; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import model.AccessToken; import model.AccessTokenRepository;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 bean; @ApplicationScoped @Named("accessTokens") public class AccessTokensBean { @Inject
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/AccessToken.java // @Entity @Data @NoArgsConstructor // public class AccessToken { // @Id @Column private String id; // @Column private String userName; // @Column private String name; // @Column private String token; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/AccessTokenRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_TOKENS) // public interface AccessTokenRepository extends DarwinoRepository<AccessToken, String> { // Stream<AccessToken> findAll(); // // Optional<AccessToken> findByToken(String token); // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/AccessTokensBean.java import java.util.Collection; import java.util.stream.Collectors; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import model.AccessToken; import model.AccessTokenRepository; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 bean; @ApplicationScoped @Named("accessTokens") public class AccessTokensBean { @Inject
AccessTokenRepository accessTokens;
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/AccessTokensBean.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/AccessToken.java // @Entity @Data @NoArgsConstructor // public class AccessToken { // @Id @Column private String id; // @Column private String userName; // @Column private String name; // @Column private String token; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/AccessTokenRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_TOKENS) // public interface AccessTokenRepository extends DarwinoRepository<AccessToken, String> { // Stream<AccessToken> findAll(); // // Optional<AccessToken> findByToken(String token); // }
import java.util.Collection; import java.util.stream.Collectors; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import model.AccessToken; import model.AccessTokenRepository;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 bean; @ApplicationScoped @Named("accessTokens") public class AccessTokensBean { @Inject AccessTokenRepository accessTokens;
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/AccessToken.java // @Entity @Data @NoArgsConstructor // public class AccessToken { // @Id @Column private String id; // @Column private String userName; // @Column private String name; // @Column private String token; // @Column private boolean isConflict; // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/AccessTokenRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_TOKENS) // public interface AccessTokenRepository extends DarwinoRepository<AccessToken, String> { // Stream<AccessToken> findAll(); // // Optional<AccessToken> findByToken(String token); // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/bean/AccessTokensBean.java import java.util.Collection; import java.util.stream.Collectors; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import model.AccessToken; import model.AccessTokenRepository; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 bean; @ApplicationScoped @Named("accessTokens") public class AccessTokensBean { @Inject AccessTokenRepository accessTokens;
public Collection<AccessToken> getAll() {
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/MicroPostController.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/bean/UserInfoBean.java // @RequestScoped // @Named("userInfo") // public class UserInfoBean { // public static final String ROLE_ADMIN = "admin"; //$NON-NLS-1$ // // @Inject @Named("darwinoContext") // DarwinoContext context; // // @SneakyThrows // public String getImageUrl(final String userName) { // String md5 = StringUtil.md5Hex(StringUtil.toString(userName).toLowerCase()); // return StringUtil.format(DarwinoHttpConstants.SOCIAL_USERS_PATH + "/users/{0}/content/photo", URLEncoder.encode(md5, "UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ // } // // public boolean isAdmin() { // return context.getUser().hasRole(ROLE_ADMIN); // } // // public boolean isAnonymous() { // return context.getUser().isAnonymous(); // } // // public String getCn() { // return context.getUser().getCn(); // } // // public String getDn() { // return context.getUser().getDn(); // } // // public String getEmailAddress() throws UserException { // Object mail = context.getUser().getAttribute(User.ATTR_EMAIL); // return StringUtil.toString(mail); // } // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MicroPostRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_MICROPOSTS) // public interface MicroPostRepository extends DarwinoRepository<MicroPost, String> { // @JSQL("select unid from microposts where $.form='MicroPost' order by $.posted desc") // List<MicroPost> findAll(); // }
import javax.annotation.security.RolesAllowed; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.mvc.Controller; import javax.mvc.Models; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import bean.UserInfoBean; import model.MicroPostRepository;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 controller; @Path(MicroPostController.PATH) @RolesAllowed(UserInfoBean.ROLE_ADMIN) @Controller @RequestScoped public class MicroPostController { public static final String PATH = "/microposts"; //$NON-NLS-1$ @Inject Models models;
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/bean/UserInfoBean.java // @RequestScoped // @Named("userInfo") // public class UserInfoBean { // public static final String ROLE_ADMIN = "admin"; //$NON-NLS-1$ // // @Inject @Named("darwinoContext") // DarwinoContext context; // // @SneakyThrows // public String getImageUrl(final String userName) { // String md5 = StringUtil.md5Hex(StringUtil.toString(userName).toLowerCase()); // return StringUtil.format(DarwinoHttpConstants.SOCIAL_USERS_PATH + "/users/{0}/content/photo", URLEncoder.encode(md5, "UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$ // } // // public boolean isAdmin() { // return context.getUser().hasRole(ROLE_ADMIN); // } // // public boolean isAnonymous() { // return context.getUser().isAnonymous(); // } // // public String getCn() { // return context.getUser().getCn(); // } // // public String getDn() { // return context.getUser().getDn(); // } // // public String getEmailAddress() throws UserException { // Object mail = context.getUser().getAttribute(User.ATTR_EMAIL); // return StringUtil.toString(mail); // } // } // // Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/MicroPostRepository.java // @RepositoryProvider(AppDatabaseDef.STORE_MICROPOSTS) // public interface MicroPostRepository extends DarwinoRepository<MicroPost, String> { // @JSQL("select unid from microposts where $.form='MicroPost' order by $.posted desc") // List<MicroPost> findAll(); // } // Path: frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/MicroPostController.java import javax.annotation.security.RolesAllowed; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.mvc.Controller; import javax.mvc.Models; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import bean.UserInfoBean; import model.MicroPostRepository; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 controller; @Path(MicroPostController.PATH) @RolesAllowed(UserInfoBean.ROLE_ADMIN) @Controller @RequestScoped public class MicroPostController { public static final String PATH = "/microposts"; //$NON-NLS-1$ @Inject Models models;
@Inject MicroPostRepository microPosts;
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-shared/src/test/java/test/model/util/TestPostUtil.java
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/util/PostUtil.java // public enum PostUtil { // ; // public static final int PAGE_LENGTH = 10; // // public static int getPostCount() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // return store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .count(); // } // // public static Collection<String> getPostMonths() throws JsonException { // Collection<String> months = new TreeSet<>(); // // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .extract(JsonObject.of("posted", "posted")) //$NON-NLS-1$ //$NON-NLS-2$ // .find(entry -> { // String posted = entry.getString("posted"); //$NON-NLS-1$ // if(posted != null && posted.length() >= 7) { // months.add(posted.substring(0, 7)); // } // return true; // }); // // return months; // } // // public static Post createPost() { // Post post = new Post(); // post.setPosted(OffsetDateTime.now()); // post.setPostId(UUID.randomUUID().toString()); // // // It's not pretty, but it's CLOSER to replication-safe // Random random = new Random(); // PostRepository posts = CDI.current().select(PostRepository.class).get(); // int postIdInt; // do { // postIdInt = random.nextInt(); // } while(posts.findByPostIdInt(postIdInt).isPresent()); // post.setPostIdInt(postIdInt); // // return post; // } // // public static Collection<String> getCategories() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // JsonArray tags = (JsonArray)database.getStore(AppDatabaseDef.STORE_POSTS).getTags(Integer.MAX_VALUE, true); // return tags.stream() // .map(JsonObject.class::cast) // .map(tag -> tag.getAsString("name")) //$NON-NLS-1$ // .map(StringUtil::toString) // .collect(Collectors.toList()); // } // // public static int parseStartParam(final String startParam) { // int start; // if(StringUtil.isNotEmpty(startParam)) { // try { // start = Integer.parseInt(startParam); // } catch(NumberFormatException e) { // start = -1; // } // } else { // start = -1; // } // return start; // } // // /** // * Extracts the common name from the provided distinguished name, or returns // * the original value if the argument is not a valid DN. // * // * @param dn the LDAP-format distinguished name // * @return the common name component // * @since 2.2.0 // */ // public static String toCn(final String dn) { // if(StringUtil.isNotEmpty(dn)) { // try { // LdapName name = new LdapName(dn); // for(int i = name.size()-1; i >= 0; i--) { // String bit = name.get(i); // if(bit.toLowerCase().startsWith("cn=")) { //$NON-NLS-1$ // return bit.substring(3); // } // } // } catch(InvalidNameException e) { // return dn; // } // } // return StringUtil.EMPTY_STRING; // } // }
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import model.util.PostUtil;
/* * Copyright © 2012-2020 Jesse Gallagher * * 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 test.model.util; @SuppressWarnings("nls") public class TestPostUtil { @Test public void testToCn() {
// Path: frostillicus-blog/frostillicus-blog-shared/src/main/java/model/util/PostUtil.java // public enum PostUtil { // ; // public static final int PAGE_LENGTH = 10; // // public static int getPostCount() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // return store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .count(); // } // // public static Collection<String> getPostMonths() throws JsonException { // Collection<String> months = new TreeSet<>(); // // Database database = CDI.current().select(Database.class).get(); // Store store = database.getStore(AppDatabaseDef.STORE_POSTS); // store.openCursor() // .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ // .extract(JsonObject.of("posted", "posted")) //$NON-NLS-1$ //$NON-NLS-2$ // .find(entry -> { // String posted = entry.getString("posted"); //$NON-NLS-1$ // if(posted != null && posted.length() >= 7) { // months.add(posted.substring(0, 7)); // } // return true; // }); // // return months; // } // // public static Post createPost() { // Post post = new Post(); // post.setPosted(OffsetDateTime.now()); // post.setPostId(UUID.randomUUID().toString()); // // // It's not pretty, but it's CLOSER to replication-safe // Random random = new Random(); // PostRepository posts = CDI.current().select(PostRepository.class).get(); // int postIdInt; // do { // postIdInt = random.nextInt(); // } while(posts.findByPostIdInt(postIdInt).isPresent()); // post.setPostIdInt(postIdInt); // // return post; // } // // public static Collection<String> getCategories() throws JsonException { // Database database = CDI.current().select(Database.class).get(); // JsonArray tags = (JsonArray)database.getStore(AppDatabaseDef.STORE_POSTS).getTags(Integer.MAX_VALUE, true); // return tags.stream() // .map(JsonObject.class::cast) // .map(tag -> tag.getAsString("name")) //$NON-NLS-1$ // .map(StringUtil::toString) // .collect(Collectors.toList()); // } // // public static int parseStartParam(final String startParam) { // int start; // if(StringUtil.isNotEmpty(startParam)) { // try { // start = Integer.parseInt(startParam); // } catch(NumberFormatException e) { // start = -1; // } // } else { // start = -1; // } // return start; // } // // /** // * Extracts the common name from the provided distinguished name, or returns // * the original value if the argument is not a valid DN. // * // * @param dn the LDAP-format distinguished name // * @return the common name component // * @since 2.2.0 // */ // public static String toCn(final String dn) { // if(StringUtil.isNotEmpty(dn)) { // try { // LdapName name = new LdapName(dn); // for(int i = name.size()-1; i >= 0; i--) { // String bit = name.get(i); // if(bit.toLowerCase().startsWith("cn=")) { //$NON-NLS-1$ // return bit.substring(3); // } // } // } catch(InvalidNameException e) { // return dn; // } // } // return StringUtil.EMPTY_STRING; // } // } // Path: frostillicus-blog/frostillicus-blog-shared/src/test/java/test/model/util/TestPostUtil.java import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import model.util.PostUtil; /* * Copyright © 2012-2020 Jesse Gallagher * * 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 test.model.util; @SuppressWarnings("nls") public class TestPostUtil { @Test public void testToCn() {
assertEquals("Foo Fooson", PostUtil.toCn("cn=Foo Fooson,o=SomeOrg"));
mleoking/LeoTask
leotask/src/core/org/leores/util/Logger.java
// Path: leotask/src/core/org/leores/util/able/Processable2.java // public interface Processable2<R, A, B> { // public R process(A a, B b); // // public static class TrimStringField implements Processable2<Boolean, Object, Field> { // // public Boolean process(Object obj, Field field) { // boolean rtn = false; // if (field != null && U.bAssignable(String.class, field.getType())) { // String sValue = (String) U.getFieldValue(obj, field); // if (sValue != null) { // String sValue2 = sValue.trim(); // if (sValue2.length() < sValue.length()) { // rtn = true; // } // U.setFieldValue(obj, field, sValue2); // } // } // return rtn; // } // // } // // public static class SampleListByIndexB<B> implements Processable2<Boolean, Integer, B> { // public Integer step; // // /** // * The sample results will with these index: 0, 0+step, 0+2*step, ... // * // * @param step // */ // public SampleListByIndexB(Integer step) { // this.step = step; // } // // public Boolean process(Integer i, B b) { // return i % step == 0; // } // // } // // public static class SampleListByIndex<B> implements Processable2<B, Integer, B> { // public Integer step; // // /** // * The sample results will with these index: 0, 0+step, 0+2*step, ... // * // * @param step // */ // public SampleListByIndex(Integer step) { // this.step = step; // } // // public B process(Integer i, B b) { // B rtn = null; // if (i % step == 0) { // rtn = b; // } // return rtn; // } // } // // public static class RemoveRowWithInvalidNumber<B> implements Processable2<B[], Integer, B[]> { // public String sInvalid; // // /** // * E.g. "$%$<0" : remove rows with negative number. // * // * @param sInvalid // */ // public RemoveRowWithInvalidNumber(String sInvalid) { // this.sInvalid = sInvalid; // } // // public B[] process(Integer a, B[] b) { // B[] rtn = b; // for (int i = 0; i < b.length; i++) { // Double d = U.toDouble(b[i] + ""); // if (d != null) { // if (U.evalCheck(sInvalid, d)) { // rtn = null; // break; // } // } // } // return rtn; // } // }; // // }
import java.util.List; import org.leores.util.able.Processable2;
package org.leores.util; public class Logger { protected final static int LOG_MAX = 100; protected final static int LOG_CRITICAL = 80; protected final static int LOG_ERROR = 70; protected final static int LOG_WARNING = 60; protected final static int LOG_INFO = 50; //default log level protected final static int LOG_CASUAL = 40; protected final static int LOG_TRIVIAL = 30; protected final static int LOG_MIN = 0; protected String log = ""; protected Integer logRecordLevel = LOG_MAX; protected Integer logOutputLevel = LOG_MIN;
// Path: leotask/src/core/org/leores/util/able/Processable2.java // public interface Processable2<R, A, B> { // public R process(A a, B b); // // public static class TrimStringField implements Processable2<Boolean, Object, Field> { // // public Boolean process(Object obj, Field field) { // boolean rtn = false; // if (field != null && U.bAssignable(String.class, field.getType())) { // String sValue = (String) U.getFieldValue(obj, field); // if (sValue != null) { // String sValue2 = sValue.trim(); // if (sValue2.length() < sValue.length()) { // rtn = true; // } // U.setFieldValue(obj, field, sValue2); // } // } // return rtn; // } // // } // // public static class SampleListByIndexB<B> implements Processable2<Boolean, Integer, B> { // public Integer step; // // /** // * The sample results will with these index: 0, 0+step, 0+2*step, ... // * // * @param step // */ // public SampleListByIndexB(Integer step) { // this.step = step; // } // // public Boolean process(Integer i, B b) { // return i % step == 0; // } // // } // // public static class SampleListByIndex<B> implements Processable2<B, Integer, B> { // public Integer step; // // /** // * The sample results will with these index: 0, 0+step, 0+2*step, ... // * // * @param step // */ // public SampleListByIndex(Integer step) { // this.step = step; // } // // public B process(Integer i, B b) { // B rtn = null; // if (i % step == 0) { // rtn = b; // } // return rtn; // } // } // // public static class RemoveRowWithInvalidNumber<B> implements Processable2<B[], Integer, B[]> { // public String sInvalid; // // /** // * E.g. "$%$<0" : remove rows with negative number. // * // * @param sInvalid // */ // public RemoveRowWithInvalidNumber(String sInvalid) { // this.sInvalid = sInvalid; // } // // public B[] process(Integer a, B[] b) { // B[] rtn = b; // for (int i = 0; i < b.length; i++) { // Double d = U.toDouble(b[i] + ""); // if (d != null) { // if (U.evalCheck(sInvalid, d)) { // rtn = null; // break; // } // } // } // return rtn; // } // }; // // } // Path: leotask/src/core/org/leores/util/Logger.java import java.util.List; import org.leores.util.able.Processable2; package org.leores.util; public class Logger { protected final static int LOG_MAX = 100; protected final static int LOG_CRITICAL = 80; protected final static int LOG_ERROR = 70; protected final static int LOG_WARNING = 60; protected final static int LOG_INFO = 50; //default log level protected final static int LOG_CASUAL = 40; protected final static int LOG_TRIVIAL = 30; protected final static int LOG_MIN = 0; protected String log = ""; protected Integer logRecordLevel = LOG_MAX; protected Integer logOutputLevel = LOG_MIN;
protected Processable2<String, Integer, String> logProcessor = null;
mleoking/LeoTask
leotask/src/app/org/leores/demo/AnaDemo.java
// Path: leotask/src/core/org/leores/net/ana/Metric.java // public class Metric extends Logger { // protected Network tNet; // // public Metric(Network net) { // tNet = net; // } // // public Metric(String sFNet) { // tNet = Network.createFromFile(sFNet, null, null); // } // // /** // * Calculating Correlation Function r according to Eq.(4) in [1]. The // * variables correspond to (dA-dB)/(dC-dB) of Eq.(4) in [1]. It is also // * called Assortativity Coefficient. <br> // * <br> // * Here only calculate undirected links. <br> // * <br> // * [1]M. E. J. Newman, Assortative Mixing in Networks, Phys. Rev. Lett., // * vol. 89, no. 20, p. 208701, Oct. 2002. // * // * @return r. <b>r=1</b>:perfectly assortative, <b>r=0</b>: no assortative, // * <b>r=-1</b>:perfectly disassortative. // */ // // public Double correlationFunction() { // Double rtn = null; // // if (tNet != null) { // List<Link> links = tNet.getLinks(); // int M = links.size(); // BigDecimal iA = new BigDecimal(0), iB = new BigDecimal(0), iC = new BigDecimal(0); // double dA = 0.0, dB = 0.0, dC = 0.0; // for (int i = 0; i < M; i++) { // Link link = links.get(i); // Node.Degree ndFrom = link.from.getDegree(tNet); // Node.Degree ndTo = link.to.getDegree(tNet); // int j = ndFrom.undirected; // int k = ndTo.undirected; // iA = iA.add(new BigDecimal(j * k)); // iB = iB.add(new BigDecimal(j + k)); // iC = iC.add(new BigDecimal(j * j + k * k)); // } // dA = iA.doubleValue() / M; // dB = iB.doubleValue() / (2 * M); // dB = dB * dB; // dC = iC.doubleValue() / (2 * M); // if (dA == dB && dB == dC) { // rtn = 1.0; // } else { // rtn = (dA - dB) / (dC - dB); // } // //tLog("CorrelationFunction: " + rtn + " Links: " + M); // } // // return rtn; // } // // public Double avgDegree() { // Double rtn = null; // if (tNet != null) { // int degreeSum = 0; // // List<Integer> lDegree = tNet.getDegreeList(Link.Flag.UNDIRECTED); // for (int i = 0, size = lDegree.size(); i < size; i++) { // Integer nDegree = lDegree.get(i); // degreeSum += i * nDegree; // } // rtn = (double) degreeSum / tNet.nNodes(); // } // // return rtn; // } // // public Double avgDegreeSquare() { // Double rtn = null; // if (tNet != null) { // int degreeSquareSum = 0; // // List<Integer> lDegree = tNet.getDegreeList(Link.Flag.UNDIRECTED); // for (int i = 0, size = lDegree.size(); i < size; i++) { // Integer nDegree = lDegree.get(i); // degreeSquareSum += i * i * nDegree; // } // rtn = (double) degreeSquareSum / tNet.nNodes(); // } // // return rtn; // } // // /** // * g1b1 = (<k^2>-<k>)/<k> // * // * @return // */ // public Double g1b1() { // Double rtn = null; // Double avgDegree = avgDegree(); // Double avgDegreeSquare = avgDegreeSquare(); // if (avgDegree != null && avgDegreeSquare != null) { // rtn = ((double) avgDegreeSquare - avgDegree) / avgDegree; // } // // return rtn; // } // // public void printMetrics() { // Double cf = correlationFunction(); // Double ad = avgDegree(); // Double ads = avgDegreeSquare(); // Double g1b1 = g1b1(); // log("CorrelationFunction: " + cf + " AverageDegree:" + ad + " AverageDegreeSquare:" + ads + " g1b1:" + g1b1); // } // }
import org.leores.net.ana.Metric;
package org.leores.demo; public class AnaDemo extends Demo { public void batchMetric(String sFNet, String sExt, int iFrom, int iTo) { for (int i = iFrom; i <= iTo; i++) { String sFNeti = sFNet + i + sExt; log(sFNeti);
// Path: leotask/src/core/org/leores/net/ana/Metric.java // public class Metric extends Logger { // protected Network tNet; // // public Metric(Network net) { // tNet = net; // } // // public Metric(String sFNet) { // tNet = Network.createFromFile(sFNet, null, null); // } // // /** // * Calculating Correlation Function r according to Eq.(4) in [1]. The // * variables correspond to (dA-dB)/(dC-dB) of Eq.(4) in [1]. It is also // * called Assortativity Coefficient. <br> // * <br> // * Here only calculate undirected links. <br> // * <br> // * [1]M. E. J. Newman, Assortative Mixing in Networks, Phys. Rev. Lett., // * vol. 89, no. 20, p. 208701, Oct. 2002. // * // * @return r. <b>r=1</b>:perfectly assortative, <b>r=0</b>: no assortative, // * <b>r=-1</b>:perfectly disassortative. // */ // // public Double correlationFunction() { // Double rtn = null; // // if (tNet != null) { // List<Link> links = tNet.getLinks(); // int M = links.size(); // BigDecimal iA = new BigDecimal(0), iB = new BigDecimal(0), iC = new BigDecimal(0); // double dA = 0.0, dB = 0.0, dC = 0.0; // for (int i = 0; i < M; i++) { // Link link = links.get(i); // Node.Degree ndFrom = link.from.getDegree(tNet); // Node.Degree ndTo = link.to.getDegree(tNet); // int j = ndFrom.undirected; // int k = ndTo.undirected; // iA = iA.add(new BigDecimal(j * k)); // iB = iB.add(new BigDecimal(j + k)); // iC = iC.add(new BigDecimal(j * j + k * k)); // } // dA = iA.doubleValue() / M; // dB = iB.doubleValue() / (2 * M); // dB = dB * dB; // dC = iC.doubleValue() / (2 * M); // if (dA == dB && dB == dC) { // rtn = 1.0; // } else { // rtn = (dA - dB) / (dC - dB); // } // //tLog("CorrelationFunction: " + rtn + " Links: " + M); // } // // return rtn; // } // // public Double avgDegree() { // Double rtn = null; // if (tNet != null) { // int degreeSum = 0; // // List<Integer> lDegree = tNet.getDegreeList(Link.Flag.UNDIRECTED); // for (int i = 0, size = lDegree.size(); i < size; i++) { // Integer nDegree = lDegree.get(i); // degreeSum += i * nDegree; // } // rtn = (double) degreeSum / tNet.nNodes(); // } // // return rtn; // } // // public Double avgDegreeSquare() { // Double rtn = null; // if (tNet != null) { // int degreeSquareSum = 0; // // List<Integer> lDegree = tNet.getDegreeList(Link.Flag.UNDIRECTED); // for (int i = 0, size = lDegree.size(); i < size; i++) { // Integer nDegree = lDegree.get(i); // degreeSquareSum += i * i * nDegree; // } // rtn = (double) degreeSquareSum / tNet.nNodes(); // } // // return rtn; // } // // /** // * g1b1 = (<k^2>-<k>)/<k> // * // * @return // */ // public Double g1b1() { // Double rtn = null; // Double avgDegree = avgDegree(); // Double avgDegreeSquare = avgDegreeSquare(); // if (avgDegree != null && avgDegreeSquare != null) { // rtn = ((double) avgDegreeSquare - avgDegree) / avgDegree; // } // // return rtn; // } // // public void printMetrics() { // Double cf = correlationFunction(); // Double ad = avgDegree(); // Double ads = avgDegreeSquare(); // Double g1b1 = g1b1(); // log("CorrelationFunction: " + cf + " AverageDegree:" + ad + " AverageDegreeSquare:" + ads + " g1b1:" + g1b1); // } // } // Path: leotask/src/app/org/leores/demo/AnaDemo.java import org.leores.net.ana.Metric; package org.leores.demo; public class AnaDemo extends Demo { public void batchMetric(String sFNet, String sExt, int iFrom, int iTo) { for (int i = iFrom; i <= iTo; i++) { String sFNeti = sFNet + i + sExt; log(sFNeti);
Metric metric = new Metric(sFNeti);
mleoking/LeoTask
leotask/src/core/org/leores/util/StrUtil.java
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/UnsupportedTypeException.java // public class UnsupportedTypeException extends TException { // public UnsupportedTypeException(Object obj) { // super(obj); // return; // } // // public UnsupportedTypeException(Object... objs) { // super(objs); // return; // } // // public UnsupportedTypeException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/WrongFormatException.java // public class WrongFormatException extends TException { // public WrongFormatException(Object obj) { // super(obj); // return; // } // // public WrongFormatException(Object... objs) { // super(objs); // return; // } // // public WrongFormatException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // }
import java.io.File; import java.math.BigDecimal; import java.net.URL; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.leores.ecpt.TRuntimeException; import org.leores.ecpt.UnsupportedTypeException; import org.leores.ecpt.WrongFormatException; import org.leores.ecpt.WrongParameterException;
package org.leores.util; public class StrUtil extends LogUtil { public static String sBlock = "}"; //Priority high public static String sEnumerate = ";"; public static String sRepeat = "@"; public static String sStep = ":";//Priority low public static String sNoEval = "~"; public static String de = ","; public static String sSet = "="; //\\S+? Several non-whitespace characters ? makes quantifier "+" reluctant. It tries to find the smallest match. public static String sPatVar = "\\$(\\S+?)\\$"; public static String sPatExp = "#(\\S+?)#"; public static String sSelf = "%"; public static final int EVAL_InvalidIgnore = 0x00000001; public static final int EVAL_InvalidException = 0x00000002; public static final int EVAL_NullIgnore = 0x00000004; public static final int EVAL_NullException = 0x00000008; public static String sPatEvalNumOut = null;//set this to null to use the default number out pattern in the system. public static boolean bAssignable(Class cTo, Class cFrom) { boolean rtn = false; if (cFrom == null) { rtn = true; } else if (cTo != null) { rtn = cTo.isAssignableFrom(cFrom); } return rtn; } public static List parseList(Class type, String[] tokens, boolean bStepped) { List rtnList = null; if (bStepped && tokens.length < 3) {
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/UnsupportedTypeException.java // public class UnsupportedTypeException extends TException { // public UnsupportedTypeException(Object obj) { // super(obj); // return; // } // // public UnsupportedTypeException(Object... objs) { // super(objs); // return; // } // // public UnsupportedTypeException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/WrongFormatException.java // public class WrongFormatException extends TException { // public WrongFormatException(Object obj) { // super(obj); // return; // } // // public WrongFormatException(Object... objs) { // super(objs); // return; // } // // public WrongFormatException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // Path: leotask/src/core/org/leores/util/StrUtil.java import java.io.File; import java.math.BigDecimal; import java.net.URL; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.leores.ecpt.TRuntimeException; import org.leores.ecpt.UnsupportedTypeException; import org.leores.ecpt.WrongFormatException; import org.leores.ecpt.WrongParameterException; package org.leores.util; public class StrUtil extends LogUtil { public static String sBlock = "}"; //Priority high public static String sEnumerate = ";"; public static String sRepeat = "@"; public static String sStep = ":";//Priority low public static String sNoEval = "~"; public static String de = ","; public static String sSet = "="; //\\S+? Several non-whitespace characters ? makes quantifier "+" reluctant. It tries to find the smallest match. public static String sPatVar = "\\$(\\S+?)\\$"; public static String sPatExp = "#(\\S+?)#"; public static String sSelf = "%"; public static final int EVAL_InvalidIgnore = 0x00000001; public static final int EVAL_InvalidException = 0x00000002; public static final int EVAL_NullIgnore = 0x00000004; public static final int EVAL_NullException = 0x00000008; public static String sPatEvalNumOut = null;//set this to null to use the default number out pattern in the system. public static boolean bAssignable(Class cTo, Class cFrom) { boolean rtn = false; if (cFrom == null) { rtn = true; } else if (cTo != null) { rtn = cTo.isAssignableFrom(cFrom); } return rtn; } public static List parseList(Class type, String[] tokens, boolean bStepped) { List rtnList = null; if (bStepped && tokens.length < 3) {
throw new TRuntimeException("Stepped type has less than 3 tokens: " + U.toStr(tokens));
mleoking/LeoTask
leotask/src/core/org/leores/util/StrUtil.java
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/UnsupportedTypeException.java // public class UnsupportedTypeException extends TException { // public UnsupportedTypeException(Object obj) { // super(obj); // return; // } // // public UnsupportedTypeException(Object... objs) { // super(objs); // return; // } // // public UnsupportedTypeException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/WrongFormatException.java // public class WrongFormatException extends TException { // public WrongFormatException(Object obj) { // super(obj); // return; // } // // public WrongFormatException(Object... objs) { // super(objs); // return; // } // // public WrongFormatException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // }
import java.io.File; import java.math.BigDecimal; import java.net.URL; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.leores.ecpt.TRuntimeException; import org.leores.ecpt.UnsupportedTypeException; import org.leores.ecpt.WrongFormatException; import org.leores.ecpt.WrongParameterException;
if (bNoEval(s)) { rtn = new ArrayList<A>(); rtn.add((A) s); } else if (type != null && s != null) { String s_ = s.trim(); if ("".equals(s_)) { rtn = new ArrayList<A>(); } else if (s_.indexOf(sBlock) >= 0) { String[] tokens = s_.split(sBlock); rtn = parseList(type, tokens, false); } else if (s_.indexOf(sEnumerate) >= 0) { String[] tokens = s_.split(sEnumerate); rtn = new ArrayList<A>(); for (int i = 0; i < tokens.length; i++) { List<A> listi = parseList(type, tokens[i]); rtn.addAll(listi); } } else if (s_.indexOf(sRepeat) >= 0) { String[] tokens = s_.split(sRepeat); Integer nRepeat = Integer.parseInt(tokens[1]); String[] tokens2 = new String[nRepeat]; for (int i = 0; i < nRepeat; i++) { tokens2[i] = tokens[0]; } rtn = parseList(type, tokens2, false); } else if (s_.indexOf(sStep) >= 0) { String[] tokens = s_.split(sStep); if (tokens.length >= 3) { rtn = parseList(type, tokens, true); } else {
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/UnsupportedTypeException.java // public class UnsupportedTypeException extends TException { // public UnsupportedTypeException(Object obj) { // super(obj); // return; // } // // public UnsupportedTypeException(Object... objs) { // super(objs); // return; // } // // public UnsupportedTypeException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/WrongFormatException.java // public class WrongFormatException extends TException { // public WrongFormatException(Object obj) { // super(obj); // return; // } // // public WrongFormatException(Object... objs) { // super(objs); // return; // } // // public WrongFormatException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // Path: leotask/src/core/org/leores/util/StrUtil.java import java.io.File; import java.math.BigDecimal; import java.net.URL; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.leores.ecpt.TRuntimeException; import org.leores.ecpt.UnsupportedTypeException; import org.leores.ecpt.WrongFormatException; import org.leores.ecpt.WrongParameterException; if (bNoEval(s)) { rtn = new ArrayList<A>(); rtn.add((A) s); } else if (type != null && s != null) { String s_ = s.trim(); if ("".equals(s_)) { rtn = new ArrayList<A>(); } else if (s_.indexOf(sBlock) >= 0) { String[] tokens = s_.split(sBlock); rtn = parseList(type, tokens, false); } else if (s_.indexOf(sEnumerate) >= 0) { String[] tokens = s_.split(sEnumerate); rtn = new ArrayList<A>(); for (int i = 0; i < tokens.length; i++) { List<A> listi = parseList(type, tokens[i]); rtn.addAll(listi); } } else if (s_.indexOf(sRepeat) >= 0) { String[] tokens = s_.split(sRepeat); Integer nRepeat = Integer.parseInt(tokens[1]); String[] tokens2 = new String[nRepeat]; for (int i = 0; i < nRepeat; i++) { tokens2[i] = tokens[0]; } rtn = parseList(type, tokens2, false); } else if (s_.indexOf(sStep) >= 0) { String[] tokens = s_.split(sStep); if (tokens.length >= 3) { rtn = parseList(type, tokens, true); } else {
throw new WrongFormatException(s_);
mleoking/LeoTask
leotask/src/core/org/leores/util/TestUtil.java
// Path: leotask/src/core/org/leores/util/able/Processable0.java // public interface Processable0<R> { // public R process(); // }
import org.leores.util.able.Processable0;
package org.leores.util; public class TestUtil extends LogUtil { public static double[] compareRunTime(int nRept, int nComp, Runnable... runs) { double[] rtn = new double[runs.length]; Timer timer = new Timer(); tLog("TestUtil.compareRunTime : ", U.toStr(runs)); for (int i = 0; i < nComp; i++) { tLog("----- " + i + " -----"); for (int k = 0; k < runs.length; k++) { long tTotal = 0; for (int j = 0; j < nRept; j++) { timer.start(); runs[k].run(); tTotal += timer.stop(); } double tAverage = (double) tTotal / nRept; rtn[k] = tAverage; tLog("r" + k + " [average, total]ms : ", tAverage, tTotal); } } tLog("----- End -----"); return rtn; }
// Path: leotask/src/core/org/leores/util/able/Processable0.java // public interface Processable0<R> { // public R process(); // } // Path: leotask/src/core/org/leores/util/TestUtil.java import org.leores.util.able.Processable0; package org.leores.util; public class TestUtil extends LogUtil { public static double[] compareRunTime(int nRept, int nComp, Runnable... runs) { double[] rtn = new double[runs.length]; Timer timer = new Timer(); tLog("TestUtil.compareRunTime : ", U.toStr(runs)); for (int i = 0; i < nComp; i++) { tLog("----- " + i + " -----"); for (int k = 0; k < runs.length; k++) { long tTotal = 0; for (int j = 0; j < nRept; j++) { timer.start(); runs[k].run(); tTotal += timer.stop(); } double tAverage = (double) tTotal / nRept; rtn[k] = tAverage; tLog("r" + k + " [average, total]ms : ", tAverage, tTotal); } } tLog("----- End -----"); return rtn; }
public static double[] compareRunTime(int nRept, int nComp, Processable0<Double>... pros) {
mleoking/LeoTask
leotask/src/app/org/leores/demo/Demo.java
// Path: leotask/src/core/org/leores/util/LogUtil.java // public class LogUtil extends Logger { // // public static int ll(String sLogLevel) { // int rtn = -1; // if (sLogLevel != null) { // rtn = (Integer) U.getFieldValue(getTLogger(), sLogLevel, U.modPubPro); // } // return rtn; // } // // public static String _tLog(int logLevel, String str) { // return getTLogger()._log(logLevel, str); // } // // public static String tLog(int logLevel, boolean addLineBreak, String str) { // return getTLogger().log(logLevel, addLineBreak, str); // } // // public static String tLog(int logLevel, String str) { // return getTLogger().log(logLevel, str); // } // // public static String tLog(boolean addLineBreak, String str) { // return getTLogger().log(addLineBreak, str); // } // // public static String tLog(String str) { // return getTLogger().log(str); // } // // public static String tLog(Exception e) { // return getTLogger().log(e); // } // // public static String tLog(Object obj) { // return getTLogger().log(obj); // } // // public static String tLog(String str, Object obj) { // return getTLogger().log(str, obj); // } // // public static String tLog(Object... objs) { // return getTLogger().log(objs); // } // // public static String tLog(String str, Object... objs) { // return getTLogger().log(str, objs); // } // } // // Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // }
import org.leores.util.LogUtil; import org.leores.util.U;
package org.leores.demo; public class Demo extends LogUtil { public static void demo() { } /** * Set the working directory to be ${workspace_loc:leotask/demo} in Eclipse. * In other IDEs set the working directory to the "demo" folder. * * @param args */ public static void main(String[] args) {
// Path: leotask/src/core/org/leores/util/LogUtil.java // public class LogUtil extends Logger { // // public static int ll(String sLogLevel) { // int rtn = -1; // if (sLogLevel != null) { // rtn = (Integer) U.getFieldValue(getTLogger(), sLogLevel, U.modPubPro); // } // return rtn; // } // // public static String _tLog(int logLevel, String str) { // return getTLogger()._log(logLevel, str); // } // // public static String tLog(int logLevel, boolean addLineBreak, String str) { // return getTLogger().log(logLevel, addLineBreak, str); // } // // public static String tLog(int logLevel, String str) { // return getTLogger().log(logLevel, str); // } // // public static String tLog(boolean addLineBreak, String str) { // return getTLogger().log(addLineBreak, str); // } // // public static String tLog(String str) { // return getTLogger().log(str); // } // // public static String tLog(Exception e) { // return getTLogger().log(e); // } // // public static String tLog(Object obj) { // return getTLogger().log(obj); // } // // public static String tLog(String str, Object obj) { // return getTLogger().log(str, obj); // } // // public static String tLog(Object... objs) { // return getTLogger().log(objs); // } // // public static String tLog(String str, Object... objs) { // return getTLogger().log(str, objs); // } // } // // Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // Path: leotask/src/app/org/leores/demo/Demo.java import org.leores.util.LogUtil; import org.leores.util.U; package org.leores.demo; public class Demo extends LogUtil { public static void demo() { } /** * Set the working directory to be ${workspace_loc:leotask/demo} in Eclipse. * In other IDEs set the working directory to the "demo" folder. * * @param args */ public static void main(String[] args) {
U.tLog("Set the working directory to be ${workspace_loc:leotask/demo} in Eclipse. In other IDEs set the working directory to the \"demo\" folder.");
mleoking/LeoTask
leotask/src/core/org/leores/net/Network.java
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.*; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1;
package org.leores.net; public class Network extends Element { private static final long serialVersionUID = 31657104899522855L; protected static Integer nNetwork = 0; protected Networks nets; protected List<Node> nodes; protected List<Link> links; protected HashMap<Integer, Node> mId2ToNode;
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/net/Network.java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.*; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1; package org.leores.net; public class Network extends Element { private static final long serialVersionUID = 31657104899522855L; protected static Integer nNetwork = 0; protected Networks nets; protected List<Node> nodes; protected List<Link> links; protected HashMap<Integer, Node> mId2ToNode;
protected NewInstanceable<Node> nIaNode;
mleoking/LeoTask
leotask/src/core/org/leores/net/Network.java
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.*; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1;
public Network clone() { return clone(null, null, null, null); } public void clear() { nNetwork = 0; nodes.clear(); links.clear(); if (mId2ToNode != null) { mId2ToNode.clear(); } } public Node newNode() { return nIaNode.newInstance(); } public Link newLink() { return nIaLink.newInstance(); } public String toStr() { String rtn = "Network" + sDe + id + sDe + nodes.size() + sDe + links.size(); String sInfo = sInfo(); if (sInfo != null) {//We have to use sInfo() here rather than info because Element.beforeSaveInfo is called in sInfo(). rtn += sDe + sInfo; } return rtn; }
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/net/Network.java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.*; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1; public Network clone() { return clone(null, null, null, null); } public void clear() { nNetwork = 0; nodes.clear(); links.clear(); if (mId2ToNode != null) { mId2ToNode.clear(); } } public Node newNode() { return nIaNode.newInstance(); } public Link newLink() { return nIaLink.newInstance(); } public String toStr() { String rtn = "Network" + sDe + id + sDe + nodes.size() + sDe + links.size(); String sInfo = sInfo(); if (sInfo != null) {//We have to use sInfo() here rather than info because Element.beforeSaveInfo is called in sInfo(). rtn += sDe + sInfo; } return rtn; }
public List<Node.Degree> updateDegreeList(Processable1<Boolean, Node> pa1) {
mleoking/LeoTask
leotask/src/core/org/leores/net/Network.java
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.*; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1;
rtn.clear(); for (int i = 0, size = nodes.size(); i < size; i++) { Node node = nodes.get(i); if (node != null && (pa1 == null || pa1.process(node))) { //degree should not be null here as node in nodes should be in this network! Node.Degree degree = node.getDegree(this); while (rtn.size() < degree.max() + 1) { Node.Degree nd = new Node.Degree(); rtn.add(nd); } Node.Degree eNodeDegree; eNodeDegree = rtn.get(degree.in); eNodeDegree.in++; eNodeDegree = rtn.get(degree.out); eNodeDegree.out++; eNodeDegree = rtn.get(degree.undirected); eNodeDegree.undirected++; } } return rtn; } public List<Integer> getDegreeList(int flags, Processable1<Boolean, Node> pa1) { List<Integer> rtn = new ArrayList<Integer>(); updateDegreeList(pa1); for (int i = 0, size = lDegree.size(); i < size; i++) { Integer nDegree = 0; Node.Degree eDegree = lDegree.get(i);
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/net/Network.java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.*; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1; rtn.clear(); for (int i = 0, size = nodes.size(); i < size; i++) { Node node = nodes.get(i); if (node != null && (pa1 == null || pa1.process(node))) { //degree should not be null here as node in nodes should be in this network! Node.Degree degree = node.getDegree(this); while (rtn.size() < degree.max() + 1) { Node.Degree nd = new Node.Degree(); rtn.add(nd); } Node.Degree eNodeDegree; eNodeDegree = rtn.get(degree.in); eNodeDegree.in++; eNodeDegree = rtn.get(degree.out); eNodeDegree.out++; eNodeDegree = rtn.get(degree.undirected); eNodeDegree.undirected++; } } return rtn; } public List<Integer> getDegreeList(int flags, Processable1<Boolean, Node> pa1) { List<Integer> rtn = new ArrayList<Integer>(); updateDegreeList(pa1); for (int i = 0, size = lDegree.size(); i < size; i++) { Integer nDegree = 0; Node.Degree eDegree = lDegree.get(i);
if ((flags & Link.Flag.IN) > 0) {
mleoking/LeoTask
leotask/src/core/org/leores/util/Worker.java
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/NextRunnable.java // public interface NextRunnable { // public Runnable nextRun(); // }
import org.leores.ecpt.WrongParameterException; import org.leores.util.able.NextRunnable;
package org.leores.util; public class Worker implements Runnable { public ThreadWorkers tTWorkers;
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/NextRunnable.java // public interface NextRunnable { // public Runnable nextRun(); // } // Path: leotask/src/core/org/leores/util/Worker.java import org.leores.ecpt.WrongParameterException; import org.leores.util.able.NextRunnable; package org.leores.util; public class Worker implements Runnable { public ThreadWorkers tTWorkers;
public NextRunnable tNRunnable;
mleoking/LeoTask
leotask/src/core/org/leores/util/Worker.java
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/NextRunnable.java // public interface NextRunnable { // public Runnable nextRun(); // }
import org.leores.ecpt.WrongParameterException; import org.leores.util.able.NextRunnable;
package org.leores.util; public class Worker implements Runnable { public ThreadWorkers tTWorkers; public NextRunnable tNRunnable; public Integer tId; public Integer nRun; public Boolean bFinished; public Runnable tRunnable; public Worker(ThreadWorkers tW, NextRunnable nR, Integer id)
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/NextRunnable.java // public interface NextRunnable { // public Runnable nextRun(); // } // Path: leotask/src/core/org/leores/util/Worker.java import org.leores.ecpt.WrongParameterException; import org.leores.util.able.NextRunnable; package org.leores.util; public class Worker implements Runnable { public ThreadWorkers tTWorkers; public NextRunnable tNRunnable; public Integer tId; public Integer nRun; public Boolean bFinished; public Runnable tRunnable; public Worker(ThreadWorkers tW, NextRunnable nR, Integer id)
throws WrongParameterException {
mleoking/LeoTask
leotask/src/core/org/leores/util/LoadHashMap.java
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // }
import java.util.HashMap; import org.leores.ecpt.TRuntimeException;
package org.leores.util; public class LoadHashMap<K, V> extends HashMap<K, V> { private static final long serialVersionUID = 2637966156374453176L; public LoadHashMap(String loadStr) { super(); if (!U.loadFromString(this, loadStr)) {
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // } // Path: leotask/src/core/org/leores/util/LoadHashMap.java import java.util.HashMap; import org.leores.ecpt.TRuntimeException; package org.leores.util; public class LoadHashMap<K, V> extends HashMap<K, V> { private static final long serialVersionUID = 2637966156374453176L; public LoadHashMap(String loadStr) { super(); if (!U.loadFromString(this, loadStr)) {
throw new TRuntimeException("LoadHashMap: Failed to load [" + loadStr + "]");
mleoking/LeoTask
leotask/src/core/org/leores/util/SerialUtil.java
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.leores.ecpt.TRuntimeException; import org.leores.util.able.Processable1; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;
package org.leores.util; public class SerialUtil extends ObjUtil { public static String[] toStrArray(Class tClass, Integer mod) { String[] rtn = null; if (tClass != null) { Field[] fields = getFields(tClass, mod); rtn = new String[fields.length]; for (int i = 0; i < fields.length; i++) { rtn[i] = fields[i].getName(); } } return rtn; } public static String[] toStrArray(Class tClass) { return toStrArray(tClass, null); }
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/util/SerialUtil.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.leores.ecpt.TRuntimeException; import org.leores.util.able.Processable1; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; package org.leores.util; public class SerialUtil extends ObjUtil { public static String[] toStrArray(Class tClass, Integer mod) { String[] rtn = null; if (tClass != null) { Field[] fields = getFields(tClass, mod); rtn = new String[fields.length]; for (int i = 0; i < fields.length; i++) { rtn[i] = fields[i].getName(); } } return rtn; } public static String[] toStrArray(Class tClass) { return toStrArray(tClass, null); }
public static String[][] toStrArray(Object tObj, String[] sFields, String sPatNumOut, Integer mod, Processable1<String, Object> pa1) {
mleoking/LeoTask
leotask/src/core/org/leores/util/SerialUtil.java
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.leores.ecpt.TRuntimeException; import org.leores.util.able.Processable1; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;
* Load fields' value of tObj from a xml file fn. This function does not * support Primitive Data Types. They has to be replaced by their * corresponding Object classes. e.g. double->Double * * @param tObj * @param sFile * @param bUnMatchException * true: throw a TRuntimeException when the root element does not * match the Object class. * @return */ public static boolean loadFromXML(Object tObj, String sFile, boolean bUnMatchException) { boolean rtn = false; if (tObj != null && U.valid(sFile)) { if (U.bExistFile(sFile)) { try { File file = new File(sFile); DocumentBuilderFactory dBFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dBFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); Class objClass = tObj.getClass(); Element eRoot = doc.getDocumentElement(); String objClassName = objClass.getName(); String docRootName = eRoot.getNodeName(); if (objClassName.indexOf(docRootName) < 0 && bUnMatchException) {
// Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java // public class TRuntimeException extends RuntimeException { // private static final long serialVersionUID = -1540271937983801068L; // // public TRuntimeException() { // super(); // return; // } // // public TRuntimeException(Object obj) { // super(U.toStr(obj)); // return; // } // // public TRuntimeException(Object... objs) { // this("", objs); // return; // } // // public TRuntimeException(String str, Object... objs) { // super(str + U.toStr(objs)); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/util/SerialUtil.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.leores.ecpt.TRuntimeException; import org.leores.util.able.Processable1; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; * Load fields' value of tObj from a xml file fn. This function does not * support Primitive Data Types. They has to be replaced by their * corresponding Object classes. e.g. double->Double * * @param tObj * @param sFile * @param bUnMatchException * true: throw a TRuntimeException when the root element does not * match the Object class. * @return */ public static boolean loadFromXML(Object tObj, String sFile, boolean bUnMatchException) { boolean rtn = false; if (tObj != null && U.valid(sFile)) { if (U.bExistFile(sFile)) { try { File file = new File(sFile); DocumentBuilderFactory dBFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dBFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); Class objClass = tObj.getClass(); Element eRoot = doc.getDocumentElement(); String objClassName = objClass.getName(); String docRootName = eRoot.getNodeName(); if (objClassName.indexOf(docRootName) < 0 && bUnMatchException) {
throw new TRuntimeException("loadFromXML: root element does not match the Object class! [sFile,objClassName,docRootName]:", sFile, objClassName, docRootName);
mleoking/LeoTask
leotask/src/core/org/leores/net/Node.java
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1;
public Integer in = 0; public Integer out = 0; public Integer undirected = 0; public int all() { return in + out + undirected; } public int max() { int rtn = -1; if (in > rtn) { rtn = in; } if (out > rtn) { rtn = out; } if (undirected > rtn) { rtn = undirected; } return rtn; } } public static class NodeLinks implements Serializable { private static final long serialVersionUID = 3531445922204864535L; public List<Link> in; public List<Link> out; public List<Link> undirected; }
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/net/Node.java import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1; public Integer in = 0; public Integer out = 0; public Integer undirected = 0; public int all() { return in + out + undirected; } public int max() { int rtn = -1; if (in > rtn) { rtn = in; } if (out > rtn) { rtn = out; } if (undirected > rtn) { rtn = undirected; } return rtn; } } public static class NodeLinks implements Serializable { private static final long serialVersionUID = 3531445922204864535L; public List<Link> in; public List<Link> out; public List<Link> undirected; }
public static class NewNode implements NewInstanceable<Node> {
mleoking/LeoTask
leotask/src/core/org/leores/net/Node.java
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1;
links.set(net.id, null); rtn = true; } } return rtn; } public boolean changeNetworkId(Integer from, Integer to) { boolean rtn = false; NodeLinks nLinks = links.get(from); if (nLinks != null) { links.set(from, null); while (links.size() <= to) { links.add(null); } NodeLinks nLinksTo = links.get(to); if (nLinksTo == null) { rtn = true; links.set(to, nLinks); } else { rtn = false; } } return rtn; }
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/net/Node.java import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1; links.set(net.id, null); rtn = true; } } return rtn; } public boolean changeNetworkId(Integer from, Integer to) { boolean rtn = false; NodeLinks nLinks = links.get(from); if (nLinks != null) { links.set(from, null); while (links.size() <= to) { links.add(null); } NodeLinks nLinksTo = links.get(to); if (nLinksTo == null) { rtn = true; links.set(to, nLinks); } else { rtn = false; } } return rtn; }
protected boolean getLinks(List<Link> lTo, List<Link> lFrom, Processable1<Boolean, Link> pa1) {
mleoking/LeoTask
leotask/src/core/org/leores/net/Node.java
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1;
/** * Check whether tNode in the parameter is linked by the links in lLink. * (tNode could be either From or To node of a link) * * @param lLink * @param tNode * @return */ protected boolean bLinked(List<Link> lLink, Node tNode) { boolean rtn = false; if (lLink != null) { for (int i = 0, size = lLink.size(); i < size; i++) { Link link = lLink.get(i); Node node = link.getOtherNode(this); if (node == tNode) { rtn = true; break; } } } return rtn; } protected boolean bLinked(NodeLinks nLinks, Node tNode, int flags) { boolean rtn = false; if (nLinks != null) {
// Path: leotask/src/core/org/leores/net/Link.java // public static class Flag implements Serializable { // private static final long serialVersionUID = 1600634581856522821L; // public static final int IN = 1; // Binary 00001 // public static final int OUT = 2; // Binary 00010 // public static final int UNDIRECTED = 4; // Binary 00100 // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/net/Node.java import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.leores.net.Link.Flag; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1; /** * Check whether tNode in the parameter is linked by the links in lLink. * (tNode could be either From or To node of a link) * * @param lLink * @param tNode * @return */ protected boolean bLinked(List<Link> lLink, Node tNode) { boolean rtn = false; if (lLink != null) { for (int i = 0, size = lLink.size(); i < size; i++) { Link link = lLink.get(i); Node node = link.getOtherNode(this); if (node == tNode) { rtn = true; break; } } } return rtn; } protected boolean bLinked(NodeLinks nLinks, Node tNode, int flags) { boolean rtn = false; if (nLinks != null) {
if ((!rtn) && (flags & Flag.IN) > 0) {
mleoking/LeoTask
leotask/src/core/org/leores/net/Link.java
// Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // }
import java.io.Serializable; import org.leores.util.*; import org.leores.util.able.NewInstanceable;
package org.leores.net; public class Link extends Element { private static final long serialVersionUID = 4225350389021346030L; public static class Flag implements Serializable { private static final long serialVersionUID = 1600634581856522821L; public static final int IN = 1; // Binary 00001 public static final int OUT = 2; // Binary 00010 public static final int UNDIRECTED = 4; // Binary 00100 }
// Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // Path: leotask/src/core/org/leores/net/Link.java import java.io.Serializable; import org.leores.util.*; import org.leores.util.able.NewInstanceable; package org.leores.net; public class Link extends Element { private static final long serialVersionUID = 4225350389021346030L; public static class Flag implements Serializable { private static final long serialVersionUID = 1600634581856522821L; public static final int IN = 1; // Binary 00001 public static final int OUT = 2; // Binary 00010 public static final int UNDIRECTED = 4; // Binary 00100 }
public static class NewLink implements NewInstanceable<Link>, Serializable {
mleoking/LeoTask
leotask/src/core/org/leores/math/Minimizer.java
// Path: leotask/src/core/org/leores/util/Logger.java // public class Logger { // protected final static int LOG_MAX = 100; // protected final static int LOG_CRITICAL = 80; // protected final static int LOG_ERROR = 70; // protected final static int LOG_WARNING = 60; // protected final static int LOG_INFO = 50; //default log level // protected final static int LOG_CASUAL = 40; // protected final static int LOG_TRIVIAL = 30; // protected final static int LOG_MIN = 0; // // protected String log = ""; // protected Integer logRecordLevel = LOG_MAX; // protected Integer logOutputLevel = LOG_MIN; // protected Processable2<String, Integer, String> logProcessor = null; // protected static Logger tLogger = new Logger(); // // public static void setTLogger(Logger logger) { // tLogger = logger; // } // // public static Logger getTLogger() { // return tLogger; // } // // public String getLog() { // return log; // } // // public void setLogProcessor(Processable2<String, Integer, String> logProcessor) { // this.logProcessor = logProcessor; // } // // public Integer getLogRecordLevel() { // return logRecordLevel; // } // // public void setLogRecordLevel(Integer logRecordLevel) { // this.logRecordLevel = logRecordLevel; // } // // public Integer getLogOutputLevel() { // return logOutputLevel; // } // // public void setLogOutputLevel(Integer logOutputLevel) { // this.logOutputLevel = logOutputLevel; // } // // protected String process(int logLevel, String str) { // String rtn = str; // if (logProcessor != null) { // rtn = logProcessor.process(logLevel, str); // } // return rtn; // } // // protected String _log(int logLevel, String str) { // if (logLevel >= LOG_ERROR) { // System.err.print(str); // } else { // System.out.print(str); // } // return str; // } // // protected String log(int logLevel, boolean addLineBreak, String str) { // String rtn = process(logLevel, str); // if (rtn != null) { // String sEnd = ""; // if (addLineBreak) { // sEnd = "\n"; // } // if (logLevel >= logRecordLevel) { // log += rtn + sEnd; // } // if (logLevel >= logOutputLevel) { // if (getTLogger().equals(this)) { // rtn = _log(logLevel, rtn + sEnd); // } else { // rtn = getTLogger().log(logLevel, addLineBreak, rtn); // } // // } // } // return rtn; // } // // protected String log(int logLevel, String str) { // return log(logLevel, true, str); // } // // protected String log(boolean addLineBreak, String str) { // return log(LOG_INFO, addLineBreak, str); // } // // protected String log(Exception e) { // e.printStackTrace(); // return log(LOG_ERROR, true, e.toString()); // } // // protected String log(String str) { // return log(LOG_INFO, true, str); // } // // protected String log(String str, Object obj) { // return log(str + U.toStr(obj)); // } // // protected String log(String str, Object... objs) { // return log(str + U.toStr(objs)); // } // // protected String log(Object obj) { // return log("", obj); // } // // protected String log(Object... objs) { // return log("", objs); // } // // } // // Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // }
import java.util.Random; import java.util.Arrays; import java.util.Vector; import java.util.Hashtable; import org.leores.util.Logger; import org.leores.util.U;
* of the target function */ private void order(double[][] simp, int[] worstNextBestArray) { int worst = 0, nextWorst = 0, best = 0; for (int i = 0; i < numVertices; i++) { if (value(simp[i]) < value(simp[best])) best = i; if (value(simp[i]) > value(simp[worst])) worst = i; } nextWorst = best; for (int i = 0; i < numVertices; i++) if (i != worst && value(simp[i]) > value(simp[nextWorst])) nextWorst = i; worstNextBestArray[WORST] = worst; worstNextBestArray[NEXT_WORST] = nextWorst; worstNextBestArray[BEST] = best; } //simplex [Iteration: s0(p1, p2....), s1(),....] private synchronized String sSimplex(double[][] simp) { String rtn = ""; for (int i = 0; i < numVertices; i++) rtn += sVertex(simp[i]) + " | "; return rtn; } private synchronized String sVertex(double[] vertex) { String rtn = ""; for (int j = 0; j < numParams; j++)
// Path: leotask/src/core/org/leores/util/Logger.java // public class Logger { // protected final static int LOG_MAX = 100; // protected final static int LOG_CRITICAL = 80; // protected final static int LOG_ERROR = 70; // protected final static int LOG_WARNING = 60; // protected final static int LOG_INFO = 50; //default log level // protected final static int LOG_CASUAL = 40; // protected final static int LOG_TRIVIAL = 30; // protected final static int LOG_MIN = 0; // // protected String log = ""; // protected Integer logRecordLevel = LOG_MAX; // protected Integer logOutputLevel = LOG_MIN; // protected Processable2<String, Integer, String> logProcessor = null; // protected static Logger tLogger = new Logger(); // // public static void setTLogger(Logger logger) { // tLogger = logger; // } // // public static Logger getTLogger() { // return tLogger; // } // // public String getLog() { // return log; // } // // public void setLogProcessor(Processable2<String, Integer, String> logProcessor) { // this.logProcessor = logProcessor; // } // // public Integer getLogRecordLevel() { // return logRecordLevel; // } // // public void setLogRecordLevel(Integer logRecordLevel) { // this.logRecordLevel = logRecordLevel; // } // // public Integer getLogOutputLevel() { // return logOutputLevel; // } // // public void setLogOutputLevel(Integer logOutputLevel) { // this.logOutputLevel = logOutputLevel; // } // // protected String process(int logLevel, String str) { // String rtn = str; // if (logProcessor != null) { // rtn = logProcessor.process(logLevel, str); // } // return rtn; // } // // protected String _log(int logLevel, String str) { // if (logLevel >= LOG_ERROR) { // System.err.print(str); // } else { // System.out.print(str); // } // return str; // } // // protected String log(int logLevel, boolean addLineBreak, String str) { // String rtn = process(logLevel, str); // if (rtn != null) { // String sEnd = ""; // if (addLineBreak) { // sEnd = "\n"; // } // if (logLevel >= logRecordLevel) { // log += rtn + sEnd; // } // if (logLevel >= logOutputLevel) { // if (getTLogger().equals(this)) { // rtn = _log(logLevel, rtn + sEnd); // } else { // rtn = getTLogger().log(logLevel, addLineBreak, rtn); // } // // } // } // return rtn; // } // // protected String log(int logLevel, String str) { // return log(logLevel, true, str); // } // // protected String log(boolean addLineBreak, String str) { // return log(LOG_INFO, addLineBreak, str); // } // // protected String log(Exception e) { // e.printStackTrace(); // return log(LOG_ERROR, true, e.toString()); // } // // protected String log(String str) { // return log(LOG_INFO, true, str); // } // // protected String log(String str, Object obj) { // return log(str + U.toStr(obj)); // } // // protected String log(String str, Object... objs) { // return log(str + U.toStr(objs)); // } // // protected String log(Object obj) { // return log("", obj); // } // // protected String log(Object... objs) { // return log("", objs); // } // // } // // Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // Path: leotask/src/core/org/leores/math/Minimizer.java import java.util.Random; import java.util.Arrays; import java.util.Vector; import java.util.Hashtable; import org.leores.util.Logger; import org.leores.util.U; * of the target function */ private void order(double[][] simp, int[] worstNextBestArray) { int worst = 0, nextWorst = 0, best = 0; for (int i = 0; i < numVertices; i++) { if (value(simp[i]) < value(simp[best])) best = i; if (value(simp[i]) > value(simp[worst])) worst = i; } nextWorst = best; for (int i = 0; i < numVertices; i++) if (i != worst && value(simp[i]) > value(simp[nextWorst])) nextWorst = i; worstNextBestArray[WORST] = worst; worstNextBestArray[NEXT_WORST] = nextWorst; worstNextBestArray[BEST] = best; } //simplex [Iteration: s0(p1, p2....), s1(),....] private synchronized String sSimplex(double[][] simp) { String rtn = ""; for (int i = 0; i < numVertices; i++) rtn += sVertex(simp[i]) + " | "; return rtn; } private synchronized String sVertex(double[] vertex) { String rtn = ""; for (int j = 0; j < numParams; j++)
rtn += " " + U.valToStr(vertex[j], sPatNumOut);
mleoking/LeoTask
leotask/src/app/org/leores/demo/ObjUtilDemo.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // }
import java.io.File; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import org.leores.util.U;
public List<Double> discountHistory; protected static Integer nBook = 0; protected Book book; public Book() { } public Book(int id2, String name, double fullPrice, Double discount) { id = nBook; this.id2 = id2; this.name = name; this.fullPrice = fullPrice; this.discount = discount; nBook++; } public double getPrice() { return fullPrice * discount; } public void setPrice(Double price) {//here it has to be ``Double''. ``double'' does not work. discount = price / fullPrice; return; } public void setPrice(String sPrice) { setPrice(new Double(sPrice)); } public String info() {
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // Path: leotask/src/app/org/leores/demo/ObjUtilDemo.java import java.io.File; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import org.leores.util.U; public List<Double> discountHistory; protected static Integer nBook = 0; protected Book book; public Book() { } public Book(int id2, String name, double fullPrice, Double discount) { id = nBook; this.id2 = id2; this.name = name; this.fullPrice = fullPrice; this.discount = discount; nBook++; } public double getPrice() { return fullPrice * discount; } public void setPrice(Double price) {//here it has to be ``Double''. ``double'' does not work. discount = price / fullPrice; return; } public void setPrice(String sPrice) { setPrice(new Double(sPrice)); } public String info() {
return U.toStr(this) + U.toStr(book);
mleoking/LeoTask
leotask/src/core/org/leores/ecpt/TException.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // }
import org.leores.util.U;
package org.leores.ecpt; public class TException extends Exception { public TException() { super(); return; } public TException(Object obj) {
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // Path: leotask/src/core/org/leores/ecpt/TException.java import org.leores.util.U; package org.leores.ecpt; public class TException extends Exception { public TException() { super(); return; } public TException(Object obj) {
super(U.toStr(obj));
mleoking/LeoTask
leotask/src/core/org/leores/net/Networks.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.util.U; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1;
package org.leores.net; public class Networks extends Element { private static final long serialVersionUID = -4149150893833201437L; protected static Integer nNetworks = 0; protected List<Node> nodes; protected List<Network> networks; protected HashMap<Integer, Node> mId2ToNode;
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/net/Networks.java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.util.U; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1; package org.leores.net; public class Networks extends Element { private static final long serialVersionUID = -4149150893833201437L; protected static Integer nNetworks = 0; protected List<Node> nodes; protected List<Network> networks; protected HashMap<Integer, Node> mId2ToNode;
protected NewInstanceable<Node> nIaNode;
mleoking/LeoTask
leotask/src/core/org/leores/net/Networks.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.util.U; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1;
boolean bData = false; do { sLine = fReader.readLine(); if (sLine != null) { sLine = sLine.trim(); if (fileSection != null) { bData = true; } tokens = sLine.split(sDeRegex); if (tokens.length >= 1) { if ("NodeInfo".equals(tokens[0]) || "SubNetworks".equals(tokens[0])) { fileSection = tokens[0]; bData = false; } if (bData) { if ("NodeInfo".equals(fileSection)) { if (tokens.length >= 1) { Integer nid = Integer.parseInt(tokens[0]); Integer nid2 = null; String ninfo = null; if (tokens.length >= 2 && !"null".equals(tokens[1])) { nid2 = Integer.parseInt(tokens[1]); } if (tokens.length >= 3 && !"null".equals(tokens[2])) { ninfo = tokens[2]; } Node node = nets.getNode(nid); if (node != null) { node.initial(nid, nid2, ninfo); } else {
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/net/Networks.java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.util.U; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1; boolean bData = false; do { sLine = fReader.readLine(); if (sLine != null) { sLine = sLine.trim(); if (fileSection != null) { bData = true; } tokens = sLine.split(sDeRegex); if (tokens.length >= 1) { if ("NodeInfo".equals(tokens[0]) || "SubNetworks".equals(tokens[0])) { fileSection = tokens[0]; bData = false; } if (bData) { if ("NodeInfo".equals(fileSection)) { if (tokens.length >= 1) { Integer nid = Integer.parseInt(tokens[0]); Integer nid2 = null; String ninfo = null; if (tokens.length >= 2 && !"null".equals(tokens[1])) { nid2 = Integer.parseInt(tokens[1]); } if (tokens.length >= 3 && !"null".equals(tokens[2])) { ninfo = tokens[2]; } Node node = nets.getNode(nid); if (node != null) { node.initial(nid, nid2, ninfo); } else {
U.tLog("Error NodeInfo: node.id=" + nid + " does not exist!");
mleoking/LeoTask
leotask/src/core/org/leores/net/Networks.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.util.U; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1;
if (nNet > 0) { rtn = new Network(0, nNode, null, null, nIaNode, nIaLink); for (int i = 0; i < nNode; i++) { Node node = nodes.get(i); if (node != null) { Node nodeClone = node.newClone(); nodeClone.id2 = node.id;//has to set id2 here. as uniteInto will use id2 to get node when rtn.nets == null; rtn.addNode(nodeClone); } else { rtn.addNullNode(); } } for (int i = 0; i < nNet; i++) { Network net = getNetwork(i); if (net != null) { net.uniteInto(rtn, false); } } } return rtn; } public int nNetworks() { return networks.size(); }
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/NewInstanceable.java // public interface NewInstanceable<E> { // public E newInstance(); // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/core/org/leores/net/Networks.java import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.leores.util.U; import org.leores.util.able.NewInstanceable; import org.leores.util.able.Processable1; if (nNet > 0) { rtn = new Network(0, nNode, null, null, nIaNode, nIaLink); for (int i = 0; i < nNode; i++) { Node node = nodes.get(i); if (node != null) { Node nodeClone = node.newClone(); nodeClone.id2 = node.id;//has to set id2 here. as uniteInto will use id2 to get node when rtn.nets == null; rtn.addNode(nodeClone); } else { rtn.addNullNode(); } } for (int i = 0; i < nNet; i++) { Network net = getNetwork(i); if (net != null) { net.uniteInto(rtn, false); } } } return rtn; } public int nNetworks() { return networks.size(); }
public int nNetworks(Processable1<Boolean, Network> pa1) {
mleoking/LeoTask
leotask/src/core/org/leores/util/able/Processable1.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // }
import java.math.BigDecimal; import java.util.List; import org.leores.util.U;
package org.leores.util.able; public interface Processable1<R, A> { public R process(A a); public static class MaxListOutSize<A> implements Processable1<String, A> { protected Integer mSize;// null means do no limit list out size public MaxListOutSize(Integer mSize) { this.mSize = mSize; } public String process(A a) { String rtn = null;
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // Path: leotask/src/core/org/leores/util/able/Processable1.java import java.math.BigDecimal; import java.util.List; import org.leores.util.U; package org.leores.util.able; public interface Processable1<R, A> { public R process(A a); public static class MaxListOutSize<A> implements Processable1<String, A> { protected Integer mSize;// null means do no limit list out size public MaxListOutSize(Integer mSize) { this.mSize = mSize; } public String process(A a) { String rtn = null;
if (a != null && U.bAssignable(List.class, a.getClass())) {
mleoking/LeoTask
leotask/src/app/org/leores/demo/ProcessableDemo.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.util.Arrays; import java.util.List; import org.leores.util.U; import org.leores.util.able.Processable1;
package org.leores.demo; public class ProcessableDemo extends Demo { public void expression() { List<String> lData1 = Arrays.asList(new String[] { "1.234E5", "7.54E-9", "1.1E+5" }); List<Double> lData2 = Arrays.asList(new Double[] { 1E5, 1E-2, 1E+10 });
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/app/org/leores/demo/ProcessableDemo.java import java.util.Arrays; import java.util.List; import org.leores.util.U; import org.leores.util.able.Processable1; package org.leores.demo; public class ProcessableDemo extends Demo { public void expression() { List<String> lData1 = Arrays.asList(new String[] { "1.234E5", "7.54E-9", "1.1E+5" }); List<Double> lData2 = Arrays.asList(new Double[] { 1E5, 1E-2, 1E+10 });
Processable1 pa1 = new Processable1.Expression<String>("%/0.1");
mleoking/LeoTask
leotask/src/app/org/leores/demo/ProcessableDemo.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // }
import java.util.Arrays; import java.util.List; import org.leores.util.U; import org.leores.util.able.Processable1;
package org.leores.demo; public class ProcessableDemo extends Demo { public void expression() { List<String> lData1 = Arrays.asList(new String[] { "1.234E5", "7.54E-9", "1.1E+5" }); List<Double> lData2 = Arrays.asList(new Double[] { 1E5, 1E-2, 1E+10 }); Processable1 pa1 = new Processable1.Expression<String>("%/0.1"); Processable1 pa2 = new Processable1.Expression<Double>("%/0.01"); log("data1:" + lData1); log("data2:" + lData2);
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // // Path: leotask/src/core/org/leores/util/able/Processable1.java // public interface Processable1<R, A> { // public R process(A a); // // public static class MaxListOutSize<A> implements Processable1<String, A> { // protected Integer mSize;// null means do no limit list out size // // public MaxListOutSize(Integer mSize) { // this.mSize = mSize; // } // // public String process(A a) { // String rtn = null; // if (a != null && U.bAssignable(List.class, a.getClass())) { // List lObj = (List) a; // if (mSize != null && mSize >= 0 && mSize < lObj.size()) { // List lOut = lObj.subList(0, mSize); // rtn = lOut + "..."; // } else { // rtn = lObj + ""; // } // } // return rtn; // } // } // // public static class ArrayToString<A> implements Processable1<String, A> { // public String process(A a) { // String rtn = a + ""; // if (a != null && a instanceof Object[]) { // rtn = "["; // Object[] aa = (Object[]) a; // for (int i = 0; i < aa.length; i++) { // rtn += aa[i]; // if (i + 1 < aa.length) { // rtn += ","; // } // } // rtn += "]"; // } // return rtn; // } // } // // public static class Expression<A> implements Processable1<A, A> { // public String sElement, sExpression; // // public Expression(String sElement, String sExpression) { // this.sElement = sElement; // this.sExpression = sExpression; // } // // public Expression(String sExpression) { // this("%", sExpression); // } // // public A process(A a) { // A rtn = a; // if (a != null) { // String sExpToEval = sExpression.replace(sElement, a + ""); // BigDecimal bdEvalRtn = U.eval1Expression(sExpToEval); // if (bdEvalRtn != null) { // rtn = (A) U.newInstance(a.getClass(), bdEvalRtn + ""); // } else { // rtn = null; // } // } // return rtn; // } // // } // } // Path: leotask/src/app/org/leores/demo/ProcessableDemo.java import java.util.Arrays; import java.util.List; import org.leores.util.U; import org.leores.util.able.Processable1; package org.leores.demo; public class ProcessableDemo extends Demo { public void expression() { List<String> lData1 = Arrays.asList(new String[] { "1.234E5", "7.54E-9", "1.1E+5" }); List<Double> lData2 = Arrays.asList(new Double[] { 1E5, 1E-2, 1E+10 }); Processable1 pa1 = new Processable1.Expression<String>("%/0.1"); Processable1 pa2 = new Processable1.Expression<Double>("%/0.01"); log("data1:" + lData1); log("data2:" + lData2);
U.processElements(lData1,pa1);
mleoking/LeoTask
leotask/src/core/org/leores/util/ThreadWorkers.java
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/NextRunnable.java // public interface NextRunnable { // public Runnable nextRun(); // }
import org.leores.ecpt.WrongParameterException; import org.leores.util.able.NextRunnable;
package org.leores.util; public class ThreadWorkers extends Logger { public Integer nThreads;
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/NextRunnable.java // public interface NextRunnable { // public Runnable nextRun(); // } // Path: leotask/src/core/org/leores/util/ThreadWorkers.java import org.leores.ecpt.WrongParameterException; import org.leores.util.able.NextRunnable; package org.leores.util; public class ThreadWorkers extends Logger { public Integer nThreads;
public NextRunnable tNRunnable;
mleoking/LeoTask
leotask/src/core/org/leores/util/ThreadWorkers.java
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/NextRunnable.java // public interface NextRunnable { // public Runnable nextRun(); // }
import org.leores.ecpt.WrongParameterException; import org.leores.util.able.NextRunnable;
package org.leores.util; public class ThreadWorkers extends Logger { public Integer nThreads; public NextRunnable tNRunnable; public Thread[] threads; public Worker[] workers; public Integer nRun; public Integer nFinishedWorkers;
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // // Path: leotask/src/core/org/leores/util/able/NextRunnable.java // public interface NextRunnable { // public Runnable nextRun(); // } // Path: leotask/src/core/org/leores/util/ThreadWorkers.java import org.leores.ecpt.WrongParameterException; import org.leores.util.able.NextRunnable; package org.leores.util; public class ThreadWorkers extends Logger { public Integer nThreads; public NextRunnable tNRunnable; public Thread[] threads; public Worker[] workers; public Integer nRun; public Integer nFinishedWorkers;
public ThreadWorkers(Integer nTs, NextRunnable nR) throws WrongParameterException {
mleoking/LeoTask
leotask/src/core/org/leores/ecpt/TRuntimeException.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // }
import org.leores.util.U;
package org.leores.ecpt; public class TRuntimeException extends RuntimeException { private static final long serialVersionUID = -1540271937983801068L; public TRuntimeException() { super(); return; } public TRuntimeException(Object obj) {
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // Path: leotask/src/core/org/leores/ecpt/TRuntimeException.java import org.leores.util.U; package org.leores.ecpt; public class TRuntimeException extends RuntimeException { private static final long serialVersionUID = -1540271937983801068L; public TRuntimeException() { super(); return; } public TRuntimeException(Object obj) {
super(U.toStr(obj));
mleoking/LeoTask
leotask/src/core/org/leores/util/data/DataTableSet.java
// Path: leotask/src/core/org/leores/util/able/Processable2.java // public interface Processable2<R, A, B> { // public R process(A a, B b); // // public static class TrimStringField implements Processable2<Boolean, Object, Field> { // // public Boolean process(Object obj, Field field) { // boolean rtn = false; // if (field != null && U.bAssignable(String.class, field.getType())) { // String sValue = (String) U.getFieldValue(obj, field); // if (sValue != null) { // String sValue2 = sValue.trim(); // if (sValue2.length() < sValue.length()) { // rtn = true; // } // U.setFieldValue(obj, field, sValue2); // } // } // return rtn; // } // // } // // public static class SampleListByIndexB<B> implements Processable2<Boolean, Integer, B> { // public Integer step; // // /** // * The sample results will with these index: 0, 0+step, 0+2*step, ... // * // * @param step // */ // public SampleListByIndexB(Integer step) { // this.step = step; // } // // public Boolean process(Integer i, B b) { // return i % step == 0; // } // // } // // public static class SampleListByIndex<B> implements Processable2<B, Integer, B> { // public Integer step; // // /** // * The sample results will with these index: 0, 0+step, 0+2*step, ... // * // * @param step // */ // public SampleListByIndex(Integer step) { // this.step = step; // } // // public B process(Integer i, B b) { // B rtn = null; // if (i % step == 0) { // rtn = b; // } // return rtn; // } // } // // public static class RemoveRowWithInvalidNumber<B> implements Processable2<B[], Integer, B[]> { // public String sInvalid; // // /** // * E.g. "$%$<0" : remove rows with negative number. // * // * @param sInvalid // */ // public RemoveRowWithInvalidNumber(String sInvalid) { // this.sInvalid = sInvalid; // } // // public B[] process(Integer a, B[] b) { // B[] rtn = b; // for (int i = 0; i < b.length; i++) { // Double d = U.toDouble(b[i] + ""); // if (d != null) { // if (U.evalCheck(sInvalid, d)) { // rtn = null; // break; // } // } // } // return rtn; // } // }; // // }
import java.util.ArrayList; import java.util.List; import org.leores.util.able.Processable2;
public boolean add(DataTable dataTable) { boolean rtn = false; if (dataTable != null) { rtn = true; members.add(dataTable); } return rtn; } public boolean add(DataTable... dataTables) { boolean rtn = false; if (dataTables != null && dataTables.length > 0) { rtn = true; for (int i = 0; i < dataTables.length; i++) { if (!add(dataTables[i])) { rtn = false; break; } } } return rtn; } public DataTable addNewDataTable(String info, int nColumn) { DataTable rtn = new DataTable(info, nColumn); add(rtn); return rtn; }
// Path: leotask/src/core/org/leores/util/able/Processable2.java // public interface Processable2<R, A, B> { // public R process(A a, B b); // // public static class TrimStringField implements Processable2<Boolean, Object, Field> { // // public Boolean process(Object obj, Field field) { // boolean rtn = false; // if (field != null && U.bAssignable(String.class, field.getType())) { // String sValue = (String) U.getFieldValue(obj, field); // if (sValue != null) { // String sValue2 = sValue.trim(); // if (sValue2.length() < sValue.length()) { // rtn = true; // } // U.setFieldValue(obj, field, sValue2); // } // } // return rtn; // } // // } // // public static class SampleListByIndexB<B> implements Processable2<Boolean, Integer, B> { // public Integer step; // // /** // * The sample results will with these index: 0, 0+step, 0+2*step, ... // * // * @param step // */ // public SampleListByIndexB(Integer step) { // this.step = step; // } // // public Boolean process(Integer i, B b) { // return i % step == 0; // } // // } // // public static class SampleListByIndex<B> implements Processable2<B, Integer, B> { // public Integer step; // // /** // * The sample results will with these index: 0, 0+step, 0+2*step, ... // * // * @param step // */ // public SampleListByIndex(Integer step) { // this.step = step; // } // // public B process(Integer i, B b) { // B rtn = null; // if (i % step == 0) { // rtn = b; // } // return rtn; // } // } // // public static class RemoveRowWithInvalidNumber<B> implements Processable2<B[], Integer, B[]> { // public String sInvalid; // // /** // * E.g. "$%$<0" : remove rows with negative number. // * // * @param sInvalid // */ // public RemoveRowWithInvalidNumber(String sInvalid) { // this.sInvalid = sInvalid; // } // // public B[] process(Integer a, B[] b) { // B[] rtn = b; // for (int i = 0; i < b.length; i++) { // Double d = U.toDouble(b[i] + ""); // if (d != null) { // if (U.evalCheck(sInvalid, d)) { // rtn = null; // break; // } // } // } // return rtn; // } // }; // // } // Path: leotask/src/core/org/leores/util/data/DataTableSet.java import java.util.ArrayList; import java.util.List; import org.leores.util.able.Processable2; public boolean add(DataTable dataTable) { boolean rtn = false; if (dataTable != null) { rtn = true; members.add(dataTable); } return rtn; } public boolean add(DataTable... dataTables) { boolean rtn = false; if (dataTables != null && dataTables.length > 0) { rtn = true; for (int i = 0; i < dataTables.length; i++) { if (!add(dataTables[i])) { rtn = false; break; } } } return rtn; } public DataTable addNewDataTable(String info, int nColumn) { DataTable rtn = new DataTable(info, nColumn); add(rtn); return rtn; }
public <R, B> DataTable addNewDataTable(String info, boolean bAddUnEqualSizedList, Processable2<R, Integer, B> pa2Element, List<B>... lists) {
mleoking/LeoTask
leotask/src/core/org/leores/util/data/MaxMinAvg.java
// Path: leotask/src/core/org/leores/util/Logger.java // public class Logger { // protected final static int LOG_MAX = 100; // protected final static int LOG_CRITICAL = 80; // protected final static int LOG_ERROR = 70; // protected final static int LOG_WARNING = 60; // protected final static int LOG_INFO = 50; //default log level // protected final static int LOG_CASUAL = 40; // protected final static int LOG_TRIVIAL = 30; // protected final static int LOG_MIN = 0; // // protected String log = ""; // protected Integer logRecordLevel = LOG_MAX; // protected Integer logOutputLevel = LOG_MIN; // protected Processable2<String, Integer, String> logProcessor = null; // protected static Logger tLogger = new Logger(); // // public static void setTLogger(Logger logger) { // tLogger = logger; // } // // public static Logger getTLogger() { // return tLogger; // } // // public String getLog() { // return log; // } // // public void setLogProcessor(Processable2<String, Integer, String> logProcessor) { // this.logProcessor = logProcessor; // } // // public Integer getLogRecordLevel() { // return logRecordLevel; // } // // public void setLogRecordLevel(Integer logRecordLevel) { // this.logRecordLevel = logRecordLevel; // } // // public Integer getLogOutputLevel() { // return logOutputLevel; // } // // public void setLogOutputLevel(Integer logOutputLevel) { // this.logOutputLevel = logOutputLevel; // } // // protected String process(int logLevel, String str) { // String rtn = str; // if (logProcessor != null) { // rtn = logProcessor.process(logLevel, str); // } // return rtn; // } // // protected String _log(int logLevel, String str) { // if (logLevel >= LOG_ERROR) { // System.err.print(str); // } else { // System.out.print(str); // } // return str; // } // // protected String log(int logLevel, boolean addLineBreak, String str) { // String rtn = process(logLevel, str); // if (rtn != null) { // String sEnd = ""; // if (addLineBreak) { // sEnd = "\n"; // } // if (logLevel >= logRecordLevel) { // log += rtn + sEnd; // } // if (logLevel >= logOutputLevel) { // if (getTLogger().equals(this)) { // rtn = _log(logLevel, rtn + sEnd); // } else { // rtn = getTLogger().log(logLevel, addLineBreak, rtn); // } // // } // } // return rtn; // } // // protected String log(int logLevel, String str) { // return log(logLevel, true, str); // } // // protected String log(boolean addLineBreak, String str) { // return log(LOG_INFO, addLineBreak, str); // } // // protected String log(Exception e) { // e.printStackTrace(); // return log(LOG_ERROR, true, e.toString()); // } // // protected String log(String str) { // return log(LOG_INFO, true, str); // } // // protected String log(String str, Object obj) { // return log(str + U.toStr(obj)); // } // // protected String log(String str, Object... objs) { // return log(str + U.toStr(objs)); // } // // protected String log(Object obj) { // return log("", obj); // } // // protected String log(Object... objs) { // return log("", objs); // } // // } // // Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // }
import java.io.FileWriter; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.math.RoundingMode; import org.leores.util.Logger; import org.leores.util.U;
package org.leores.util.data; public class MaxMinAvg<D, V, P> extends Logger implements Serializable { private static final long serialVersionUID = -8843593173537608047L; public static class ValPar<V, P> implements Comparable<ValPar<V, P>>, Serializable { private static final long serialVersionUID = -6865012104095781653L; public Comparable<V> value; public P parameter; public static String sPatNumOut = null; public ValPar(Comparable<V> value, P parameter) { this.value = value; this.parameter = parameter; } public int compareTo(ValPar<V, P> o) { return value.compareTo((V) o.value); } public String toString() {
// Path: leotask/src/core/org/leores/util/Logger.java // public class Logger { // protected final static int LOG_MAX = 100; // protected final static int LOG_CRITICAL = 80; // protected final static int LOG_ERROR = 70; // protected final static int LOG_WARNING = 60; // protected final static int LOG_INFO = 50; //default log level // protected final static int LOG_CASUAL = 40; // protected final static int LOG_TRIVIAL = 30; // protected final static int LOG_MIN = 0; // // protected String log = ""; // protected Integer logRecordLevel = LOG_MAX; // protected Integer logOutputLevel = LOG_MIN; // protected Processable2<String, Integer, String> logProcessor = null; // protected static Logger tLogger = new Logger(); // // public static void setTLogger(Logger logger) { // tLogger = logger; // } // // public static Logger getTLogger() { // return tLogger; // } // // public String getLog() { // return log; // } // // public void setLogProcessor(Processable2<String, Integer, String> logProcessor) { // this.logProcessor = logProcessor; // } // // public Integer getLogRecordLevel() { // return logRecordLevel; // } // // public void setLogRecordLevel(Integer logRecordLevel) { // this.logRecordLevel = logRecordLevel; // } // // public Integer getLogOutputLevel() { // return logOutputLevel; // } // // public void setLogOutputLevel(Integer logOutputLevel) { // this.logOutputLevel = logOutputLevel; // } // // protected String process(int logLevel, String str) { // String rtn = str; // if (logProcessor != null) { // rtn = logProcessor.process(logLevel, str); // } // return rtn; // } // // protected String _log(int logLevel, String str) { // if (logLevel >= LOG_ERROR) { // System.err.print(str); // } else { // System.out.print(str); // } // return str; // } // // protected String log(int logLevel, boolean addLineBreak, String str) { // String rtn = process(logLevel, str); // if (rtn != null) { // String sEnd = ""; // if (addLineBreak) { // sEnd = "\n"; // } // if (logLevel >= logRecordLevel) { // log += rtn + sEnd; // } // if (logLevel >= logOutputLevel) { // if (getTLogger().equals(this)) { // rtn = _log(logLevel, rtn + sEnd); // } else { // rtn = getTLogger().log(logLevel, addLineBreak, rtn); // } // // } // } // return rtn; // } // // protected String log(int logLevel, String str) { // return log(logLevel, true, str); // } // // protected String log(boolean addLineBreak, String str) { // return log(LOG_INFO, addLineBreak, str); // } // // protected String log(Exception e) { // e.printStackTrace(); // return log(LOG_ERROR, true, e.toString()); // } // // protected String log(String str) { // return log(LOG_INFO, true, str); // } // // protected String log(String str, Object obj) { // return log(str + U.toStr(obj)); // } // // protected String log(String str, Object... objs) { // return log(str + U.toStr(objs)); // } // // protected String log(Object obj) { // return log("", obj); // } // // protected String log(Object... objs) { // return log("", objs); // } // // } // // Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // Path: leotask/src/core/org/leores/util/data/MaxMinAvg.java import java.io.FileWriter; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.math.RoundingMode; import org.leores.util.Logger; import org.leores.util.U; package org.leores.util.data; public class MaxMinAvg<D, V, P> extends Logger implements Serializable { private static final long serialVersionUID = -8843593173537608047L; public static class ValPar<V, P> implements Comparable<ValPar<V, P>>, Serializable { private static final long serialVersionUID = -6865012104095781653L; public Comparable<V> value; public P parameter; public static String sPatNumOut = null; public ValPar(Comparable<V> value, P parameter) { this.value = value; this.parameter = parameter; } public int compareTo(ValPar<V, P> o) { return value.compareTo((V) o.value); } public String toString() {
String sValue = U.valToStr(value, sPatNumOut);
mleoking/LeoTask
leotask/src/core/org/leores/util/able/Processable2.java
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // }
import java.lang.reflect.Field; import org.leores.util.U;
package org.leores.util.able; public interface Processable2<R, A, B> { public R process(A a, B b); public static class TrimStringField implements Processable2<Boolean, Object, Field> { public Boolean process(Object obj, Field field) { boolean rtn = false;
// Path: leotask/src/core/org/leores/util/U.java // public class U extends SerialUtil { // // } // Path: leotask/src/core/org/leores/util/able/Processable2.java import java.lang.reflect.Field; import org.leores.util.U; package org.leores.util.able; public interface Processable2<R, A, B> { public R process(A a, B b); public static class TrimStringField implements Processable2<Boolean, Object, Field> { public Boolean process(Object obj, Field field) { boolean rtn = false;
if (field != null && U.bAssignable(String.class, field.getType())) {
mleoking/LeoTask
leotask/src/core/org/leores/util/Variable.java
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // }
import java.io.Serializable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.lang.reflect.Method; import org.leores.ecpt.WrongParameterException;
package org.leores.util; public class Variable extends Logger implements Serializable { private static final long serialVersionUID = -8087990681997357462L; public String sField; public List values; public Integer iValue; @SuppressWarnings("all")
// Path: leotask/src/core/org/leores/ecpt/WrongParameterException.java // public class WrongParameterException extends TException { // public WrongParameterException(Object obj){ // super(obj); // return; // } // // public WrongParameterException(Object... objs) { // super(objs); // return; // } // // public WrongParameterException(String str, Object... objs) { // super(str, objs); // return; // } // } // Path: leotask/src/core/org/leores/util/Variable.java import java.io.Serializable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.lang.reflect.Method; import org.leores.ecpt.WrongParameterException; package org.leores.util; public class Variable extends Logger implements Serializable { private static final long serialVersionUID = -8087990681997357462L; public String sField; public List values; public Integer iValue; @SuppressWarnings("all")
public Variable(Class tClass, String name, String sValues) throws WrongParameterException {
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/EnableBasic.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/util/ProfileHelper.java // @Component // public class ProfileHelper implements ApplicationContextAware { // // private static ApplicationContext context = null; // // @Override // public void setApplicationContext(ApplicationContext applicationContext) // throws BeansException { // this.context = applicationContext; // } // // // 获取当前环境参数 exp: dev,prod,test // public static String getActiveProfile() { // String []profiles = context.getEnvironment().getActiveProfiles(); // if(ArrayUtils.isEmpty(profiles)){ // return profiles[0]; // } // return ""; // } // }
import com.jayqqaa12.jbase.spring.util.ProfileHelper; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.Import; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.lang.annotation.*;
package com.jayqqaa12.jbase.spring.boot; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/util/ProfileHelper.java // @Component // public class ProfileHelper implements ApplicationContextAware { // // private static ApplicationContext context = null; // // @Override // public void setApplicationContext(ApplicationContext applicationContext) // throws BeansException { // this.context = applicationContext; // } // // // 获取当前环境参数 exp: dev,prod,test // public static String getActiveProfile() { // String []profiles = context.getEnvironment().getActiveProfiles(); // if(ArrayUtils.isEmpty(profiles)){ // return profiles[0]; // } // return ""; // } // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/EnableBasic.java import com.jayqqaa12.jbase.spring.util.ProfileHelper; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.Import; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.lang.annotation.*; package com.jayqqaa12.jbase.spring.boot; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({
ProfileHelper.class ,
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCache.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.util.CacheException;
package com.jayqqaa12.jbase.cache.provider.caffeine; /** * @author jayqqaa12 */ public class CaffeineCache implements Cache { private com.github.benmanes.caffeine.cache.Cache<String, CacheObject> cache; public CaffeineCache(com.github.benmanes.caffeine.cache.Cache<String, CacheObject> loadingCache) { this.cache=loadingCache; } @Override
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCache.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.util.CacheException; package com.jayqqaa12.jbase.cache.provider.caffeine; /** * @author jayqqaa12 */ public class CaffeineCache implements Cache { private com.github.benmanes.caffeine.cache.Cache<String, CacheObject> cache; public CaffeineCache(com.github.benmanes.caffeine.cache.Cache<String, CacheObject> loadingCache) { this.cache=loadingCache; } @Override
public CacheObject get(String key) throws CacheException {
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/dubbo/DubboExceptionFilter.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // protected int code; // protected String msg; // // // public BusinessException(int code) { // this(code, LocaleKit.MSG_PREFIX + code, null); // } // // // public BusinessException(int code, String msg) { // super(msg); // this.code = code; // this.msg = msg; // } // // // public BusinessException(int code, String msg, Throwable e) { // // super(msg, e); // this.code = code; // this.msg = msg; // } // // public int getCode() { // return code; // } // // @Override // public String getMessage() { // // if (msg.startsWith(LocaleKit.MSG_PREFIX)) // return LocaleKit.resolverOrGet(this.code, this.msg); // else return msg; // } // }
import com.jayqqaa12.jbase.spring.exception.BusinessException; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.*; import org.apache.dubbo.rpc.service.GenericService; import java.lang.reflect.Method;
} public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { if (appResponse.hasException() && GenericService.class != invoker.getInterface()) { try { Throwable exception = appResponse.getException(); if (exception instanceof RuntimeException || !(exception instanceof Exception)) { try { Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); Class<?>[] exceptionClassses = method.getExceptionTypes(); Class[] var7 = exceptionClassses; int var8 = exceptionClassses.length; for (int var9 = 0; var9 < var8; ++var9) { Class<?> exceptionClass = var7[var9]; if (exception.getClass().equals(exceptionClass)) { return; } } } catch (NoSuchMethodException var11) { return; } this.logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); String exceptionFile = ReflectUtils.getCodeBase(exception.getClass()); if (serviceFile != null && exceptionFile != null && !serviceFile.equals(exceptionFile)) { String className = exception.getClass().getName(); if (!className.startsWith("java.") && !className.startsWith("javax.")) { if (!(exception instanceof RpcException)) {
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // protected int code; // protected String msg; // // // public BusinessException(int code) { // this(code, LocaleKit.MSG_PREFIX + code, null); // } // // // public BusinessException(int code, String msg) { // super(msg); // this.code = code; // this.msg = msg; // } // // // public BusinessException(int code, String msg, Throwable e) { // // super(msg, e); // this.code = code; // this.msg = msg; // } // // public int getCode() { // return code; // } // // @Override // public String getMessage() { // // if (msg.startsWith(LocaleKit.MSG_PREFIX)) // return LocaleKit.resolverOrGet(this.code, this.msg); // else return msg; // } // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/dubbo/DubboExceptionFilter.java import com.jayqqaa12.jbase.spring.exception.BusinessException; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.*; import org.apache.dubbo.rpc.service.GenericService; import java.lang.reflect.Method; } public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { if (appResponse.hasException() && GenericService.class != invoker.getInterface()) { try { Throwable exception = appResponse.getException(); if (exception instanceof RuntimeException || !(exception instanceof Exception)) { try { Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); Class<?>[] exceptionClassses = method.getExceptionTypes(); Class[] var7 = exceptionClassses; int var8 = exceptionClassses.length; for (int var9 = 0; var9 < var8; ++var9) { Class<?> exceptionClass = var7[var9]; if (exception.getClass().equals(exceptionClass)) { return; } } } catch (NoSuchMethodException var11) { return; } this.logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); String exceptionFile = ReflectUtils.getCodeBase(exception.getClass()); if (serviceFile != null && exceptionFile != null && !serviceFile.equals(exceptionFile)) { String className = exception.getClass().getName(); if (!className.startsWith("java.") && !className.startsWith("javax.")) { if (!(exception instanceof RpcException)) {
if (exception instanceof BusinessException) {
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/db/MapWrapperFactory.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/db/CustomWrapper.java // public class CustomWrapper extends MapWrapper { // // // public CustomWrapper(MetaObject metaObject, Map<String, Object> map) { // super(metaObject, map); // } // // @Override // public String findProperty(String name, boolean useCamelCaseMapping) { // if(useCamelCaseMapping){ // return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,name); // } // return name; // } // }
import com.jayqqaa12.jbase.spring.db.CustomWrapper; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.wrapper.ObjectWrapper; import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory; import java.util.Map;
package com.jayqqaa12.jbase.spring.db; public class MapWrapperFactory implements ObjectWrapperFactory { @Override public boolean hasWrapperFor(Object object) { return object != null && object instanceof Map; } @Override public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/db/CustomWrapper.java // public class CustomWrapper extends MapWrapper { // // // public CustomWrapper(MetaObject metaObject, Map<String, Object> map) { // super(metaObject, map); // } // // @Override // public String findProperty(String name, boolean useCamelCaseMapping) { // if(useCamelCaseMapping){ // return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,name); // } // return name; // } // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/db/MapWrapperFactory.java import com.jayqqaa12.jbase.spring.db.CustomWrapper; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.wrapper.ObjectWrapper; import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory; import java.util.Map; package com.jayqqaa12.jbase.spring.db; public class MapWrapperFactory implements ObjectWrapperFactory { @Override public boolean hasWrapperFor(Object object) { return object != null && object instanceof Map; } @Override public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
return new CustomWrapper(metaObject,(Map)object);
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/RestConfig.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // protected int code; // protected String msg; // // // public BusinessException(int code) { // this(code, LocaleKit.MSG_PREFIX + code, null); // } // // // public BusinessException(int code, String msg) { // super(msg); // this.code = code; // this.msg = msg; // } // // // public BusinessException(int code, String msg, Throwable e) { // // super(msg, e); // this.code = code; // this.msg = msg; // } // // public int getCode() { // return code; // } // // @Override // public String getMessage() { // // if (msg.startsWith(LocaleKit.MSG_PREFIX)) // return LocaleKit.resolverOrGet(this.code, this.msg); // else return msg; // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java // @Data // public class Resp { // private int code; // String msg; // private Object data; // // // public Resp(){ // } // // private Resp(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public static Resp response(int code) { // return new Resp(code, LocaleKit.resolverOrGet(code, null)); // } // // public static Resp response(int code, String msg) { // return new Resp(code, LocaleKit.resolverOrGet(code, msg)); // } // // // public static Resp success() { // return Resp.response(RespCode.SUCCESS ); // } // // // public static Resp error() { // return Resp.response(RespCode.SERVER_ERROR ); // } // // public static Resp error(String msg) { // return new Resp(RespCode.SERVER_ERROR, LocaleKit.resolverOrGet(RespCode.SERVER_ERROR, msg)); // } // // // // // // }
import com.alibaba.fastjson.JSON; import com.jayqqaa12.jbase.spring.exception.BusinessException; import com.jayqqaa12.jbase.spring.mvc.Resp; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.io.IOException;
package com.jayqqaa12.jbase.spring.feign; /** * 跟dubbo有冲突 */ @Configurable public class RestConfig { @Bean @LoadBalanced public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new CustomResponseError()); return restTemplate; } public class CustomResponseError extends DefaultResponseErrorHandler { @Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = getHttpStatusCode(response); switch (statusCode.series()) { case CLIENT_ERROR: throw new HttpClientErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); case SERVER_ERROR:
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // protected int code; // protected String msg; // // // public BusinessException(int code) { // this(code, LocaleKit.MSG_PREFIX + code, null); // } // // // public BusinessException(int code, String msg) { // super(msg); // this.code = code; // this.msg = msg; // } // // // public BusinessException(int code, String msg, Throwable e) { // // super(msg, e); // this.code = code; // this.msg = msg; // } // // public int getCode() { // return code; // } // // @Override // public String getMessage() { // // if (msg.startsWith(LocaleKit.MSG_PREFIX)) // return LocaleKit.resolverOrGet(this.code, this.msg); // else return msg; // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java // @Data // public class Resp { // private int code; // String msg; // private Object data; // // // public Resp(){ // } // // private Resp(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public static Resp response(int code) { // return new Resp(code, LocaleKit.resolverOrGet(code, null)); // } // // public static Resp response(int code, String msg) { // return new Resp(code, LocaleKit.resolverOrGet(code, msg)); // } // // // public static Resp success() { // return Resp.response(RespCode.SUCCESS ); // } // // // public static Resp error() { // return Resp.response(RespCode.SERVER_ERROR ); // } // // public static Resp error(String msg) { // return new Resp(RespCode.SERVER_ERROR, LocaleKit.resolverOrGet(RespCode.SERVER_ERROR, msg)); // } // // // // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/RestConfig.java import com.alibaba.fastjson.JSON; import com.jayqqaa12.jbase.spring.exception.BusinessException; import com.jayqqaa12.jbase.spring.mvc.Resp; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.io.IOException; package com.jayqqaa12.jbase.spring.feign; /** * 跟dubbo有冲突 */ @Configurable public class RestConfig { @Bean @LoadBalanced public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new CustomResponseError()); return restTemplate; } public class CustomResponseError extends DefaultResponseErrorHandler { @Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = getHttpStatusCode(response); switch (statusCode.series()) { case CLIENT_ERROR: throw new HttpClientErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); case SERVER_ERROR:
Resp req = JSON.parseObject(getResponseBody(response), Resp.class);
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/RestConfig.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // protected int code; // protected String msg; // // // public BusinessException(int code) { // this(code, LocaleKit.MSG_PREFIX + code, null); // } // // // public BusinessException(int code, String msg) { // super(msg); // this.code = code; // this.msg = msg; // } // // // public BusinessException(int code, String msg, Throwable e) { // // super(msg, e); // this.code = code; // this.msg = msg; // } // // public int getCode() { // return code; // } // // @Override // public String getMessage() { // // if (msg.startsWith(LocaleKit.MSG_PREFIX)) // return LocaleKit.resolverOrGet(this.code, this.msg); // else return msg; // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java // @Data // public class Resp { // private int code; // String msg; // private Object data; // // // public Resp(){ // } // // private Resp(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public static Resp response(int code) { // return new Resp(code, LocaleKit.resolverOrGet(code, null)); // } // // public static Resp response(int code, String msg) { // return new Resp(code, LocaleKit.resolverOrGet(code, msg)); // } // // // public static Resp success() { // return Resp.response(RespCode.SUCCESS ); // } // // // public static Resp error() { // return Resp.response(RespCode.SERVER_ERROR ); // } // // public static Resp error(String msg) { // return new Resp(RespCode.SERVER_ERROR, LocaleKit.resolverOrGet(RespCode.SERVER_ERROR, msg)); // } // // // // // // }
import com.alibaba.fastjson.JSON; import com.jayqqaa12.jbase.spring.exception.BusinessException; import com.jayqqaa12.jbase.spring.mvc.Resp; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.io.IOException;
package com.jayqqaa12.jbase.spring.feign; /** * 跟dubbo有冲突 */ @Configurable public class RestConfig { @Bean @LoadBalanced public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new CustomResponseError()); return restTemplate; } public class CustomResponseError extends DefaultResponseErrorHandler { @Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = getHttpStatusCode(response); switch (statusCode.series()) { case CLIENT_ERROR: throw new HttpClientErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); case SERVER_ERROR: Resp req = JSON.parseObject(getResponseBody(response), Resp.class);
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/exception/BusinessException.java // public class BusinessException extends RuntimeException { // // protected int code; // protected String msg; // // // public BusinessException(int code) { // this(code, LocaleKit.MSG_PREFIX + code, null); // } // // // public BusinessException(int code, String msg) { // super(msg); // this.code = code; // this.msg = msg; // } // // // public BusinessException(int code, String msg, Throwable e) { // // super(msg, e); // this.code = code; // this.msg = msg; // } // // public int getCode() { // return code; // } // // @Override // public String getMessage() { // // if (msg.startsWith(LocaleKit.MSG_PREFIX)) // return LocaleKit.resolverOrGet(this.code, this.msg); // else return msg; // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java // @Data // public class Resp { // private int code; // String msg; // private Object data; // // // public Resp(){ // } // // private Resp(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public static Resp response(int code) { // return new Resp(code, LocaleKit.resolverOrGet(code, null)); // } // // public static Resp response(int code, String msg) { // return new Resp(code, LocaleKit.resolverOrGet(code, msg)); // } // // // public static Resp success() { // return Resp.response(RespCode.SUCCESS ); // } // // // public static Resp error() { // return Resp.response(RespCode.SERVER_ERROR ); // } // // public static Resp error(String msg) { // return new Resp(RespCode.SERVER_ERROR, LocaleKit.resolverOrGet(RespCode.SERVER_ERROR, msg)); // } // // // // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/RestConfig.java import com.alibaba.fastjson.JSON; import com.jayqqaa12.jbase.spring.exception.BusinessException; import com.jayqqaa12.jbase.spring.mvc.Resp; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.DefaultResponseErrorHandler; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import java.io.IOException; package com.jayqqaa12.jbase.spring.feign; /** * 跟dubbo有冲突 */ @Configurable public class RestConfig { @Bean @LoadBalanced public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new CustomResponseError()); return restTemplate; } public class CustomResponseError extends DefaultResponseErrorHandler { @Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus statusCode = getHttpStatusCode(response); switch (statusCode.series()) { case CLIENT_ERROR: throw new HttpClientErrorException(statusCode, response.getStatusText(), response.getHeaders(), getResponseBody(response), getCharset(response)); case SERVER_ERROR: Resp req = JSON.parseObject(getResponseBody(response), Resp.class);
throw new BusinessException(req.getCode(),req.getMsg(),null);
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCacheProvider.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConst.java // public static final String REDIS_MODE_CLUSTER="cluster"; // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import static com.jayqqaa12.jbase.cache.core.CacheConst.REDIS_MODE_CLUSTER; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import io.lettuce.core.AbstractRedisClient; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulConnection; import io.lettuce.core.cluster.ClusterClientOptions; import io.lettuce.core.cluster.ClusterTopologyRefreshOptions; import io.lettuce.core.cluster.RedisClusterClient; import io.lettuce.core.support.ConnectionPoolSupport; import lombok.extern.slf4j.Slf4j; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap;
package com.jayqqaa12.jbase.cache.provider.lettuce; /** * @author jayqqaa12 */ @Slf4j public class LettuceCacheProvider implements CacheProvider { private static AbstractRedisClient redisClient; private GenericObjectPool<StatefulConnection<String, byte[]>> pool; private LettuceByteCodec codec = new LettuceByteCodec();
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConst.java // public static final String REDIS_MODE_CLUSTER="cluster"; // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCacheProvider.java import static com.jayqqaa12.jbase.cache.core.CacheConst.REDIS_MODE_CLUSTER; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import io.lettuce.core.AbstractRedisClient; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulConnection; import io.lettuce.core.cluster.ClusterClientOptions; import io.lettuce.core.cluster.ClusterTopologyRefreshOptions; import io.lettuce.core.cluster.RedisClusterClient; import io.lettuce.core.support.ConnectionPoolSupport; import lombok.extern.slf4j.Slf4j; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; package com.jayqqaa12.jbase.cache.provider.lettuce; /** * @author jayqqaa12 */ @Slf4j public class LettuceCacheProvider implements CacheProvider { private static AbstractRedisClient redisClient; private GenericObjectPool<StatefulConnection<String, byte[]>> pool; private LettuceByteCodec codec = new LettuceByteCodec();
private final ConcurrentHashMap<String, Cache> regions = new ConcurrentHashMap<>();
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCacheProvider.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConst.java // public static final String REDIS_MODE_CLUSTER="cluster"; // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import static com.jayqqaa12.jbase.cache.core.CacheConst.REDIS_MODE_CLUSTER; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import io.lettuce.core.AbstractRedisClient; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulConnection; import io.lettuce.core.cluster.ClusterClientOptions; import io.lettuce.core.cluster.ClusterTopologyRefreshOptions; import io.lettuce.core.cluster.RedisClusterClient; import io.lettuce.core.support.ConnectionPoolSupport; import lombok.extern.slf4j.Slf4j; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap;
package com.jayqqaa12.jbase.cache.provider.lettuce; /** * @author jayqqaa12 */ @Slf4j public class LettuceCacheProvider implements CacheProvider { private static AbstractRedisClient redisClient; private GenericObjectPool<StatefulConnection<String, byte[]>> pool; private LettuceByteCodec codec = new LettuceByteCodec(); private final ConcurrentHashMap<String, Cache> regions = new ConcurrentHashMap<>();
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConst.java // public static final String REDIS_MODE_CLUSTER="cluster"; // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCacheProvider.java import static com.jayqqaa12.jbase.cache.core.CacheConst.REDIS_MODE_CLUSTER; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import io.lettuce.core.AbstractRedisClient; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulConnection; import io.lettuce.core.cluster.ClusterClientOptions; import io.lettuce.core.cluster.ClusterTopologyRefreshOptions; import io.lettuce.core.cluster.RedisClusterClient; import io.lettuce.core.support.ConnectionPoolSupport; import lombok.extern.slf4j.Slf4j; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; package com.jayqqaa12.jbase.cache.provider.lettuce; /** * @author jayqqaa12 */ @Slf4j public class LettuceCacheProvider implements CacheProvider { private static AbstractRedisClient redisClient; private GenericObjectPool<StatefulConnection<String, byte[]>> pool; private LettuceByteCodec codec = new LettuceByteCodec(); private final ConcurrentHashMap<String, Cache> regions = new ConcurrentHashMap<>();
private CacheConfig cacheConfig;
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/load/AutoLoadObject.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConst.java // public static final int REFRESH_MIN_TIME=60;
import static com.jayqqaa12.jbase.cache.core.CacheConst.REFRESH_MIN_TIME; import lombok.Builder; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.util.function.Supplier;
package com.jayqqaa12.jbase.cache.core.load; @Data @Builder @Slf4j public class AutoLoadObject { private String region; private String key; //主动传入的加载方法 private Supplier<Object> function; /** * 过期时长 单位:秒 */ private int expire; private volatile boolean isLock; /** * 最后更新时间 */ private volatile Long lastUpdateTime; /** * 最后一次请求时间 如果没有请求就不刷新缓存 */ private volatile Long lastRequestTime; /** * 判断是否可用自动加载 没有请求或者过期时间太短的都不行 * <p> * 并且要快到过期时间了(9/10)才刷新 */ public boolean canAutoLoad() { return !isLock
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConst.java // public static final int REFRESH_MIN_TIME=60; // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/load/AutoLoadObject.java import static com.jayqqaa12.jbase.cache.core.CacheConst.REFRESH_MIN_TIME; import lombok.Builder; import lombok.Data; import lombok.extern.slf4j.Slf4j; import java.util.function.Supplier; package com.jayqqaa12.jbase.cache.core.load; @Data @Builder @Slf4j public class AutoLoadObject { private String region; private String key; //主动传入的加载方法 private Supplier<Object> function; /** * 过期时长 单位:秒 */ private int expire; private volatile boolean isLock; /** * 最后更新时间 */ private volatile Long lastUpdateTime; /** * 最后一次请求时间 如果没有请求就不刷新缓存 */ private volatile Long lastRequestTime; /** * 判断是否可用自动加载 没有请求或者过期时间太短的都不行 * <p> * 并且要快到过期时间了(9/10)才刷新 */ public boolean canAutoLoad() { return !isLock
&& expire > REFRESH_MIN_TIME
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProviderGroup.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.util.CacheException; import lombok.Data; import java.util.ArrayList; import java.util.List;
package com.jayqqaa12.jbase.cache.provider; public class CacheProviderGroup { private final static int LEVEL1 = 0; private final static int LEVEL2 = 1; private List<CacheProvider> cacheProviders = new ArrayList<>();
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProviderGroup.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.util.CacheException; import lombok.Data; import java.util.ArrayList; import java.util.List; package com.jayqqaa12.jbase.cache.provider; public class CacheProviderGroup { private final static int LEVEL1 = 0; private final static int LEVEL2 = 1; private List<CacheProvider> cacheProviders = new ArrayList<>();
public CacheProviderGroup(CacheConfig cacheConfig) {
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProviderGroup.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.util.CacheException; import lombok.Data; import java.util.ArrayList; import java.util.List;
package com.jayqqaa12.jbase.cache.provider; public class CacheProviderGroup { private final static int LEVEL1 = 0; private final static int LEVEL2 = 1; private List<CacheProvider> cacheProviders = new ArrayList<>(); public CacheProviderGroup(CacheConfig cacheConfig) { if (cacheConfig.getProviderClassList().isEmpty()) { throw new IllegalArgumentException("cache providers can't null"); } for (String provider : cacheConfig.getProviderClassList()) { CacheProvider cacheProvider = null; try { cacheProvider = (CacheProvider) Class.forName(provider).newInstance(); } catch (Exception e) {
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProviderGroup.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.util.CacheException; import lombok.Data; import java.util.ArrayList; import java.util.List; package com.jayqqaa12.jbase.cache.provider; public class CacheProviderGroup { private final static int LEVEL1 = 0; private final static int LEVEL2 = 1; private List<CacheProvider> cacheProviders = new ArrayList<>(); public CacheProviderGroup(CacheConfig cacheConfig) { if (cacheConfig.getProviderClassList().isEmpty()) { throw new IllegalArgumentException("cache providers can't null"); } for (String provider : cacheConfig.getProviderClassList()) { CacheProvider cacheProvider = null; try { cacheProvider = (CacheProvider) Class.forName(provider).newInstance(); } catch (Exception e) {
throw new CacheException("nonexistent cache providers class");
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProviderGroup.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.util.CacheException; import lombok.Data; import java.util.ArrayList; import java.util.List;
package com.jayqqaa12.jbase.cache.provider; public class CacheProviderGroup { private final static int LEVEL1 = 0; private final static int LEVEL2 = 1; private List<CacheProvider> cacheProviders = new ArrayList<>(); public CacheProviderGroup(CacheConfig cacheConfig) { if (cacheConfig.getProviderClassList().isEmpty()) { throw new IllegalArgumentException("cache providers can't null"); } for (String provider : cacheConfig.getProviderClassList()) { CacheProvider cacheProvider = null; try { cacheProvider = (CacheProvider) Class.forName(provider).newInstance(); } catch (Exception e) { throw new CacheException("nonexistent cache providers class"); } cacheProvider.init(cacheConfig); this.cacheProviders.add(cacheProvider); } }
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProviderGroup.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.util.CacheException; import lombok.Data; import java.util.ArrayList; import java.util.List; package com.jayqqaa12.jbase.cache.provider; public class CacheProviderGroup { private final static int LEVEL1 = 0; private final static int LEVEL2 = 1; private List<CacheProvider> cacheProviders = new ArrayList<>(); public CacheProviderGroup(CacheConfig cacheConfig) { if (cacheConfig.getProviderClassList().isEmpty()) { throw new IllegalArgumentException("cache providers can't null"); } for (String provider : cacheConfig.getProviderClassList()) { CacheProvider cacheProvider = null; try { cacheProvider = (CacheProvider) Class.forName(provider).newInstance(); } catch (Exception e) { throw new CacheException("nonexistent cache providers class"); } cacheProvider.init(cacheConfig); this.cacheProviders.add(cacheProvider); } }
public Cache getLevel1Provider(String region) {
jayqqaa12/jbase
jbase-cache/src/test/java/com/jayqqaa12/jbase/cache/core/LettuceTest.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java // public class NullCacheProvider implements CacheProvider { // // private static final NullCache cache=new NullCache(); // // @Override // public void init(CacheConfig cacheConfig) { // } // @Override // public Cache buildCache(String region, int expire) { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) { // return cache; // } // // @Override // public void stop() { // // } // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCacheProvider.java // @Slf4j // public class LettuceCacheProvider implements CacheProvider { // // private static AbstractRedisClient redisClient; // private GenericObjectPool<StatefulConnection<String, byte[]>> pool; // // private LettuceByteCodec codec = new LettuceByteCodec(); // // private final ConcurrentHashMap<String, Cache> regions = new ConcurrentHashMap<>(); // private CacheConfig cacheConfig; // // @Override // public void init(CacheConfig cacheConfig) { // this.cacheConfig = cacheConfig; // // String hosts = cacheConfig.getLettuceConfig().getHosts(); // // int database = cacheConfig.getLettuceConfig().getDatabase(); // String password = cacheConfig.getLettuceConfig().getPassword(); // // int clusterTopologyRefresh = cacheConfig.getLettuceConfig().getClusterTopologyRefresh(); // // if (REDIS_MODE_CLUSTER.equalsIgnoreCase(cacheConfig.getLettuceConfig().getSchema())) { // List<RedisURI> redisURIs = new ArrayList<>(); // String[] hostArray = hosts.split(","); // for (String host : hostArray) { // String[] redisArray = host.split(":"); // RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1])); // uri.setDatabase(database); // uri.setPassword(password); // // uri.setSentinelMasterId(sentinelMasterId); // redisURIs.add(uri); // } // redisClient = RedisClusterClient.create(redisURIs); // ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder() // //开启自适应刷新 // .enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT, // ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS) // .enableAllAdaptiveRefreshTriggers() // .adaptiveRefreshTriggersTimeout(Duration.ofMillis(clusterTopologyRefresh)) // //开启定时刷新,时间间隔根据实际情况修改 // .enablePeriodicRefresh(Duration.ofMillis(clusterTopologyRefresh)) // .build(); // ((RedisClusterClient) redisClient).setOptions( // ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); // } else { // String[] redisArray = hosts.split(":"); // RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1])); // uri.setDatabase(database); // uri.setPassword(password); // redisClient = RedisClient.create(uri); // } // // try { // redisClient.setDefaultTimeout(Duration.ofMillis(cacheConfig.getLettuceConfig().getTimeout())); // } catch (Exception e) { // log.warn("Failed to set default timeout, using default 10000 milliseconds.", e); // } // // //connection pool configurations // GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); // poolConfig.setMaxTotal(cacheConfig.getLettuceConfig().getMaxTotal()); // poolConfig.setMaxIdle(cacheConfig.getLettuceConfig().getMaxIdle()); // poolConfig.setMinIdle(cacheConfig.getLettuceConfig().getMinIdle()); // // pool = ConnectionPoolSupport.createGenericObjectPool(() -> { // if (redisClient instanceof RedisClient) { // return ((RedisClient) redisClient).connect(codec); // } else if (redisClient instanceof RedisClusterClient) { // return ((RedisClusterClient) redisClient).connect(codec); // } // return null; // }, poolConfig); // // } // // @Override // public Cache buildCache(String region, int expire) throws CacheException { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) throws CacheException { // // try { // // CacheSerializer cacheSerializer = (CacheSerializer) Class // .forName(cacheConfig.getCacheSerializerClass()).newInstance(); // String namespace = this.cacheConfig.getLettuceConfig().getNamespace(); // // return regions // .computeIfAbsent(namespace + ":" + region, // k -> new LettuceCache(cacheSerializer, namespace, region, pool)); // }catch (Exception e){ // throw new CacheException(e); // } // // } // // @Override // public void stop() { // // pool.close(); // regions.clear(); // redisClient.shutdown(); // // } // }
import static org.junit.Assert.assertEquals; import com.google.common.collect.Lists; import com.jayqqaa12.jbase.cache.provider.NullCacheProvider; import com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import redis.embedded.RedisServer; import java.util.concurrent.TimeUnit;
package com.jayqqaa12.jbase.cache.core; /** * @author 12, {@literal <shuai.wang@leyantech.com>} * @date 2020-10-12. */ public class LettuceTest { private static JbaseCache jbaseCache; private static RedisServer redisServer; @BeforeClass public static void init() { redisServer = RedisServer.builder() .port(7777) .setting("bind localhost") .build() ; CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setProviderClassList(
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java // public class NullCacheProvider implements CacheProvider { // // private static final NullCache cache=new NullCache(); // // @Override // public void init(CacheConfig cacheConfig) { // } // @Override // public Cache buildCache(String region, int expire) { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) { // return cache; // } // // @Override // public void stop() { // // } // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCacheProvider.java // @Slf4j // public class LettuceCacheProvider implements CacheProvider { // // private static AbstractRedisClient redisClient; // private GenericObjectPool<StatefulConnection<String, byte[]>> pool; // // private LettuceByteCodec codec = new LettuceByteCodec(); // // private final ConcurrentHashMap<String, Cache> regions = new ConcurrentHashMap<>(); // private CacheConfig cacheConfig; // // @Override // public void init(CacheConfig cacheConfig) { // this.cacheConfig = cacheConfig; // // String hosts = cacheConfig.getLettuceConfig().getHosts(); // // int database = cacheConfig.getLettuceConfig().getDatabase(); // String password = cacheConfig.getLettuceConfig().getPassword(); // // int clusterTopologyRefresh = cacheConfig.getLettuceConfig().getClusterTopologyRefresh(); // // if (REDIS_MODE_CLUSTER.equalsIgnoreCase(cacheConfig.getLettuceConfig().getSchema())) { // List<RedisURI> redisURIs = new ArrayList<>(); // String[] hostArray = hosts.split(","); // for (String host : hostArray) { // String[] redisArray = host.split(":"); // RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1])); // uri.setDatabase(database); // uri.setPassword(password); // // uri.setSentinelMasterId(sentinelMasterId); // redisURIs.add(uri); // } // redisClient = RedisClusterClient.create(redisURIs); // ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder() // //开启自适应刷新 // .enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT, // ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS) // .enableAllAdaptiveRefreshTriggers() // .adaptiveRefreshTriggersTimeout(Duration.ofMillis(clusterTopologyRefresh)) // //开启定时刷新,时间间隔根据实际情况修改 // .enablePeriodicRefresh(Duration.ofMillis(clusterTopologyRefresh)) // .build(); // ((RedisClusterClient) redisClient).setOptions( // ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); // } else { // String[] redisArray = hosts.split(":"); // RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1])); // uri.setDatabase(database); // uri.setPassword(password); // redisClient = RedisClient.create(uri); // } // // try { // redisClient.setDefaultTimeout(Duration.ofMillis(cacheConfig.getLettuceConfig().getTimeout())); // } catch (Exception e) { // log.warn("Failed to set default timeout, using default 10000 milliseconds.", e); // } // // //connection pool configurations // GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); // poolConfig.setMaxTotal(cacheConfig.getLettuceConfig().getMaxTotal()); // poolConfig.setMaxIdle(cacheConfig.getLettuceConfig().getMaxIdle()); // poolConfig.setMinIdle(cacheConfig.getLettuceConfig().getMinIdle()); // // pool = ConnectionPoolSupport.createGenericObjectPool(() -> { // if (redisClient instanceof RedisClient) { // return ((RedisClient) redisClient).connect(codec); // } else if (redisClient instanceof RedisClusterClient) { // return ((RedisClusterClient) redisClient).connect(codec); // } // return null; // }, poolConfig); // // } // // @Override // public Cache buildCache(String region, int expire) throws CacheException { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) throws CacheException { // // try { // // CacheSerializer cacheSerializer = (CacheSerializer) Class // .forName(cacheConfig.getCacheSerializerClass()).newInstance(); // String namespace = this.cacheConfig.getLettuceConfig().getNamespace(); // // return regions // .computeIfAbsent(namespace + ":" + region, // k -> new LettuceCache(cacheSerializer, namespace, region, pool)); // }catch (Exception e){ // throw new CacheException(e); // } // // } // // @Override // public void stop() { // // pool.close(); // regions.clear(); // redisClient.shutdown(); // // } // } // Path: jbase-cache/src/test/java/com/jayqqaa12/jbase/cache/core/LettuceTest.java import static org.junit.Assert.assertEquals; import com.google.common.collect.Lists; import com.jayqqaa12.jbase.cache.provider.NullCacheProvider; import com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import redis.embedded.RedisServer; import java.util.concurrent.TimeUnit; package com.jayqqaa12.jbase.cache.core; /** * @author 12, {@literal <shuai.wang@leyantech.com>} * @date 2020-10-12. */ public class LettuceTest { private static JbaseCache jbaseCache; private static RedisServer redisServer; @BeforeClass public static void init() { redisServer = RedisServer.builder() .port(7777) .setting("bind localhost") .build() ; CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setProviderClassList(
Lists.newArrayList(NullCacheProvider.class.getName(),
jayqqaa12/jbase
jbase-cache/src/test/java/com/jayqqaa12/jbase/cache/core/LettuceTest.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java // public class NullCacheProvider implements CacheProvider { // // private static final NullCache cache=new NullCache(); // // @Override // public void init(CacheConfig cacheConfig) { // } // @Override // public Cache buildCache(String region, int expire) { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) { // return cache; // } // // @Override // public void stop() { // // } // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCacheProvider.java // @Slf4j // public class LettuceCacheProvider implements CacheProvider { // // private static AbstractRedisClient redisClient; // private GenericObjectPool<StatefulConnection<String, byte[]>> pool; // // private LettuceByteCodec codec = new LettuceByteCodec(); // // private final ConcurrentHashMap<String, Cache> regions = new ConcurrentHashMap<>(); // private CacheConfig cacheConfig; // // @Override // public void init(CacheConfig cacheConfig) { // this.cacheConfig = cacheConfig; // // String hosts = cacheConfig.getLettuceConfig().getHosts(); // // int database = cacheConfig.getLettuceConfig().getDatabase(); // String password = cacheConfig.getLettuceConfig().getPassword(); // // int clusterTopologyRefresh = cacheConfig.getLettuceConfig().getClusterTopologyRefresh(); // // if (REDIS_MODE_CLUSTER.equalsIgnoreCase(cacheConfig.getLettuceConfig().getSchema())) { // List<RedisURI> redisURIs = new ArrayList<>(); // String[] hostArray = hosts.split(","); // for (String host : hostArray) { // String[] redisArray = host.split(":"); // RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1])); // uri.setDatabase(database); // uri.setPassword(password); // // uri.setSentinelMasterId(sentinelMasterId); // redisURIs.add(uri); // } // redisClient = RedisClusterClient.create(redisURIs); // ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder() // //开启自适应刷新 // .enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT, // ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS) // .enableAllAdaptiveRefreshTriggers() // .adaptiveRefreshTriggersTimeout(Duration.ofMillis(clusterTopologyRefresh)) // //开启定时刷新,时间间隔根据实际情况修改 // .enablePeriodicRefresh(Duration.ofMillis(clusterTopologyRefresh)) // .build(); // ((RedisClusterClient) redisClient).setOptions( // ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); // } else { // String[] redisArray = hosts.split(":"); // RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1])); // uri.setDatabase(database); // uri.setPassword(password); // redisClient = RedisClient.create(uri); // } // // try { // redisClient.setDefaultTimeout(Duration.ofMillis(cacheConfig.getLettuceConfig().getTimeout())); // } catch (Exception e) { // log.warn("Failed to set default timeout, using default 10000 milliseconds.", e); // } // // //connection pool configurations // GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); // poolConfig.setMaxTotal(cacheConfig.getLettuceConfig().getMaxTotal()); // poolConfig.setMaxIdle(cacheConfig.getLettuceConfig().getMaxIdle()); // poolConfig.setMinIdle(cacheConfig.getLettuceConfig().getMinIdle()); // // pool = ConnectionPoolSupport.createGenericObjectPool(() -> { // if (redisClient instanceof RedisClient) { // return ((RedisClient) redisClient).connect(codec); // } else if (redisClient instanceof RedisClusterClient) { // return ((RedisClusterClient) redisClient).connect(codec); // } // return null; // }, poolConfig); // // } // // @Override // public Cache buildCache(String region, int expire) throws CacheException { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) throws CacheException { // // try { // // CacheSerializer cacheSerializer = (CacheSerializer) Class // .forName(cacheConfig.getCacheSerializerClass()).newInstance(); // String namespace = this.cacheConfig.getLettuceConfig().getNamespace(); // // return regions // .computeIfAbsent(namespace + ":" + region, // k -> new LettuceCache(cacheSerializer, namespace, region, pool)); // }catch (Exception e){ // throw new CacheException(e); // } // // } // // @Override // public void stop() { // // pool.close(); // regions.clear(); // redisClient.shutdown(); // // } // }
import static org.junit.Assert.assertEquals; import com.google.common.collect.Lists; import com.jayqqaa12.jbase.cache.provider.NullCacheProvider; import com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import redis.embedded.RedisServer; import java.util.concurrent.TimeUnit;
package com.jayqqaa12.jbase.cache.core; /** * @author 12, {@literal <shuai.wang@leyantech.com>} * @date 2020-10-12. */ public class LettuceTest { private static JbaseCache jbaseCache; private static RedisServer redisServer; @BeforeClass public static void init() { redisServer = RedisServer.builder() .port(7777) .setting("bind localhost") .build() ; CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setProviderClassList( Lists.newArrayList(NullCacheProvider.class.getName(),
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java // public class NullCacheProvider implements CacheProvider { // // private static final NullCache cache=new NullCache(); // // @Override // public void init(CacheConfig cacheConfig) { // } // @Override // public Cache buildCache(String region, int expire) { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) { // return cache; // } // // @Override // public void stop() { // // } // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCacheProvider.java // @Slf4j // public class LettuceCacheProvider implements CacheProvider { // // private static AbstractRedisClient redisClient; // private GenericObjectPool<StatefulConnection<String, byte[]>> pool; // // private LettuceByteCodec codec = new LettuceByteCodec(); // // private final ConcurrentHashMap<String, Cache> regions = new ConcurrentHashMap<>(); // private CacheConfig cacheConfig; // // @Override // public void init(CacheConfig cacheConfig) { // this.cacheConfig = cacheConfig; // // String hosts = cacheConfig.getLettuceConfig().getHosts(); // // int database = cacheConfig.getLettuceConfig().getDatabase(); // String password = cacheConfig.getLettuceConfig().getPassword(); // // int clusterTopologyRefresh = cacheConfig.getLettuceConfig().getClusterTopologyRefresh(); // // if (REDIS_MODE_CLUSTER.equalsIgnoreCase(cacheConfig.getLettuceConfig().getSchema())) { // List<RedisURI> redisURIs = new ArrayList<>(); // String[] hostArray = hosts.split(","); // for (String host : hostArray) { // String[] redisArray = host.split(":"); // RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1])); // uri.setDatabase(database); // uri.setPassword(password); // // uri.setSentinelMasterId(sentinelMasterId); // redisURIs.add(uri); // } // redisClient = RedisClusterClient.create(redisURIs); // ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder() // //开启自适应刷新 // .enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT, // ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS) // .enableAllAdaptiveRefreshTriggers() // .adaptiveRefreshTriggersTimeout(Duration.ofMillis(clusterTopologyRefresh)) // //开启定时刷新,时间间隔根据实际情况修改 // .enablePeriodicRefresh(Duration.ofMillis(clusterTopologyRefresh)) // .build(); // ((RedisClusterClient) redisClient).setOptions( // ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build()); // } else { // String[] redisArray = hosts.split(":"); // RedisURI uri = RedisURI.create(redisArray[0], Integer.valueOf(redisArray[1])); // uri.setDatabase(database); // uri.setPassword(password); // redisClient = RedisClient.create(uri); // } // // try { // redisClient.setDefaultTimeout(Duration.ofMillis(cacheConfig.getLettuceConfig().getTimeout())); // } catch (Exception e) { // log.warn("Failed to set default timeout, using default 10000 milliseconds.", e); // } // // //connection pool configurations // GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); // poolConfig.setMaxTotal(cacheConfig.getLettuceConfig().getMaxTotal()); // poolConfig.setMaxIdle(cacheConfig.getLettuceConfig().getMaxIdle()); // poolConfig.setMinIdle(cacheConfig.getLettuceConfig().getMinIdle()); // // pool = ConnectionPoolSupport.createGenericObjectPool(() -> { // if (redisClient instanceof RedisClient) { // return ((RedisClient) redisClient).connect(codec); // } else if (redisClient instanceof RedisClusterClient) { // return ((RedisClusterClient) redisClient).connect(codec); // } // return null; // }, poolConfig); // // } // // @Override // public Cache buildCache(String region, int expire) throws CacheException { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) throws CacheException { // // try { // // CacheSerializer cacheSerializer = (CacheSerializer) Class // .forName(cacheConfig.getCacheSerializerClass()).newInstance(); // String namespace = this.cacheConfig.getLettuceConfig().getNamespace(); // // return regions // .computeIfAbsent(namespace + ":" + region, // k -> new LettuceCache(cacheSerializer, namespace, region, pool)); // }catch (Exception e){ // throw new CacheException(e); // } // // } // // @Override // public void stop() { // // pool.close(); // regions.clear(); // redisClient.shutdown(); // // } // } // Path: jbase-cache/src/test/java/com/jayqqaa12/jbase/cache/core/LettuceTest.java import static org.junit.Assert.assertEquals; import com.google.common.collect.Lists; import com.jayqqaa12.jbase.cache.provider.NullCacheProvider; import com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import redis.embedded.RedisServer; import java.util.concurrent.TimeUnit; package com.jayqqaa12.jbase.cache.core; /** * @author 12, {@literal <shuai.wang@leyantech.com>} * @date 2020-10-12. */ public class LettuceTest { private static JbaseCache jbaseCache; private static RedisServer redisServer; @BeforeClass public static void init() { redisServer = RedisServer.builder() .port(7777) .setting("bind localhost") .build() ; CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setProviderClassList( Lists.newArrayList(NullCacheProvider.class.getName(),
LettuceCacheProvider.class.getName()
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/EnableDb.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MybatisConfig.java // @Configuration // public class MybatisConfig { // // @Autowired // SqlSessionFactory sqlSessionFactory; // // // /** // * 注册enum 类型 都使用ordinal 表示 // */ // @PostConstruct // public void specialTypeHandlerRegistry() { // TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry(); // typeHandlerRegistry.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class); // // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MybatisPlusConfig.java // @Configuration // @ConditionalOnClass(MybatisConfiguration.class) // public class MybatisPlusConfig { // // // /** // * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除) // */ // @Bean // public MybatisPlusInterceptor mybatisPlusInterceptor() { // MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); // return interceptor; // } // // @Bean // public ConfigurationCustomizer configurationCustomizer() { // return configuration -> configuration.setUseDeprecatedExecutor(false); // } // }
import com.jayqqaa12.jbase.spring.boot.config.MybatisConfig; import com.jayqqaa12.jbase.spring.boot.config.MybatisPlusConfig; import org.springframework.context.annotation.Import; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.lang.annotation.*;
package com.jayqqaa12.jbase.spring.boot; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MybatisConfig.java // @Configuration // public class MybatisConfig { // // @Autowired // SqlSessionFactory sqlSessionFactory; // // // /** // * 注册enum 类型 都使用ordinal 表示 // */ // @PostConstruct // public void specialTypeHandlerRegistry() { // TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry(); // typeHandlerRegistry.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class); // // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MybatisPlusConfig.java // @Configuration // @ConditionalOnClass(MybatisConfiguration.class) // public class MybatisPlusConfig { // // // /** // * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除) // */ // @Bean // public MybatisPlusInterceptor mybatisPlusInterceptor() { // MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); // return interceptor; // } // // @Bean // public ConfigurationCustomizer configurationCustomizer() { // return configuration -> configuration.setUseDeprecatedExecutor(false); // } // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/EnableDb.java import com.jayqqaa12.jbase.spring.boot.config.MybatisConfig; import com.jayqqaa12.jbase.spring.boot.config.MybatisPlusConfig; import org.springframework.context.annotation.Import; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.lang.annotation.*; package com.jayqqaa12.jbase.spring.boot; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({
MybatisPlusConfig.class,
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/EnableDb.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MybatisConfig.java // @Configuration // public class MybatisConfig { // // @Autowired // SqlSessionFactory sqlSessionFactory; // // // /** // * 注册enum 类型 都使用ordinal 表示 // */ // @PostConstruct // public void specialTypeHandlerRegistry() { // TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry(); // typeHandlerRegistry.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class); // // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MybatisPlusConfig.java // @Configuration // @ConditionalOnClass(MybatisConfiguration.class) // public class MybatisPlusConfig { // // // /** // * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除) // */ // @Bean // public MybatisPlusInterceptor mybatisPlusInterceptor() { // MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); // return interceptor; // } // // @Bean // public ConfigurationCustomizer configurationCustomizer() { // return configuration -> configuration.setUseDeprecatedExecutor(false); // } // }
import com.jayqqaa12.jbase.spring.boot.config.MybatisConfig; import com.jayqqaa12.jbase.spring.boot.config.MybatisPlusConfig; import org.springframework.context.annotation.Import; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.lang.annotation.*;
package com.jayqqaa12.jbase.spring.boot; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({ MybatisPlusConfig.class,
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MybatisConfig.java // @Configuration // public class MybatisConfig { // // @Autowired // SqlSessionFactory sqlSessionFactory; // // // /** // * 注册enum 类型 都使用ordinal 表示 // */ // @PostConstruct // public void specialTypeHandlerRegistry() { // TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry(); // typeHandlerRegistry.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class); // // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MybatisPlusConfig.java // @Configuration // @ConditionalOnClass(MybatisConfiguration.class) // public class MybatisPlusConfig { // // // /** // * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除) // */ // @Bean // public MybatisPlusInterceptor mybatisPlusInterceptor() { // MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); // return interceptor; // } // // @Bean // public ConfigurationCustomizer configurationCustomizer() { // return configuration -> configuration.setUseDeprecatedExecutor(false); // } // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/EnableDb.java import com.jayqqaa12.jbase.spring.boot.config.MybatisConfig; import com.jayqqaa12.jbase.spring.boot.config.MybatisPlusConfig; import org.springframework.context.annotation.Import; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.lang.annotation.*; package com.jayqqaa12.jbase.spring.boot; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({ MybatisPlusConfig.class,
MybatisConfig.class,
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCache.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/SerializerCache.java // public abstract class SerializerCache implements Cache { // // private final CacheSerializer cacheSerializer; // // public SerializerCache(CacheSerializer cacheSerializer) { // this.cacheSerializer = cacheSerializer; // // } // // @Override // public CacheObject get(String key) throws CacheException { // try { // byte[] bytes = getByte(key); // return (CacheObject) cacheSerializer.deserialize(bytes); // } catch (Exception e) { // throw new CacheException(key + " deserialize error ", e); // } // } // // // // @Override // public void set(String key, CacheObject value) throws CacheException { // try { // setByte(key, cacheSerializer.serialize(value),0); // } catch (Exception e) { // throw new CacheException(key + " serialize error ", e); // } // // } // // // @Override // public void set(String key, CacheObject value, int expire) throws CacheException { // // try { // setByte(key, cacheSerializer.serialize(value), expire); // } catch (Exception e) { // throw new CacheException(key + " serialize error ", e); // } // } // // // public abstract byte[] getByte(String key) throws CacheException; // // public abstract void setByte(String key, byte[] value, int seconds) throws CacheException ; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.provider.SerializerCache; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import io.lettuce.core.api.StatefulConnection; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.BaseRedisCommands; import io.lettuce.core.api.sync.RedisKeyCommands; import io.lettuce.core.api.sync.RedisStringCommands; import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; import org.apache.commons.pool2.impl.GenericObjectPool;
package com.jayqqaa12.jbase.cache.provider.lettuce; public class LettuceCache extends SerializerCache { private final GenericObjectPool<StatefulConnection<String, byte[]>> pool; private final String region; private final String namespace;
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/SerializerCache.java // public abstract class SerializerCache implements Cache { // // private final CacheSerializer cacheSerializer; // // public SerializerCache(CacheSerializer cacheSerializer) { // this.cacheSerializer = cacheSerializer; // // } // // @Override // public CacheObject get(String key) throws CacheException { // try { // byte[] bytes = getByte(key); // return (CacheObject) cacheSerializer.deserialize(bytes); // } catch (Exception e) { // throw new CacheException(key + " deserialize error ", e); // } // } // // // // @Override // public void set(String key, CacheObject value) throws CacheException { // try { // setByte(key, cacheSerializer.serialize(value),0); // } catch (Exception e) { // throw new CacheException(key + " serialize error ", e); // } // // } // // // @Override // public void set(String key, CacheObject value, int expire) throws CacheException { // // try { // setByte(key, cacheSerializer.serialize(value), expire); // } catch (Exception e) { // throw new CacheException(key + " serialize error ", e); // } // } // // // public abstract byte[] getByte(String key) throws CacheException; // // public abstract void setByte(String key, byte[] value, int seconds) throws CacheException ; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCache.java import com.jayqqaa12.jbase.cache.provider.SerializerCache; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import io.lettuce.core.api.StatefulConnection; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.BaseRedisCommands; import io.lettuce.core.api.sync.RedisKeyCommands; import io.lettuce.core.api.sync.RedisStringCommands; import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; import org.apache.commons.pool2.impl.GenericObjectPool; package com.jayqqaa12.jbase.cache.provider.lettuce; public class LettuceCache extends SerializerCache { private final GenericObjectPool<StatefulConnection<String, byte[]>> pool; private final String region; private final String namespace;
public LettuceCache(CacheSerializer cacheSerializer, String namespace, String region,
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCache.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/SerializerCache.java // public abstract class SerializerCache implements Cache { // // private final CacheSerializer cacheSerializer; // // public SerializerCache(CacheSerializer cacheSerializer) { // this.cacheSerializer = cacheSerializer; // // } // // @Override // public CacheObject get(String key) throws CacheException { // try { // byte[] bytes = getByte(key); // return (CacheObject) cacheSerializer.deserialize(bytes); // } catch (Exception e) { // throw new CacheException(key + " deserialize error ", e); // } // } // // // // @Override // public void set(String key, CacheObject value) throws CacheException { // try { // setByte(key, cacheSerializer.serialize(value),0); // } catch (Exception e) { // throw new CacheException(key + " serialize error ", e); // } // // } // // // @Override // public void set(String key, CacheObject value, int expire) throws CacheException { // // try { // setByte(key, cacheSerializer.serialize(value), expire); // } catch (Exception e) { // throw new CacheException(key + " serialize error ", e); // } // } // // // public abstract byte[] getByte(String key) throws CacheException; // // public abstract void setByte(String key, byte[] value, int seconds) throws CacheException ; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.provider.SerializerCache; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import io.lettuce.core.api.StatefulConnection; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.BaseRedisCommands; import io.lettuce.core.api.sync.RedisKeyCommands; import io.lettuce.core.api.sync.RedisStringCommands; import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; import org.apache.commons.pool2.impl.GenericObjectPool;
package com.jayqqaa12.jbase.cache.provider.lettuce; public class LettuceCache extends SerializerCache { private final GenericObjectPool<StatefulConnection<String, byte[]>> pool; private final String region; private final String namespace; public LettuceCache(CacheSerializer cacheSerializer, String namespace, String region, GenericObjectPool<StatefulConnection<String, byte[]>> pool) { super(cacheSerializer); this.pool = pool; this.region = getRegionName(region); this.namespace = namespace; } private String getRegionName(String region) { if (namespace != null && !namespace.trim().isEmpty()) { region = namespace + ":" + region; } return region; } private StatefulConnection connect() { try { return pool.borrowObject(); } catch (Exception e) {
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/SerializerCache.java // public abstract class SerializerCache implements Cache { // // private final CacheSerializer cacheSerializer; // // public SerializerCache(CacheSerializer cacheSerializer) { // this.cacheSerializer = cacheSerializer; // // } // // @Override // public CacheObject get(String key) throws CacheException { // try { // byte[] bytes = getByte(key); // return (CacheObject) cacheSerializer.deserialize(bytes); // } catch (Exception e) { // throw new CacheException(key + " deserialize error ", e); // } // } // // // // @Override // public void set(String key, CacheObject value) throws CacheException { // try { // setByte(key, cacheSerializer.serialize(value),0); // } catch (Exception e) { // throw new CacheException(key + " serialize error ", e); // } // // } // // // @Override // public void set(String key, CacheObject value, int expire) throws CacheException { // // try { // setByte(key, cacheSerializer.serialize(value), expire); // } catch (Exception e) { // throw new CacheException(key + " serialize error ", e); // } // } // // // public abstract byte[] getByte(String key) throws CacheException; // // public abstract void setByte(String key, byte[] value, int seconds) throws CacheException ; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/lettuce/LettuceCache.java import com.jayqqaa12.jbase.cache.provider.SerializerCache; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import io.lettuce.core.api.StatefulConnection; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.BaseRedisCommands; import io.lettuce.core.api.sync.RedisKeyCommands; import io.lettuce.core.api.sync.RedisStringCommands; import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; import org.apache.commons.pool2.impl.GenericObjectPool; package com.jayqqaa12.jbase.cache.provider.lettuce; public class LettuceCache extends SerializerCache { private final GenericObjectPool<StatefulConnection<String, byte[]>> pool; private final String region; private final String namespace; public LettuceCache(CacheSerializer cacheSerializer, String namespace, String region, GenericObjectPool<StatefulConnection<String, byte[]>> pool) { super(cacheSerializer); this.pool = pool; this.region = getRegionName(region); this.namespace = namespace; } private String getRegionName(String region) { if (namespace != null && !namespace.trim().isEmpty()) { region = namespace + ":" + region; } return region; } private StatefulConnection connect() { try { return pool.borrowObject(); } catch (Exception e) {
throw new CacheException(e);
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/exception/GlobalExceptionHandler.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java // @Data // public class Resp { // private int code; // String msg; // private Object data; // // // public Resp(){ // } // // private Resp(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public static Resp response(int code) { // return new Resp(code, LocaleKit.resolverOrGet(code, null)); // } // // public static Resp response(int code, String msg) { // return new Resp(code, LocaleKit.resolverOrGet(code, msg)); // } // // // public static Resp success() { // return Resp.response(RespCode.SUCCESS ); // } // // // public static Resp error() { // return Resp.response(RespCode.SERVER_ERROR ); // } // // public static Resp error(String msg) { // return new Resp(RespCode.SERVER_ERROR, LocaleKit.resolverOrGet(RespCode.SERVER_ERROR, msg)); // } // // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/RespCode.java // public abstract class RespCode { // // public static final int SUCCESS = 200; // | 成功 | // // // // 1000-1199 内部异常 服务器相关错误 // public static final int SERVER_ERROR = 1000; // | 服务器内部异常 或未指定异常| // public static final int GATEWAY_ERROR=1100; // |网关访问异常| // public static final int DB_SQL_ERROR= 1101; // sql执行异常 // public static final int PARAM_ERROR=1102; //参数异常 // public static final int RETRY_ERROR =1103; // 重试异常 // public static final int RETRY_LOCK_ERROR=1104;// 幂等性异常 // public static final int SERVER_BLOCK=1105;//服务限流 // public static final int SERVER_DEGRADE=1106;//服务降级 // // // // 1300-1399 请求相关异常 // public static final int RESOURCE_NOT_FOUND = 1300; // | 请求没有被找到 | // public static final int REQ_METHOD_NOT_ALLOWED = 1301; // | 方法不被允许 | // public static final int REQ_MEDIA_UNSUPPORTED = 1302; // | 不支持的媒体类型 | // public static final int BAD_REQ = 1303; // | BAD REQUEST | // public static final int REQ_METHOD_GET = 1304; // | 请求必须是GET请求 | // public static final int REQ_METHOD_POST = 1305; // | 请求必须是POST请求 | // public static final int REQ_METHOD_PUT = 1306; // | 请求必须是PUT请求 | // public static final int REQ_METHOD_DELETE = 1307; // | 请求必须是DELETE请求 | // // public static final int REQ_JSON_FORMAT_ERROR=1310;// JSON 解析异常 // // // // 引用外部 SDK 相关错误 1500-1599 // public static final int INNER__CONTENT_SCAN_ERROR = 1500; //没有配置图片检测类型 // // // // // 1600-1999 内部模块异常 // // public static final int AUTH_ERROR=1600; // |没有权限| // public static final int AUTH_USER_NOT_FOUND=1601; //用户不存在 // public static final int AUTH_USER_LOGIN_ERROR=1602; //用户名或密码错误 // // public static final int AUTH_TOKEN_EXPIRED=1603; //TOKEN 过期 // public static final int AUTH_TOKEN_SIGN_ERROR=1604;//TOKEN 签名异常 // // // // // public static final int VALIDATE_CODE_VALIDATE_ERROR =1700; //验证码错误 // public static final int VALIDATE_CODE_PAST_DUE =1701; //验证码过期 // // public static final int SMS_ERROR=1702; //发送失败 // // public static final int SMS_LIMIT=1703; //超过限制 // public static final int SMS_PHONE_ERROR=1704;//手机号错误 // // // // //2000+ 业务模块自定义异常 继承这个类 最好定义在一个公共模块里防止 冲突 // // // // // }
import com.jayqqaa12.jbase.spring.mvc.Resp; import com.jayqqaa12.jbase.spring.mvc.RespCode; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.util.List;
package com.jayqqaa12.jbase.spring.mvc.exception; @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { if (body == null) { switch (status) { case NOT_FOUND:
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java // @Data // public class Resp { // private int code; // String msg; // private Object data; // // // public Resp(){ // } // // private Resp(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public static Resp response(int code) { // return new Resp(code, LocaleKit.resolverOrGet(code, null)); // } // // public static Resp response(int code, String msg) { // return new Resp(code, LocaleKit.resolverOrGet(code, msg)); // } // // // public static Resp success() { // return Resp.response(RespCode.SUCCESS ); // } // // // public static Resp error() { // return Resp.response(RespCode.SERVER_ERROR ); // } // // public static Resp error(String msg) { // return new Resp(RespCode.SERVER_ERROR, LocaleKit.resolverOrGet(RespCode.SERVER_ERROR, msg)); // } // // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/RespCode.java // public abstract class RespCode { // // public static final int SUCCESS = 200; // | 成功 | // // // // 1000-1199 内部异常 服务器相关错误 // public static final int SERVER_ERROR = 1000; // | 服务器内部异常 或未指定异常| // public static final int GATEWAY_ERROR=1100; // |网关访问异常| // public static final int DB_SQL_ERROR= 1101; // sql执行异常 // public static final int PARAM_ERROR=1102; //参数异常 // public static final int RETRY_ERROR =1103; // 重试异常 // public static final int RETRY_LOCK_ERROR=1104;// 幂等性异常 // public static final int SERVER_BLOCK=1105;//服务限流 // public static final int SERVER_DEGRADE=1106;//服务降级 // // // // 1300-1399 请求相关异常 // public static final int RESOURCE_NOT_FOUND = 1300; // | 请求没有被找到 | // public static final int REQ_METHOD_NOT_ALLOWED = 1301; // | 方法不被允许 | // public static final int REQ_MEDIA_UNSUPPORTED = 1302; // | 不支持的媒体类型 | // public static final int BAD_REQ = 1303; // | BAD REQUEST | // public static final int REQ_METHOD_GET = 1304; // | 请求必须是GET请求 | // public static final int REQ_METHOD_POST = 1305; // | 请求必须是POST请求 | // public static final int REQ_METHOD_PUT = 1306; // | 请求必须是PUT请求 | // public static final int REQ_METHOD_DELETE = 1307; // | 请求必须是DELETE请求 | // // public static final int REQ_JSON_FORMAT_ERROR=1310;// JSON 解析异常 // // // // 引用外部 SDK 相关错误 1500-1599 // public static final int INNER__CONTENT_SCAN_ERROR = 1500; //没有配置图片检测类型 // // // // // 1600-1999 内部模块异常 // // public static final int AUTH_ERROR=1600; // |没有权限| // public static final int AUTH_USER_NOT_FOUND=1601; //用户不存在 // public static final int AUTH_USER_LOGIN_ERROR=1602; //用户名或密码错误 // // public static final int AUTH_TOKEN_EXPIRED=1603; //TOKEN 过期 // public static final int AUTH_TOKEN_SIGN_ERROR=1604;//TOKEN 签名异常 // // // // // public static final int VALIDATE_CODE_VALIDATE_ERROR =1700; //验证码错误 // public static final int VALIDATE_CODE_PAST_DUE =1701; //验证码过期 // // public static final int SMS_ERROR=1702; //发送失败 // // public static final int SMS_LIMIT=1703; //超过限制 // public static final int SMS_PHONE_ERROR=1704;//手机号错误 // // // // //2000+ 业务模块自定义异常 继承这个类 最好定义在一个公共模块里防止 冲突 // // // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/exception/GlobalExceptionHandler.java import com.jayqqaa12.jbase.spring.mvc.Resp; import com.jayqqaa12.jbase.spring.mvc.RespCode; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.util.List; package com.jayqqaa12.jbase.spring.mvc.exception; @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { if (body == null) { switch (status) { case NOT_FOUND:
body = Resp.response(RespCode.RESOURCE_NOT_FOUND);
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/exception/GlobalExceptionHandler.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java // @Data // public class Resp { // private int code; // String msg; // private Object data; // // // public Resp(){ // } // // private Resp(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public static Resp response(int code) { // return new Resp(code, LocaleKit.resolverOrGet(code, null)); // } // // public static Resp response(int code, String msg) { // return new Resp(code, LocaleKit.resolverOrGet(code, msg)); // } // // // public static Resp success() { // return Resp.response(RespCode.SUCCESS ); // } // // // public static Resp error() { // return Resp.response(RespCode.SERVER_ERROR ); // } // // public static Resp error(String msg) { // return new Resp(RespCode.SERVER_ERROR, LocaleKit.resolverOrGet(RespCode.SERVER_ERROR, msg)); // } // // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/RespCode.java // public abstract class RespCode { // // public static final int SUCCESS = 200; // | 成功 | // // // // 1000-1199 内部异常 服务器相关错误 // public static final int SERVER_ERROR = 1000; // | 服务器内部异常 或未指定异常| // public static final int GATEWAY_ERROR=1100; // |网关访问异常| // public static final int DB_SQL_ERROR= 1101; // sql执行异常 // public static final int PARAM_ERROR=1102; //参数异常 // public static final int RETRY_ERROR =1103; // 重试异常 // public static final int RETRY_LOCK_ERROR=1104;// 幂等性异常 // public static final int SERVER_BLOCK=1105;//服务限流 // public static final int SERVER_DEGRADE=1106;//服务降级 // // // // 1300-1399 请求相关异常 // public static final int RESOURCE_NOT_FOUND = 1300; // | 请求没有被找到 | // public static final int REQ_METHOD_NOT_ALLOWED = 1301; // | 方法不被允许 | // public static final int REQ_MEDIA_UNSUPPORTED = 1302; // | 不支持的媒体类型 | // public static final int BAD_REQ = 1303; // | BAD REQUEST | // public static final int REQ_METHOD_GET = 1304; // | 请求必须是GET请求 | // public static final int REQ_METHOD_POST = 1305; // | 请求必须是POST请求 | // public static final int REQ_METHOD_PUT = 1306; // | 请求必须是PUT请求 | // public static final int REQ_METHOD_DELETE = 1307; // | 请求必须是DELETE请求 | // // public static final int REQ_JSON_FORMAT_ERROR=1310;// JSON 解析异常 // // // // 引用外部 SDK 相关错误 1500-1599 // public static final int INNER__CONTENT_SCAN_ERROR = 1500; //没有配置图片检测类型 // // // // // 1600-1999 内部模块异常 // // public static final int AUTH_ERROR=1600; // |没有权限| // public static final int AUTH_USER_NOT_FOUND=1601; //用户不存在 // public static final int AUTH_USER_LOGIN_ERROR=1602; //用户名或密码错误 // // public static final int AUTH_TOKEN_EXPIRED=1603; //TOKEN 过期 // public static final int AUTH_TOKEN_SIGN_ERROR=1604;//TOKEN 签名异常 // // // // // public static final int VALIDATE_CODE_VALIDATE_ERROR =1700; //验证码错误 // public static final int VALIDATE_CODE_PAST_DUE =1701; //验证码过期 // // public static final int SMS_ERROR=1702; //发送失败 // // public static final int SMS_LIMIT=1703; //超过限制 // public static final int SMS_PHONE_ERROR=1704;//手机号错误 // // // // //2000+ 业务模块自定义异常 继承这个类 最好定义在一个公共模块里防止 冲突 // // // // // }
import com.jayqqaa12.jbase.spring.mvc.Resp; import com.jayqqaa12.jbase.spring.mvc.RespCode; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.util.List;
package com.jayqqaa12.jbase.spring.mvc.exception; @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { if (body == null) { switch (status) { case NOT_FOUND:
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java // @Data // public class Resp { // private int code; // String msg; // private Object data; // // // public Resp(){ // } // // private Resp(int code, String msg) { // this.code = code; // this.msg = msg; // } // // public static Resp response(int code) { // return new Resp(code, LocaleKit.resolverOrGet(code, null)); // } // // public static Resp response(int code, String msg) { // return new Resp(code, LocaleKit.resolverOrGet(code, msg)); // } // // // public static Resp success() { // return Resp.response(RespCode.SUCCESS ); // } // // // public static Resp error() { // return Resp.response(RespCode.SERVER_ERROR ); // } // // public static Resp error(String msg) { // return new Resp(RespCode.SERVER_ERROR, LocaleKit.resolverOrGet(RespCode.SERVER_ERROR, msg)); // } // // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/RespCode.java // public abstract class RespCode { // // public static final int SUCCESS = 200; // | 成功 | // // // // 1000-1199 内部异常 服务器相关错误 // public static final int SERVER_ERROR = 1000; // | 服务器内部异常 或未指定异常| // public static final int GATEWAY_ERROR=1100; // |网关访问异常| // public static final int DB_SQL_ERROR= 1101; // sql执行异常 // public static final int PARAM_ERROR=1102; //参数异常 // public static final int RETRY_ERROR =1103; // 重试异常 // public static final int RETRY_LOCK_ERROR=1104;// 幂等性异常 // public static final int SERVER_BLOCK=1105;//服务限流 // public static final int SERVER_DEGRADE=1106;//服务降级 // // // // 1300-1399 请求相关异常 // public static final int RESOURCE_NOT_FOUND = 1300; // | 请求没有被找到 | // public static final int REQ_METHOD_NOT_ALLOWED = 1301; // | 方法不被允许 | // public static final int REQ_MEDIA_UNSUPPORTED = 1302; // | 不支持的媒体类型 | // public static final int BAD_REQ = 1303; // | BAD REQUEST | // public static final int REQ_METHOD_GET = 1304; // | 请求必须是GET请求 | // public static final int REQ_METHOD_POST = 1305; // | 请求必须是POST请求 | // public static final int REQ_METHOD_PUT = 1306; // | 请求必须是PUT请求 | // public static final int REQ_METHOD_DELETE = 1307; // | 请求必须是DELETE请求 | // // public static final int REQ_JSON_FORMAT_ERROR=1310;// JSON 解析异常 // // // // 引用外部 SDK 相关错误 1500-1599 // public static final int INNER__CONTENT_SCAN_ERROR = 1500; //没有配置图片检测类型 // // // // // 1600-1999 内部模块异常 // // public static final int AUTH_ERROR=1600; // |没有权限| // public static final int AUTH_USER_NOT_FOUND=1601; //用户不存在 // public static final int AUTH_USER_LOGIN_ERROR=1602; //用户名或密码错误 // // public static final int AUTH_TOKEN_EXPIRED=1603; //TOKEN 过期 // public static final int AUTH_TOKEN_SIGN_ERROR=1604;//TOKEN 签名异常 // // // // // public static final int VALIDATE_CODE_VALIDATE_ERROR =1700; //验证码错误 // public static final int VALIDATE_CODE_PAST_DUE =1701; //验证码过期 // // public static final int SMS_ERROR=1702; //发送失败 // // public static final int SMS_LIMIT=1703; //超过限制 // public static final int SMS_PHONE_ERROR=1704;//手机号错误 // // // // //2000+ 业务模块自定义异常 继承这个类 最好定义在一个公共模块里防止 冲突 // // // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/exception/GlobalExceptionHandler.java import com.jayqqaa12.jbase.spring.mvc.Resp; import com.jayqqaa12.jbase.spring.mvc.RespCode; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import java.util.List; package com.jayqqaa12.jbase.spring.mvc.exception; @ControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @Override protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { if (body == null) { switch (status) { case NOT_FOUND:
body = Resp.response(RespCode.RESOURCE_NOT_FOUND);
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/i18n/LocaleKit.java // public class LocaleKit { // // public static final String MSG_PREFIX = "msg."; // // private static final String PREFIX = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX; // private static final String SUFFIX = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_SUFFIX; // // private static PropertyPlaceholderHelper placeholderHelper = new PropertyPlaceholderHelper(PREFIX, SUFFIX); // private static Pattern PATTERN = Pattern.compile("[\\w]+([\\.][\\w\\d]+)+"); // private static Locale DEFAULT_LOCALE = Locale.CHINA; // private static final String[] PARAM_HOLDER = new String[]{"", "", "", "", "", ""}; // // private static MessageSource messageSource; // // // public static LocaleKit of(MessageSource messageSource) { // LocaleKit.messageSource = messageSource; // return new LocaleKit(); // } // // // public static String resolverOrGet(String message, Object... args) { // // if (PATTERN.matcher(message).matches()) { // return get(message, args); // } else { // return resolver(message, args); // } // } // // public static String resolverOrGet(int code, String message, Object... args) { // // if (StringUtils.isEmpty(message)) { // return resolverOrGet(MSG_PREFIX + code, args); // } else { // return resolverOrGet(message, args); // } // } // // // public static String resolver(String message, Object... args) { // // final Locale locale = getLocale(); // // return placeholderHelper.replacePlaceholders(message, s -> get(s, locale, args)); // } // // public static String get(String code, Object... args) { // // return get(code, getLocale(), args); // } // // // public static String get(String code, Locale locale, Object... args) { // // if (messageSource == null) return "messageSource not init "; // // // if (args == null || args.length == 0) { // args = PARAM_HOLDER; // } // // String msg = code; // try { // msg = messageSource.getMessage(code, args, locale); // } catch (NoSuchMessageException e) { // //Ignore // } // // return msg; // } // // // public static Locale getLocale() { // Locale locale = LocaleContextHolder.getLocale(); // // return locale == null ? DEFAULT_LOCALE : locale; // } // // // // public static Locale getLocale(HttpServletRequest request) { // // Locale locale = RequestContextUtils.getLocale(request); // // // // return locale == null ? DEFAULT_LOCALE : locale; // // } // // public static void setDefaultLocale(Locale locale){ // DEFAULT_LOCALE = locale; // } // }
import com.jayqqaa12.jbase.spring.mvc.i18n.LocaleKit; import lombok.Data;
package com.jayqqaa12.jbase.spring.mvc; @Data public class Resp { private int code; String msg; private Object data; public Resp(){ } private Resp(int code, String msg) { this.code = code; this.msg = msg; } public static Resp response(int code) {
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/i18n/LocaleKit.java // public class LocaleKit { // // public static final String MSG_PREFIX = "msg."; // // private static final String PREFIX = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX; // private static final String SUFFIX = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_SUFFIX; // // private static PropertyPlaceholderHelper placeholderHelper = new PropertyPlaceholderHelper(PREFIX, SUFFIX); // private static Pattern PATTERN = Pattern.compile("[\\w]+([\\.][\\w\\d]+)+"); // private static Locale DEFAULT_LOCALE = Locale.CHINA; // private static final String[] PARAM_HOLDER = new String[]{"", "", "", "", "", ""}; // // private static MessageSource messageSource; // // // public static LocaleKit of(MessageSource messageSource) { // LocaleKit.messageSource = messageSource; // return new LocaleKit(); // } // // // public static String resolverOrGet(String message, Object... args) { // // if (PATTERN.matcher(message).matches()) { // return get(message, args); // } else { // return resolver(message, args); // } // } // // public static String resolverOrGet(int code, String message, Object... args) { // // if (StringUtils.isEmpty(message)) { // return resolverOrGet(MSG_PREFIX + code, args); // } else { // return resolverOrGet(message, args); // } // } // // // public static String resolver(String message, Object... args) { // // final Locale locale = getLocale(); // // return placeholderHelper.replacePlaceholders(message, s -> get(s, locale, args)); // } // // public static String get(String code, Object... args) { // // return get(code, getLocale(), args); // } // // // public static String get(String code, Locale locale, Object... args) { // // if (messageSource == null) return "messageSource not init "; // // // if (args == null || args.length == 0) { // args = PARAM_HOLDER; // } // // String msg = code; // try { // msg = messageSource.getMessage(code, args, locale); // } catch (NoSuchMessageException e) { // //Ignore // } // // return msg; // } // // // public static Locale getLocale() { // Locale locale = LocaleContextHolder.getLocale(); // // return locale == null ? DEFAULT_LOCALE : locale; // } // // // // public static Locale getLocale(HttpServletRequest request) { // // Locale locale = RequestContextUtils.getLocale(request); // // // // return locale == null ? DEFAULT_LOCALE : locale; // // } // // public static void setDefaultLocale(Locale locale){ // DEFAULT_LOCALE = locale; // } // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/Resp.java import com.jayqqaa12.jbase.spring.mvc.i18n.LocaleKit; import lombok.Data; package com.jayqqaa12.jbase.spring.mvc; @Data public class Resp { private int code; String msg; private Object data; public Resp(){ } private Resp(int code, String msg) { this.code = code; this.msg = msg; } public static Resp response(int code) {
return new Resp(code, LocaleKit.resolverOrGet(code, null));
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/SerializerCache.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import java.io.IOException;
package com.jayqqaa12.jbase.cache.provider; public abstract class SerializerCache implements Cache { private final CacheSerializer cacheSerializer; public SerializerCache(CacheSerializer cacheSerializer) { this.cacheSerializer = cacheSerializer; } @Override
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/SerializerCache.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import java.io.IOException; package com.jayqqaa12.jbase.cache.provider; public abstract class SerializerCache implements Cache { private final CacheSerializer cacheSerializer; public SerializerCache(CacheSerializer cacheSerializer) { this.cacheSerializer = cacheSerializer; } @Override
public CacheObject get(String key) throws CacheException {
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/SerializerCache.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import java.io.IOException;
package com.jayqqaa12.jbase.cache.provider; public abstract class SerializerCache implements Cache { private final CacheSerializer cacheSerializer; public SerializerCache(CacheSerializer cacheSerializer) { this.cacheSerializer = cacheSerializer; } @Override
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/serializer/CacheSerializer.java // public interface CacheSerializer { // // byte[] serialize(Object obj) ; // // Object deserialize(byte[] bytes) ; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/SerializerCache.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.serializer.CacheSerializer; import com.jayqqaa12.jbase.cache.util.CacheException; import java.io.IOException; package com.jayqqaa12.jbase.cache.provider; public abstract class SerializerCache implements Cache { private final CacheSerializer cacheSerializer; public SerializerCache(CacheSerializer cacheSerializer) { this.cacheSerializer = cacheSerializer; } @Override
public CacheObject get(String key) throws CacheException {
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.provider.CacheProvider;
package com.jayqqaa12.jbase.cache.provider; public class NullCacheProvider implements CacheProvider { private static final NullCache cache=new NullCache(); @Override
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.provider.CacheProvider; package com.jayqqaa12.jbase.cache.provider; public class NullCacheProvider implements CacheProvider { private static final NullCache cache=new NullCache(); @Override
public void init(CacheConfig cacheConfig) {
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.provider.CacheProvider;
package com.jayqqaa12.jbase.cache.provider; public class NullCacheProvider implements CacheProvider { private static final NullCache cache=new NullCache(); @Override public void init(CacheConfig cacheConfig) { } @Override
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.provider.CacheProvider; package com.jayqqaa12.jbase.cache.provider; public class NullCacheProvider implements CacheProvider { private static final NullCache cache=new NullCache(); @Override public void init(CacheConfig cacheConfig) { } @Override
public Cache buildCache(String region, int expire) {
jayqqaa12/jbase
jbase-cache/src/test/java/com/jayqqaa12/jbase/cache/core/CaffeineTest.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java // public class NullCacheProvider implements CacheProvider { // // private static final NullCache cache=new NullCache(); // // @Override // public void init(CacheConfig cacheConfig) { // } // @Override // public Cache buildCache(String region, int expire) { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) { // return cache; // } // // @Override // public void stop() { // // } // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java // public class CaffeineCacheProvider implements CacheProvider { // // private CacheConfig cacheConfig; // // private Map<String, Cache> cacheMap = new HashMap<>(); // private CaffeineConfig defualtConfig = new CaffeineConfig(); // // @Override // public void init(CacheConfig cacheConfig) { // // this.cacheConfig = cacheConfig; // // this.defualtConfig.setSize(10000); // this.defualtConfig.setExpire(60 * 30); // // } // // @Override // public Cache // buildCache(String region, int expire) { // CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); // // return newCache(region, config.getSize(), expire); // } // // private Cache newCache(String region, int size, int expire) { // return cacheMap.computeIfAbsent(region, v -> { // Caffeine<Object, Object> caffeine = Caffeine.newBuilder(); // // caffeine = caffeine.maximumSize(size); // if (expire > 0) { // caffeine = caffeine.expireAfterWrite(expire, TimeUnit.SECONDS); // } // // com.github.benmanes.caffeine.cache.Cache<String, CacheObject> loadingCache = caffeine.build(); // return new CaffeineCache(loadingCache); // }); // } // // @Override // public Cache buildCache(String region) { // CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); // return newCache(region, config.getSize(), config.getExpire()); // } // // // @Override // public void stop() { // cacheMap.clear(); // } // }
import static org.junit.Assert.*; import com.google.common.collect.Lists; import com.jayqqaa12.jbase.cache.provider.NullCacheProvider; import com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import redis.embedded.RedisServer; import java.util.concurrent.TimeUnit;
package com.jayqqaa12.jbase.cache.core; /** * @author 12, {@literal <shuai.wang@leyantech.com>} * @date 2020-10-12. */ @Slf4j public class CaffeineTest { private JbaseCache jbaseCache; @Before public void init() { CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setProviderClassList(
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java // public class NullCacheProvider implements CacheProvider { // // private static final NullCache cache=new NullCache(); // // @Override // public void init(CacheConfig cacheConfig) { // } // @Override // public Cache buildCache(String region, int expire) { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) { // return cache; // } // // @Override // public void stop() { // // } // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java // public class CaffeineCacheProvider implements CacheProvider { // // private CacheConfig cacheConfig; // // private Map<String, Cache> cacheMap = new HashMap<>(); // private CaffeineConfig defualtConfig = new CaffeineConfig(); // // @Override // public void init(CacheConfig cacheConfig) { // // this.cacheConfig = cacheConfig; // // this.defualtConfig.setSize(10000); // this.defualtConfig.setExpire(60 * 30); // // } // // @Override // public Cache // buildCache(String region, int expire) { // CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); // // return newCache(region, config.getSize(), expire); // } // // private Cache newCache(String region, int size, int expire) { // return cacheMap.computeIfAbsent(region, v -> { // Caffeine<Object, Object> caffeine = Caffeine.newBuilder(); // // caffeine = caffeine.maximumSize(size); // if (expire > 0) { // caffeine = caffeine.expireAfterWrite(expire, TimeUnit.SECONDS); // } // // com.github.benmanes.caffeine.cache.Cache<String, CacheObject> loadingCache = caffeine.build(); // return new CaffeineCache(loadingCache); // }); // } // // @Override // public Cache buildCache(String region) { // CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); // return newCache(region, config.getSize(), config.getExpire()); // } // // // @Override // public void stop() { // cacheMap.clear(); // } // } // Path: jbase-cache/src/test/java/com/jayqqaa12/jbase/cache/core/CaffeineTest.java import static org.junit.Assert.*; import com.google.common.collect.Lists; import com.jayqqaa12.jbase.cache.provider.NullCacheProvider; import com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import redis.embedded.RedisServer; import java.util.concurrent.TimeUnit; package com.jayqqaa12.jbase.cache.core; /** * @author 12, {@literal <shuai.wang@leyantech.com>} * @date 2020-10-12. */ @Slf4j public class CaffeineTest { private JbaseCache jbaseCache; @Before public void init() { CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setProviderClassList(
Lists.newArrayList(NullCacheProvider.class.getName(),
jayqqaa12/jbase
jbase-cache/src/test/java/com/jayqqaa12/jbase/cache/core/CaffeineTest.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java // public class NullCacheProvider implements CacheProvider { // // private static final NullCache cache=new NullCache(); // // @Override // public void init(CacheConfig cacheConfig) { // } // @Override // public Cache buildCache(String region, int expire) { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) { // return cache; // } // // @Override // public void stop() { // // } // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java // public class CaffeineCacheProvider implements CacheProvider { // // private CacheConfig cacheConfig; // // private Map<String, Cache> cacheMap = new HashMap<>(); // private CaffeineConfig defualtConfig = new CaffeineConfig(); // // @Override // public void init(CacheConfig cacheConfig) { // // this.cacheConfig = cacheConfig; // // this.defualtConfig.setSize(10000); // this.defualtConfig.setExpire(60 * 30); // // } // // @Override // public Cache // buildCache(String region, int expire) { // CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); // // return newCache(region, config.getSize(), expire); // } // // private Cache newCache(String region, int size, int expire) { // return cacheMap.computeIfAbsent(region, v -> { // Caffeine<Object, Object> caffeine = Caffeine.newBuilder(); // // caffeine = caffeine.maximumSize(size); // if (expire > 0) { // caffeine = caffeine.expireAfterWrite(expire, TimeUnit.SECONDS); // } // // com.github.benmanes.caffeine.cache.Cache<String, CacheObject> loadingCache = caffeine.build(); // return new CaffeineCache(loadingCache); // }); // } // // @Override // public Cache buildCache(String region) { // CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); // return newCache(region, config.getSize(), config.getExpire()); // } // // // @Override // public void stop() { // cacheMap.clear(); // } // }
import static org.junit.Assert.*; import com.google.common.collect.Lists; import com.jayqqaa12.jbase.cache.provider.NullCacheProvider; import com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import redis.embedded.RedisServer; import java.util.concurrent.TimeUnit;
package com.jayqqaa12.jbase.cache.core; /** * @author 12, {@literal <shuai.wang@leyantech.com>} * @date 2020-10-12. */ @Slf4j public class CaffeineTest { private JbaseCache jbaseCache; @Before public void init() { CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setProviderClassList( Lists.newArrayList(NullCacheProvider.class.getName(),
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCacheProvider.java // public class NullCacheProvider implements CacheProvider { // // private static final NullCache cache=new NullCache(); // // @Override // public void init(CacheConfig cacheConfig) { // } // @Override // public Cache buildCache(String region, int expire) { // return buildCache(region); // } // // @Override // public Cache buildCache(String region) { // return cache; // } // // @Override // public void stop() { // // } // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java // public class CaffeineCacheProvider implements CacheProvider { // // private CacheConfig cacheConfig; // // private Map<String, Cache> cacheMap = new HashMap<>(); // private CaffeineConfig defualtConfig = new CaffeineConfig(); // // @Override // public void init(CacheConfig cacheConfig) { // // this.cacheConfig = cacheConfig; // // this.defualtConfig.setSize(10000); // this.defualtConfig.setExpire(60 * 30); // // } // // @Override // public Cache // buildCache(String region, int expire) { // CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); // // return newCache(region, config.getSize(), expire); // } // // private Cache newCache(String region, int size, int expire) { // return cacheMap.computeIfAbsent(region, v -> { // Caffeine<Object, Object> caffeine = Caffeine.newBuilder(); // // caffeine = caffeine.maximumSize(size); // if (expire > 0) { // caffeine = caffeine.expireAfterWrite(expire, TimeUnit.SECONDS); // } // // com.github.benmanes.caffeine.cache.Cache<String, CacheObject> loadingCache = caffeine.build(); // return new CaffeineCache(loadingCache); // }); // } // // @Override // public Cache buildCache(String region) { // CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); // return newCache(region, config.getSize(), config.getExpire()); // } // // // @Override // public void stop() { // cacheMap.clear(); // } // } // Path: jbase-cache/src/test/java/com/jayqqaa12/jbase/cache/core/CaffeineTest.java import static org.junit.Assert.*; import com.google.common.collect.Lists; import com.jayqqaa12.jbase.cache.provider.NullCacheProvider; import com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import redis.embedded.RedisServer; import java.util.concurrent.TimeUnit; package com.jayqqaa12.jbase.cache.core; /** * @author 12, {@literal <shuai.wang@leyantech.com>} * @date 2020-10-12. */ @Slf4j public class CaffeineTest { private JbaseCache jbaseCache; @Before public void init() { CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setProviderClassList( Lists.newArrayList(NullCacheProvider.class.getName(),
CaffeineCacheProvider.class.getName()
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mqtt/handler/MqttReceiver.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mqtt/protocol/MqttReq.java // @Data // public class MqttReq<T> { // // /** // * 请求序列 客户端传递用来标示 返回的消息是哪次请求 // */ // private String reqNo; // // /** // * 时间戳 // */ // private Long timestamp; // // /** // * 当前接口的版本号 // */ // private String version; // // /** // * 平台 device android ios // */ // private String platform; // // /** // * 设备唯一标示 // */ // private String uniqueCode; // // // private T data; // // // // }
import com.alibaba.fastjson.JSON; import com.jayqqaa12.jbase.spring.mqtt.protocol.MqttReq; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.mqtt.support.MqttHeaders; import org.springframework.messaging.MessageHandler; import org.springframework.stereotype.Component; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.List;
package com.jayqqaa12.jbase.spring.mqtt.handler; @Slf4j @Component public class MqttReceiver { @Autowired(required = false) List<MqttHandler> handlerList; @Bean @ServiceActivator(inputChannel = "mqttInputChannel") public MessageHandler handler() { return (message) -> { String topic = (String) message.getHeaders().get(MqttHeaders.TOPIC); byte[] payload = (byte[]) message.getPayload(); log.info("receiver byte len {}", payload.length); try { if (handlerList == null) return; for (MqttHandler mqttHandler : handlerList) { TopicMapping topicMapping = mqttHandler.getClass().getAnnotation(TopicMapping.class); if (topicMapping == null) throw new RuntimeException("MqttHandler must use @TopicMapping "); Type type = mqttHandler.getClass().getGenericInterfaces()[0]; ParameterizedType parameterizedType = (ParameterizedType) type; Type[] types = parameterizedType.getActualTypeArguments(); Type rawType = types[0]; if (rawType instanceof ParameterizedType) { rawType = ((ParameterizedType) rawType).getRawType(); } Class clazz = (Class) rawType; // 这里要判断一下 topic if (isContainsTopic(topic, topicMapping.value())) { Object data = payload; if (clazz.isAssignableFrom(String.class)) data = new String(payload, Charset.defaultCharset());
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mqtt/protocol/MqttReq.java // @Data // public class MqttReq<T> { // // /** // * 请求序列 客户端传递用来标示 返回的消息是哪次请求 // */ // private String reqNo; // // /** // * 时间戳 // */ // private Long timestamp; // // /** // * 当前接口的版本号 // */ // private String version; // // /** // * 平台 device android ios // */ // private String platform; // // /** // * 设备唯一标示 // */ // private String uniqueCode; // // // private T data; // // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mqtt/handler/MqttReceiver.java import com.alibaba.fastjson.JSON; import com.jayqqaa12.jbase.spring.mqtt.protocol.MqttReq; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.mqtt.support.MqttHeaders; import org.springframework.messaging.MessageHandler; import org.springframework.stereotype.Component; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.List; package com.jayqqaa12.jbase.spring.mqtt.handler; @Slf4j @Component public class MqttReceiver { @Autowired(required = false) List<MqttHandler> handlerList; @Bean @ServiceActivator(inputChannel = "mqttInputChannel") public MessageHandler handler() { return (message) -> { String topic = (String) message.getHeaders().get(MqttHeaders.TOPIC); byte[] payload = (byte[]) message.getPayload(); log.info("receiver byte len {}", payload.length); try { if (handlerList == null) return; for (MqttHandler mqttHandler : handlerList) { TopicMapping topicMapping = mqttHandler.getClass().getAnnotation(TopicMapping.class); if (topicMapping == null) throw new RuntimeException("MqttHandler must use @TopicMapping "); Type type = mqttHandler.getClass().getGenericInterfaces()[0]; ParameterizedType parameterizedType = (ParameterizedType) type; Type[] types = parameterizedType.getActualTypeArguments(); Type rawType = types[0]; if (rawType instanceof ParameterizedType) { rawType = ((ParameterizedType) rawType).getRawType(); } Class clazz = (Class) rawType; // 这里要判断一下 topic if (isContainsTopic(topic, topicMapping.value())) { Object data = payload; if (clazz.isAssignableFrom(String.class)) data = new String(payload, Charset.defaultCharset());
else if (clazz.isAssignableFrom(MqttReq.class)) {
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/RedisConfig.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/serialize/RedisJsonSerializer.java // public class RedisJsonSerializer<T> implements RedisSerializer<T> { // // // private static final SerializerFeature[] features = { // SerializerFeature.WriteEnumUsingToString, // SerializerFeature.SortField, SerializerFeature.SkipTransientField, // SerializerFeature.WriteClassName }; // // private static final Feature[] DEFAULT_PARSER_FEATURE = { // Feature.AutoCloseSource, Feature.InternFieldNames, // Feature.AllowUnQuotedFieldNames, Feature.AllowSingleQuotes, // Feature.AllowArbitraryCommas, Feature.SortFeidFastMatch, // Feature.IgnoreNotMatch }; // // @Override // public byte[] serialize(Object t) throws SerializationException { // return JSON.toJSONBytes(t, features); // } // // @SuppressWarnings("unchecked") // @Override // public T deserialize(byte[] bytes) throws SerializationException { // if (bytes == null) // return null; // return (T) JSON.parse(bytes, DEFAULT_PARSER_FEATURE); // } // // // }
import com.jayqqaa12.jbase.spring.serialize.RedisJsonSerializer; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.net.UnknownHostException;
package com.jayqqaa12.jbase.spring.boot.config; /** * Created by 12 on 2017/6/1. */ @Configuration @ConditionalOnClass(RedisTemplate.class) public class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(new StringRedisSerializer());
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/serialize/RedisJsonSerializer.java // public class RedisJsonSerializer<T> implements RedisSerializer<T> { // // // private static final SerializerFeature[] features = { // SerializerFeature.WriteEnumUsingToString, // SerializerFeature.SortField, SerializerFeature.SkipTransientField, // SerializerFeature.WriteClassName }; // // private static final Feature[] DEFAULT_PARSER_FEATURE = { // Feature.AutoCloseSource, Feature.InternFieldNames, // Feature.AllowUnQuotedFieldNames, Feature.AllowSingleQuotes, // Feature.AllowArbitraryCommas, Feature.SortFeidFastMatch, // Feature.IgnoreNotMatch }; // // @Override // public byte[] serialize(Object t) throws SerializationException { // return JSON.toJSONBytes(t, features); // } // // @SuppressWarnings("unchecked") // @Override // public T deserialize(byte[] bytes) throws SerializationException { // if (bytes == null) // return null; // return (T) JSON.parse(bytes, DEFAULT_PARSER_FEATURE); // } // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/RedisConfig.java import com.jayqqaa12.jbase.spring.serialize.RedisJsonSerializer; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.net.UnknownHostException; package com.jayqqaa12.jbase.spring.boot.config; /** * Created by 12 on 2017/6/1. */ @Configuration @ConditionalOnClass(RedisTemplate.class) public class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); template.setKeySerializer(new StringRedisSerializer());
template.setDefaultSerializer(new RedisJsonSerializer<>());
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/exception/BusinessException.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/i18n/LocaleKit.java // public class LocaleKit { // // public static final String MSG_PREFIX = "msg."; // // private static final String PREFIX = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX; // private static final String SUFFIX = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_SUFFIX; // // private static PropertyPlaceholderHelper placeholderHelper = new PropertyPlaceholderHelper(PREFIX, SUFFIX); // private static Pattern PATTERN = Pattern.compile("[\\w]+([\\.][\\w\\d]+)+"); // private static Locale DEFAULT_LOCALE = Locale.CHINA; // private static final String[] PARAM_HOLDER = new String[]{"", "", "", "", "", ""}; // // private static MessageSource messageSource; // // // public static LocaleKit of(MessageSource messageSource) { // LocaleKit.messageSource = messageSource; // return new LocaleKit(); // } // // // public static String resolverOrGet(String message, Object... args) { // // if (PATTERN.matcher(message).matches()) { // return get(message, args); // } else { // return resolver(message, args); // } // } // // public static String resolverOrGet(int code, String message, Object... args) { // // if (StringUtils.isEmpty(message)) { // return resolverOrGet(MSG_PREFIX + code, args); // } else { // return resolverOrGet(message, args); // } // } // // // public static String resolver(String message, Object... args) { // // final Locale locale = getLocale(); // // return placeholderHelper.replacePlaceholders(message, s -> get(s, locale, args)); // } // // public static String get(String code, Object... args) { // // return get(code, getLocale(), args); // } // // // public static String get(String code, Locale locale, Object... args) { // // if (messageSource == null) return "messageSource not init "; // // // if (args == null || args.length == 0) { // args = PARAM_HOLDER; // } // // String msg = code; // try { // msg = messageSource.getMessage(code, args, locale); // } catch (NoSuchMessageException e) { // //Ignore // } // // return msg; // } // // // public static Locale getLocale() { // Locale locale = LocaleContextHolder.getLocale(); // // return locale == null ? DEFAULT_LOCALE : locale; // } // // // // public static Locale getLocale(HttpServletRequest request) { // // Locale locale = RequestContextUtils.getLocale(request); // // // // return locale == null ? DEFAULT_LOCALE : locale; // // } // // public static void setDefaultLocale(Locale locale){ // DEFAULT_LOCALE = locale; // } // }
import com.jayqqaa12.jbase.spring.mvc.i18n.LocaleKit;
package com.jayqqaa12.jbase.spring.exception; /** * Created by 12 on 2017/2/24. */ public class BusinessException extends RuntimeException { protected int code; protected String msg; public BusinessException(int code) {
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/i18n/LocaleKit.java // public class LocaleKit { // // public static final String MSG_PREFIX = "msg."; // // private static final String PREFIX = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_PREFIX; // private static final String SUFFIX = PlaceholderConfigurerSupport.DEFAULT_PLACEHOLDER_SUFFIX; // // private static PropertyPlaceholderHelper placeholderHelper = new PropertyPlaceholderHelper(PREFIX, SUFFIX); // private static Pattern PATTERN = Pattern.compile("[\\w]+([\\.][\\w\\d]+)+"); // private static Locale DEFAULT_LOCALE = Locale.CHINA; // private static final String[] PARAM_HOLDER = new String[]{"", "", "", "", "", ""}; // // private static MessageSource messageSource; // // // public static LocaleKit of(MessageSource messageSource) { // LocaleKit.messageSource = messageSource; // return new LocaleKit(); // } // // // public static String resolverOrGet(String message, Object... args) { // // if (PATTERN.matcher(message).matches()) { // return get(message, args); // } else { // return resolver(message, args); // } // } // // public static String resolverOrGet(int code, String message, Object... args) { // // if (StringUtils.isEmpty(message)) { // return resolverOrGet(MSG_PREFIX + code, args); // } else { // return resolverOrGet(message, args); // } // } // // // public static String resolver(String message, Object... args) { // // final Locale locale = getLocale(); // // return placeholderHelper.replacePlaceholders(message, s -> get(s, locale, args)); // } // // public static String get(String code, Object... args) { // // return get(code, getLocale(), args); // } // // // public static String get(String code, Locale locale, Object... args) { // // if (messageSource == null) return "messageSource not init "; // // // if (args == null || args.length == 0) { // args = PARAM_HOLDER; // } // // String msg = code; // try { // msg = messageSource.getMessage(code, args, locale); // } catch (NoSuchMessageException e) { // //Ignore // } // // return msg; // } // // // public static Locale getLocale() { // Locale locale = LocaleContextHolder.getLocale(); // // return locale == null ? DEFAULT_LOCALE : locale; // } // // // // public static Locale getLocale(HttpServletRequest request) { // // Locale locale = RequestContextUtils.getLocale(request); // // // // return locale == null ? DEFAULT_LOCALE : locale; // // } // // public static void setDefaultLocale(Locale locale){ // DEFAULT_LOCALE = locale; // } // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/exception/BusinessException.java import com.jayqqaa12.jbase.spring.mvc.i18n.LocaleKit; package com.jayqqaa12.jbase.spring.exception; /** * Created by 12 on 2017/2/24. */ public class BusinessException extends RuntimeException { protected int code; protected String msg; public BusinessException(int code) {
this(code, LocaleKit.MSG_PREFIX + code, null);
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // }
import com.github.benmanes.caffeine.cache.Caffeine; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.core.CacheConfig.CaffeineConfig; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
package com.jayqqaa12.jbase.cache.provider.caffeine; /** * @author jayqqaa12 */ public class CaffeineCacheProvider implements CacheProvider { private CacheConfig cacheConfig;
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java import com.github.benmanes.caffeine.cache.Caffeine; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.core.CacheConfig.CaffeineConfig; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; package com.jayqqaa12.jbase.cache.provider.caffeine; /** * @author jayqqaa12 */ public class CaffeineCacheProvider implements CacheProvider { private CacheConfig cacheConfig;
private Map<String, Cache> cacheMap = new HashMap<>();
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // }
import com.github.benmanes.caffeine.cache.Caffeine; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.core.CacheConfig.CaffeineConfig; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
package com.jayqqaa12.jbase.cache.provider.caffeine; /** * @author jayqqaa12 */ public class CaffeineCacheProvider implements CacheProvider { private CacheConfig cacheConfig; private Map<String, Cache> cacheMap = new HashMap<>();
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java import com.github.benmanes.caffeine.cache.Caffeine; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.core.CacheConfig.CaffeineConfig; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; package com.jayqqaa12.jbase.cache.provider.caffeine; /** * @author jayqqaa12 */ public class CaffeineCacheProvider implements CacheProvider { private CacheConfig cacheConfig; private Map<String, Cache> cacheMap = new HashMap<>();
private CaffeineConfig defualtConfig = new CaffeineConfig();
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // }
import com.github.benmanes.caffeine.cache.Caffeine; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.core.CacheConfig.CaffeineConfig; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
package com.jayqqaa12.jbase.cache.provider.caffeine; /** * @author jayqqaa12 */ public class CaffeineCacheProvider implements CacheProvider { private CacheConfig cacheConfig; private Map<String, Cache> cacheMap = new HashMap<>(); private CaffeineConfig defualtConfig = new CaffeineConfig(); @Override public void init(CacheConfig cacheConfig) { this.cacheConfig = cacheConfig; this.defualtConfig.setSize(10000); this.defualtConfig.setExpire(60 * 30); } @Override public Cache buildCache(String region, int expire) { CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); return newCache(region, config.getSize(), expire); } private Cache newCache(String region, int size, int expire) { return cacheMap.computeIfAbsent(region, v -> { Caffeine<Object, Object> caffeine = Caffeine.newBuilder(); caffeine = caffeine.maximumSize(size); if (expire > 0) { caffeine = caffeine.expireAfterWrite(expire, TimeUnit.SECONDS); }
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java // public interface CacheProvider { // // void init(CacheConfig cacheConfig); // // Cache buildCache(String region,int expire) ; // Cache buildCache(String region ) ; // // // void stop(); // // // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/caffeine/CaffeineCacheProvider.java import com.github.benmanes.caffeine.cache.Caffeine; import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; import com.jayqqaa12.jbase.cache.core.CacheConfig.CaffeineConfig; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.provider.CacheProvider; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; package com.jayqqaa12.jbase.cache.provider.caffeine; /** * @author jayqqaa12 */ public class CaffeineCacheProvider implements CacheProvider { private CacheConfig cacheConfig; private Map<String, Cache> cacheMap = new HashMap<>(); private CaffeineConfig defualtConfig = new CaffeineConfig(); @Override public void init(CacheConfig cacheConfig) { this.cacheConfig = cacheConfig; this.defualtConfig.setSize(10000); this.defualtConfig.setExpire(60 * 30); } @Override public Cache buildCache(String region, int expire) { CaffeineConfig config = cacheConfig.getCaffeineConfig().getOrDefault(region, defualtConfig); return newCache(region, config.getSize(), expire); } private Cache newCache(String region, int size, int expire) { return cacheMap.computeIfAbsent(region, v -> { Caffeine<Object, Object> caffeine = Caffeine.newBuilder(); caffeine = caffeine.maximumSize(size); if (expire > 0) { caffeine = caffeine.expireAfterWrite(expire, TimeUnit.SECONDS); }
com.github.benmanes.caffeine.cache.Cache<String, CacheObject> loadingCache = caffeine.build();
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/serialize/json/EnumDeserializer.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/db/BaseModel.java // @Data // @ToString(callSuper = true) // public abstract class BaseModel implements Serializable { // // @JSONField(serializeUsing = ToStringSerializer.class) // @Id // @JsonSerialize(using = JacksonToStringSerializer.class) // @TableId(type = IdType.ID_WORKER) // protected Long id; // // /** // * 加个方法方便链式调用 // * // * @param id // * @return // */ // public <T> T settId(Long id) { // this.id = id; // // return (T) this; // } // // // public enum Status { // CLOSE, OPEN; // // public static Status valueOf(int v) { // for (Status status : values()) { // if (status.ordinal() == v) return status; // } // throw new IllegalStateException(" error param enum for status"); // } // } // // public enum Deleted { // FALSE, TRUE; // // public static Deleted valueOf(int v) { // for (Deleted deleted : values()) { // if (deleted.ordinal() == v) return deleted; // } // throw new IllegalStateException(" error param enum for deleted"); // } // } // // }
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.jayqqaa12.jbase.spring.db.BaseModel; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Type;
package com.jayqqaa12.jbase.spring.serialize.json; /** * spring mvc 不能把字符串解析成 enum * 所以用这个转换一下字符串的 */ @Slf4j public class EnumDeserializer implements ObjectDeserializer { @Override public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { parser.parse(); String input = parser.getInput(); Integer value = JSON.parseObject(input) .getInteger((String) fieldName); if (value == null) return null;
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/db/BaseModel.java // @Data // @ToString(callSuper = true) // public abstract class BaseModel implements Serializable { // // @JSONField(serializeUsing = ToStringSerializer.class) // @Id // @JsonSerialize(using = JacksonToStringSerializer.class) // @TableId(type = IdType.ID_WORKER) // protected Long id; // // /** // * 加个方法方便链式调用 // * // * @param id // * @return // */ // public <T> T settId(Long id) { // this.id = id; // // return (T) this; // } // // // public enum Status { // CLOSE, OPEN; // // public static Status valueOf(int v) { // for (Status status : values()) { // if (status.ordinal() == v) return status; // } // throw new IllegalStateException(" error param enum for status"); // } // } // // public enum Deleted { // FALSE, TRUE; // // public static Deleted valueOf(int v) { // for (Deleted deleted : values()) { // if (deleted.ordinal() == v) return deleted; // } // throw new IllegalStateException(" error param enum for deleted"); // } // } // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/serialize/json/EnumDeserializer.java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.DefaultJSONParser; import com.alibaba.fastjson.parser.JSONToken; import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer; import com.jayqqaa12.jbase.spring.db.BaseModel; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Type; package com.jayqqaa12.jbase.spring.serialize.json; /** * spring mvc 不能把字符串解析成 enum * 所以用这个转换一下字符串的 */ @Slf4j public class EnumDeserializer implements ObjectDeserializer { @Override public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { parser.parse(); String input = parser.getInput(); Integer value = JSON.parseObject(input) .getInteger((String) fieldName); if (value == null) return null;
if (type == (BaseModel.Deleted.class)) {
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig;
package com.jayqqaa12.jbase.cache.provider; public interface CacheProvider { void init(CacheConfig cacheConfig);
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheConfig.java // @Data // public class CacheConfig { // // /** // * 缓存提供者 可选 // * <p> // * com.jayqqaa12.jbase.cache.provider.NullCacheProvider com.jayqqaa12.jbase.cache.provider.caffeine.CaffeineCacheProvider // * com.jayqqaa12.jbase.cache.provider.lettuce.LettuceCacheProvider // * <p> // * 根据加入顺序确定缓存级别 可自定义CacheProvider 进行扩展 // */ // private List<String> providerClassList = new ArrayList<>(); // // private String cacheSerializerClass = "com.jayqqaa12.jbase.cache.serializer.FastJsonCacheSerializer"; // // /** // * 自动加载的线程数 // */ // private int autoLoadThreadCount = 5; // // // 具体的缓存中间件相关配置 // // private String redisMode = CacheConst.REDIS_MODE_SINGLE; // // private LettuceConfig lettuceConfig = new LettuceConfig(); // // private NotifyConfig notifyConfig = new NotifyConfig(); // // private Map<String, CaffeineConfig> caffeineConfig = new HashMap<>(); // // @Data // public static class CaffeineConfig { // // private int size = 10_000; // private int expire = 0; // // } // // @Data // public static class NotifyConfig { // // private String notifyClass = "com.jayqqaa12.jbase.cache.notify.NullNotify"; // private String notifyTopic = CacheConst.DEFAULT_TOPIC; // // private String host; // private String groupId = CacheConst.DEFAULT_TOPIC; // // // } // // // @Data // public class LettuceConfig { // // /** // * 命名空间 可以用来区分不同 项目 // */ // private String namespace = CacheConst.NAMESPACE; // /** // * single 单点 cluster 集群 // */ // private String schema = CacheConst.REDIS_MODE_SINGLE; // private String hosts = "127.0.0.1:6379"; // private String password = ""; // private int database = 0; // private int maxTotal = 100; // private int maxIdle = 10; // private int minIdle = 10; // private int timeout = 10000; // private int clusterTopologyRefresh = 3000; // // // } // // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/CacheProvider.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheConfig; package com.jayqqaa12.jbase.cache.provider; public interface CacheProvider { void init(CacheConfig cacheConfig);
Cache buildCache(String region,int expire) ;
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/db/BaseModel.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/serialize/json/JacksonToStringSerializer.java // public class JacksonToStringSerializer extends JsonSerializer<Object> { // // @Override // public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // jgen.writeString(value.toString()); // } // }
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.ToStringSerializer; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.jayqqaa12.jbase.spring.serialize.json.JacksonToStringSerializer; import lombok.Data; import lombok.ToString; import org.springframework.data.annotation.Id; import java.io.Serializable;
package com.jayqqaa12.jbase.spring.db; /** * 数据库表的基本类 * Created by 12 on 2018/1/23. */ @Data @ToString(callSuper = true) public abstract class BaseModel implements Serializable { @JSONField(serializeUsing = ToStringSerializer.class) @Id
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/serialize/json/JacksonToStringSerializer.java // public class JacksonToStringSerializer extends JsonSerializer<Object> { // // @Override // public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // jgen.writeString(value.toString()); // } // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/db/BaseModel.java import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.ToStringSerializer; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.jayqqaa12.jbase.spring.serialize.json.JacksonToStringSerializer; import lombok.Data; import lombok.ToString; import org.springframework.data.annotation.Id; import java.io.Serializable; package com.jayqqaa12.jbase.spring.db; /** * 数据库表的基本类 * Created by 12 on 2018/1/23. */ @Data @ToString(callSuper = true) public abstract class BaseModel implements Serializable { @JSONField(serializeUsing = ToStringSerializer.class) @Id
@JsonSerialize(using = JacksonToStringSerializer.class)
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mqtt/protocol/MqttResp.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/RespCode.java // public abstract class RespCode { // // public static final int SUCCESS = 200; // | 成功 | // // // // 1000-1199 内部异常 服务器相关错误 // public static final int SERVER_ERROR = 1000; // | 服务器内部异常 或未指定异常| // public static final int GATEWAY_ERROR=1100; // |网关访问异常| // public static final int DB_SQL_ERROR= 1101; // sql执行异常 // public static final int PARAM_ERROR=1102; //参数异常 // public static final int RETRY_ERROR =1103; // 重试异常 // public static final int RETRY_LOCK_ERROR=1104;// 幂等性异常 // public static final int SERVER_BLOCK=1105;//服务限流 // public static final int SERVER_DEGRADE=1106;//服务降级 // // // // 1300-1399 请求相关异常 // public static final int RESOURCE_NOT_FOUND = 1300; // | 请求没有被找到 | // public static final int REQ_METHOD_NOT_ALLOWED = 1301; // | 方法不被允许 | // public static final int REQ_MEDIA_UNSUPPORTED = 1302; // | 不支持的媒体类型 | // public static final int BAD_REQ = 1303; // | BAD REQUEST | // public static final int REQ_METHOD_GET = 1304; // | 请求必须是GET请求 | // public static final int REQ_METHOD_POST = 1305; // | 请求必须是POST请求 | // public static final int REQ_METHOD_PUT = 1306; // | 请求必须是PUT请求 | // public static final int REQ_METHOD_DELETE = 1307; // | 请求必须是DELETE请求 | // // public static final int REQ_JSON_FORMAT_ERROR=1310;// JSON 解析异常 // // // // 引用外部 SDK 相关错误 1500-1599 // public static final int INNER__CONTENT_SCAN_ERROR = 1500; //没有配置图片检测类型 // // // // // 1600-1999 内部模块异常 // // public static final int AUTH_ERROR=1600; // |没有权限| // public static final int AUTH_USER_NOT_FOUND=1601; //用户不存在 // public static final int AUTH_USER_LOGIN_ERROR=1602; //用户名或密码错误 // // public static final int AUTH_TOKEN_EXPIRED=1603; //TOKEN 过期 // public static final int AUTH_TOKEN_SIGN_ERROR=1604;//TOKEN 签名异常 // // // // // public static final int VALIDATE_CODE_VALIDATE_ERROR =1700; //验证码错误 // public static final int VALIDATE_CODE_PAST_DUE =1701; //验证码过期 // // public static final int SMS_ERROR=1702; //发送失败 // // public static final int SMS_LIMIT=1703; //超过限制 // public static final int SMS_PHONE_ERROR=1704;//手机号错误 // // // // //2000+ 业务模块自定义异常 继承这个类 最好定义在一个公共模块里防止 冲突 // // // // // }
import com.jayqqaa12.jbase.spring.mvc.RespCode; import lombok.Data;
package com.jayqqaa12.jbase.spring.mqtt.protocol; @Data public class MqttResp { /** * 请求序列 客户端传递用来标示 返回的消息是哪次请求 */ private String reqNo; /** * 返回码 * */
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mvc/RespCode.java // public abstract class RespCode { // // public static final int SUCCESS = 200; // | 成功 | // // // // 1000-1199 内部异常 服务器相关错误 // public static final int SERVER_ERROR = 1000; // | 服务器内部异常 或未指定异常| // public static final int GATEWAY_ERROR=1100; // |网关访问异常| // public static final int DB_SQL_ERROR= 1101; // sql执行异常 // public static final int PARAM_ERROR=1102; //参数异常 // public static final int RETRY_ERROR =1103; // 重试异常 // public static final int RETRY_LOCK_ERROR=1104;// 幂等性异常 // public static final int SERVER_BLOCK=1105;//服务限流 // public static final int SERVER_DEGRADE=1106;//服务降级 // // // // 1300-1399 请求相关异常 // public static final int RESOURCE_NOT_FOUND = 1300; // | 请求没有被找到 | // public static final int REQ_METHOD_NOT_ALLOWED = 1301; // | 方法不被允许 | // public static final int REQ_MEDIA_UNSUPPORTED = 1302; // | 不支持的媒体类型 | // public static final int BAD_REQ = 1303; // | BAD REQUEST | // public static final int REQ_METHOD_GET = 1304; // | 请求必须是GET请求 | // public static final int REQ_METHOD_POST = 1305; // | 请求必须是POST请求 | // public static final int REQ_METHOD_PUT = 1306; // | 请求必须是PUT请求 | // public static final int REQ_METHOD_DELETE = 1307; // | 请求必须是DELETE请求 | // // public static final int REQ_JSON_FORMAT_ERROR=1310;// JSON 解析异常 // // // // 引用外部 SDK 相关错误 1500-1599 // public static final int INNER__CONTENT_SCAN_ERROR = 1500; //没有配置图片检测类型 // // // // // 1600-1999 内部模块异常 // // public static final int AUTH_ERROR=1600; // |没有权限| // public static final int AUTH_USER_NOT_FOUND=1601; //用户不存在 // public static final int AUTH_USER_LOGIN_ERROR=1602; //用户名或密码错误 // // public static final int AUTH_TOKEN_EXPIRED=1603; //TOKEN 过期 // public static final int AUTH_TOKEN_SIGN_ERROR=1604;//TOKEN 签名异常 // // // // // public static final int VALIDATE_CODE_VALIDATE_ERROR =1700; //验证码错误 // public static final int VALIDATE_CODE_PAST_DUE =1701; //验证码过期 // // public static final int SMS_ERROR=1702; //发送失败 // // public static final int SMS_LIMIT=1703; //超过限制 // public static final int SMS_PHONE_ERROR=1704;//手机号错误 // // // // //2000+ 业务模块自定义异常 继承这个类 最好定义在一个公共模块里防止 冲突 // // // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/mqtt/protocol/MqttResp.java import com.jayqqaa12.jbase.spring.mvc.RespCode; import lombok.Data; package com.jayqqaa12.jbase.spring.mqtt.protocol; @Data public class MqttResp { /** * 请求序列 客户端传递用来标示 返回的消息是哪次请求 */ private String reqNo; /** * 返回码 * */
private int code= RespCode.SUCCESS;
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCache.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.util.CacheException;
package com.jayqqaa12.jbase.cache.provider; public class NullCache implements Cache { @Override
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCache.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.util.CacheException; package com.jayqqaa12.jbase.cache.provider; public class NullCache implements Cache { @Override
public CacheObject get(String key) throws CacheException {
jayqqaa12/jbase
jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCache.java
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // }
import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.util.CacheException;
package com.jayqqaa12.jbase.cache.provider; public class NullCache implements Cache { @Override
// Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/Cache.java // public interface Cache { // // CacheObject get(String key) throws CacheException; // // // void set(String key, CacheObject value) throws CacheException; // // // void set(String key, CacheObject value, int expire) throws CacheException; // // void delete(String key) throws CacheException; // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/core/CacheObject.java // @Data // @Builder // @AllArgsConstructor // @NoArgsConstructor // public class CacheObject<T> implements Serializable { // // private String region; // private String key; // private T value; // // private long loadTime; // // // /** // * 过期时长 单位:秒 // */ // private int expire; // // public boolean canAutoLoad() { // // return // (System.currentTimeMillis() - loadTime > expire * 900); // } // // // public boolean isEmpty() { // return value == null; // } // // // } // // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/util/CacheException.java // public class CacheException extends RuntimeException { // // private static final long serialVersionUID = -5112528854998647834L; // // public CacheException(String s) { // super(s); // } // // public CacheException(String s, Throwable e) { // super(s, e); // } // // public CacheException(Throwable e) { // super(e); // } // // } // Path: jbase-cache/src/main/java/com/jayqqaa12/jbase/cache/provider/NullCache.java import com.jayqqaa12.jbase.cache.core.Cache; import com.jayqqaa12.jbase.cache.core.CacheObject; import com.jayqqaa12.jbase.cache.util.CacheException; package com.jayqqaa12.jbase.cache.provider; public class NullCache implements Cache { @Override
public CacheObject get(String key) throws CacheException {
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/EnableWeb.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MvcConfig.java // @Configuration // public class MvcConfig implements WebMvcConfigurer { // // //fastjson 出现不兼容的情况 改用 jackson // // @Bean // // public FastJsonHttpMessageConverter fastJsonHttpMessageConverters() { // // // // return new FastJsonConverter(); // // } // // @Override // // public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { // // // // converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof MappingJackson2HttpMessageConverter); // // // // converters.add(fastJsonHttpMessageConverters()); // // } // // // @Bean // public CustomExceptionHandler customExceptionHandler() { // return new CustomExceptionHandler(); // } // // @Bean // public GlobalExceptionHandler globalExceptionHandler() { // return new GlobalExceptionHandler(); // } // // // @Bean // public LocaleResolver localeResolver() { // CookieLocaleResolver resolver = new CookieLocaleResolver(); // resolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); // resolver.setCookieName("language"); // resolver.setCookieMaxAge(3600); // return resolver; // } // // @Bean // public LocaleChangeInterceptor localeChangeInterceptor() { // LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor(); // interceptor.setParamName("lang"); // return interceptor; // } // // // @Bean // public HeaderLocaleChangeInterceptor headerLocaleChangeInterceptor() { // return new HeaderLocaleChangeInterceptor(); // } // // @Bean // public LocaleKit localeKit(MessageSource messageSource, // @Value("${config.lang:zh_CN}") Locale locale) { // // LocaleKit kit = LocaleKit.of(messageSource); // LocaleKit.setDefaultLocale(locale); // return kit; // } // // // @Bean // public FilterRegistrationBean hiddenHttpMethodFilter() { // FilterRegistrationBean registration = new FilterRegistrationBean(new HiddenHttpMethodFilter()); // registration.addUrlPatterns("/"); // return registration; // } // // // public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // argumentResolvers.add(new PageableHandlerMethodArgumentResolver()); // } // // // @Bean // // public HttpPutFormContentFilter putFilter() { // // return new HttpPutFormContentFilter(); // // } // // // @Override // // public void addCorsMappings(CorsRegistry registry) { // // registry.addMapping("/**").allowedOrigins("*") // // .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") // // .allowCredentials(false).maxAge(3600); // // } // // // @Override // public void addInterceptors(InterceptorRegistry registry) { // //以后改为权限控制 由api-gateway控制 // // registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**"); // registry.addInterceptor(localeChangeInterceptor()).addPathPatterns("/**"); // registry.addInterceptor(headerLocaleChangeInterceptor()).addPathPatterns("/**"); // // } // // // }
import com.jayqqaa12.jbase.spring.boot.config.MvcConfig; import org.springframework.context.annotation.Import; import java.lang.annotation.*;
package com.jayqqaa12.jbase.spring.boot; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/config/MvcConfig.java // @Configuration // public class MvcConfig implements WebMvcConfigurer { // // //fastjson 出现不兼容的情况 改用 jackson // // @Bean // // public FastJsonHttpMessageConverter fastJsonHttpMessageConverters() { // // // // return new FastJsonConverter(); // // } // // @Override // // public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { // // // // converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof MappingJackson2HttpMessageConverter); // // // // converters.add(fastJsonHttpMessageConverters()); // // } // // // @Bean // public CustomExceptionHandler customExceptionHandler() { // return new CustomExceptionHandler(); // } // // @Bean // public GlobalExceptionHandler globalExceptionHandler() { // return new GlobalExceptionHandler(); // } // // // @Bean // public LocaleResolver localeResolver() { // CookieLocaleResolver resolver = new CookieLocaleResolver(); // resolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); // resolver.setCookieName("language"); // resolver.setCookieMaxAge(3600); // return resolver; // } // // @Bean // public LocaleChangeInterceptor localeChangeInterceptor() { // LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor(); // interceptor.setParamName("lang"); // return interceptor; // } // // // @Bean // public HeaderLocaleChangeInterceptor headerLocaleChangeInterceptor() { // return new HeaderLocaleChangeInterceptor(); // } // // @Bean // public LocaleKit localeKit(MessageSource messageSource, // @Value("${config.lang:zh_CN}") Locale locale) { // // LocaleKit kit = LocaleKit.of(messageSource); // LocaleKit.setDefaultLocale(locale); // return kit; // } // // // @Bean // public FilterRegistrationBean hiddenHttpMethodFilter() { // FilterRegistrationBean registration = new FilterRegistrationBean(new HiddenHttpMethodFilter()); // registration.addUrlPatterns("/"); // return registration; // } // // // public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // argumentResolvers.add(new PageableHandlerMethodArgumentResolver()); // } // // // @Bean // // public HttpPutFormContentFilter putFilter() { // // return new HttpPutFormContentFilter(); // // } // // // @Override // // public void addCorsMappings(CorsRegistry registry) { // // registry.addMapping("/**").allowedOrigins("*") // // .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") // // .allowCredentials(false).maxAge(3600); // // } // // // @Override // public void addInterceptors(InterceptorRegistry registry) { // //以后改为权限控制 由api-gateway控制 // // registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**"); // registry.addInterceptor(localeChangeInterceptor()).addPathPatterns("/**"); // registry.addInterceptor(headerLocaleChangeInterceptor()).addPathPatterns("/**"); // // } // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/boot/EnableWeb.java import com.jayqqaa12.jbase.spring.boot.config.MvcConfig; import org.springframework.context.annotation.Import; import java.lang.annotation.*; package com.jayqqaa12.jbase.spring.boot; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({
MvcConfig.class,
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FiegnConfig.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FeignReqInterceptor.java // public class FeignReqInterceptor implements RequestInterceptor { // // @Override // public void apply(RequestTemplate requestTemplate) { // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder // .getRequestAttributes(); // if (attributes == null) { // return; // } // HttpServletRequest request = attributes.getRequest(); // if (request == null) { // return; // } // Enumeration<String> headerNames = request.getHeaderNames(); // if (headerNames != null) { // while (headerNames.hasMoreElements()) { // String name = headerNames.nextElement(); // String values = request.getHeader(name); // requestTemplate.header(name, values); // } // } // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/ResponseHttpMessageConverter.java // public class ResponseHttpMessageConverter extends AbstractHttpMessageConverter<Object> { // // @Override // protected boolean supports(Class<?> clazz) { // return true; // } // // @Override // protected boolean canRead(MediaType mediaType) { // return true; // } // // @Override // protected boolean canWrite(MediaType mediaType) { // return false; // } // // @Override // protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { // // if (clazz.isAssignableFrom(byte[].class)||clazz.isAssignableFrom(Byte[].class)) { // return Util.toByteArray(inputMessage.getBody()); // } // String body = Util.toString(new InputStreamReader(inputMessage.getBody())); // // // JSONObject obj = JSON.parseObject(body); // // Integer code = obj.getInteger("code"); // // if (code != null && code != RespCode.SUCCESS) { // // throw new BusinessException(code); // // } // // return JSON.parseObject(body, clazz); // // } // // @Override // protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // // // } // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/CustomErrorDecoder.java // public class CustomErrorDecoder implements ErrorDecoder { // // @Override // public Exception decode(String s, Response response) { // try { // if (response.body() != null) { // String body = Util.toString(response.body().asReader()); // Resp req = JSON.parseObject(body, Resp.class); // if (req.getCode() != RespCode.SUCCESS) { // return new BusinessException(req.getCode(), req.getMsg(), null); // } // } // } catch (IOException e) { // return e; // } // return new Exception("UNKOWN ERROR"); // } // // // }
import com.jayqqaa12.jbase.spring.feign.FeignReqInterceptor; import com.jayqqaa12.jbase.spring.feign.ResponseHttpMessageConverter; import com.jayqqaa12.jbase.spring.feign.CustomErrorDecoder; import feign.*; import feign.codec.Decoder; import feign.codec.ErrorDecoder; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.SpringDecoder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration;
package com.jayqqaa12.jbase.spring.feign; /** * Created by 12 on 2017/12/2. */ @Configuration @ConditionalOnClass({Feign.class}) public class FiegnConfig { @Bean public ErrorDecoder errorDecoder() {
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FeignReqInterceptor.java // public class FeignReqInterceptor implements RequestInterceptor { // // @Override // public void apply(RequestTemplate requestTemplate) { // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder // .getRequestAttributes(); // if (attributes == null) { // return; // } // HttpServletRequest request = attributes.getRequest(); // if (request == null) { // return; // } // Enumeration<String> headerNames = request.getHeaderNames(); // if (headerNames != null) { // while (headerNames.hasMoreElements()) { // String name = headerNames.nextElement(); // String values = request.getHeader(name); // requestTemplate.header(name, values); // } // } // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/ResponseHttpMessageConverter.java // public class ResponseHttpMessageConverter extends AbstractHttpMessageConverter<Object> { // // @Override // protected boolean supports(Class<?> clazz) { // return true; // } // // @Override // protected boolean canRead(MediaType mediaType) { // return true; // } // // @Override // protected boolean canWrite(MediaType mediaType) { // return false; // } // // @Override // protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { // // if (clazz.isAssignableFrom(byte[].class)||clazz.isAssignableFrom(Byte[].class)) { // return Util.toByteArray(inputMessage.getBody()); // } // String body = Util.toString(new InputStreamReader(inputMessage.getBody())); // // // JSONObject obj = JSON.parseObject(body); // // Integer code = obj.getInteger("code"); // // if (code != null && code != RespCode.SUCCESS) { // // throw new BusinessException(code); // // } // // return JSON.parseObject(body, clazz); // // } // // @Override // protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // // // } // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/CustomErrorDecoder.java // public class CustomErrorDecoder implements ErrorDecoder { // // @Override // public Exception decode(String s, Response response) { // try { // if (response.body() != null) { // String body = Util.toString(response.body().asReader()); // Resp req = JSON.parseObject(body, Resp.class); // if (req.getCode() != RespCode.SUCCESS) { // return new BusinessException(req.getCode(), req.getMsg(), null); // } // } // } catch (IOException e) { // return e; // } // return new Exception("UNKOWN ERROR"); // } // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FiegnConfig.java import com.jayqqaa12.jbase.spring.feign.FeignReqInterceptor; import com.jayqqaa12.jbase.spring.feign.ResponseHttpMessageConverter; import com.jayqqaa12.jbase.spring.feign.CustomErrorDecoder; import feign.*; import feign.codec.Decoder; import feign.codec.ErrorDecoder; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.SpringDecoder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; package com.jayqqaa12.jbase.spring.feign; /** * Created by 12 on 2017/12/2. */ @Configuration @ConditionalOnClass({Feign.class}) public class FiegnConfig { @Bean public ErrorDecoder errorDecoder() {
return new CustomErrorDecoder();
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FiegnConfig.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FeignReqInterceptor.java // public class FeignReqInterceptor implements RequestInterceptor { // // @Override // public void apply(RequestTemplate requestTemplate) { // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder // .getRequestAttributes(); // if (attributes == null) { // return; // } // HttpServletRequest request = attributes.getRequest(); // if (request == null) { // return; // } // Enumeration<String> headerNames = request.getHeaderNames(); // if (headerNames != null) { // while (headerNames.hasMoreElements()) { // String name = headerNames.nextElement(); // String values = request.getHeader(name); // requestTemplate.header(name, values); // } // } // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/ResponseHttpMessageConverter.java // public class ResponseHttpMessageConverter extends AbstractHttpMessageConverter<Object> { // // @Override // protected boolean supports(Class<?> clazz) { // return true; // } // // @Override // protected boolean canRead(MediaType mediaType) { // return true; // } // // @Override // protected boolean canWrite(MediaType mediaType) { // return false; // } // // @Override // protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { // // if (clazz.isAssignableFrom(byte[].class)||clazz.isAssignableFrom(Byte[].class)) { // return Util.toByteArray(inputMessage.getBody()); // } // String body = Util.toString(new InputStreamReader(inputMessage.getBody())); // // // JSONObject obj = JSON.parseObject(body); // // Integer code = obj.getInteger("code"); // // if (code != null && code != RespCode.SUCCESS) { // // throw new BusinessException(code); // // } // // return JSON.parseObject(body, clazz); // // } // // @Override // protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // // // } // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/CustomErrorDecoder.java // public class CustomErrorDecoder implements ErrorDecoder { // // @Override // public Exception decode(String s, Response response) { // try { // if (response.body() != null) { // String body = Util.toString(response.body().asReader()); // Resp req = JSON.parseObject(body, Resp.class); // if (req.getCode() != RespCode.SUCCESS) { // return new BusinessException(req.getCode(), req.getMsg(), null); // } // } // } catch (IOException e) { // return e; // } // return new Exception("UNKOWN ERROR"); // } // // // }
import com.jayqqaa12.jbase.spring.feign.FeignReqInterceptor; import com.jayqqaa12.jbase.spring.feign.ResponseHttpMessageConverter; import com.jayqqaa12.jbase.spring.feign.CustomErrorDecoder; import feign.*; import feign.codec.Decoder; import feign.codec.ErrorDecoder; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.SpringDecoder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration;
package com.jayqqaa12.jbase.spring.feign; /** * Created by 12 on 2017/12/2. */ @Configuration @ConditionalOnClass({Feign.class}) public class FiegnConfig { @Bean public ErrorDecoder errorDecoder() { return new CustomErrorDecoder(); } @Bean public Decoder feignDecoder() { return new ResponseEntityDecoder(
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FeignReqInterceptor.java // public class FeignReqInterceptor implements RequestInterceptor { // // @Override // public void apply(RequestTemplate requestTemplate) { // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder // .getRequestAttributes(); // if (attributes == null) { // return; // } // HttpServletRequest request = attributes.getRequest(); // if (request == null) { // return; // } // Enumeration<String> headerNames = request.getHeaderNames(); // if (headerNames != null) { // while (headerNames.hasMoreElements()) { // String name = headerNames.nextElement(); // String values = request.getHeader(name); // requestTemplate.header(name, values); // } // } // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/ResponseHttpMessageConverter.java // public class ResponseHttpMessageConverter extends AbstractHttpMessageConverter<Object> { // // @Override // protected boolean supports(Class<?> clazz) { // return true; // } // // @Override // protected boolean canRead(MediaType mediaType) { // return true; // } // // @Override // protected boolean canWrite(MediaType mediaType) { // return false; // } // // @Override // protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { // // if (clazz.isAssignableFrom(byte[].class)||clazz.isAssignableFrom(Byte[].class)) { // return Util.toByteArray(inputMessage.getBody()); // } // String body = Util.toString(new InputStreamReader(inputMessage.getBody())); // // // JSONObject obj = JSON.parseObject(body); // // Integer code = obj.getInteger("code"); // // if (code != null && code != RespCode.SUCCESS) { // // throw new BusinessException(code); // // } // // return JSON.parseObject(body, clazz); // // } // // @Override // protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // // // } // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/CustomErrorDecoder.java // public class CustomErrorDecoder implements ErrorDecoder { // // @Override // public Exception decode(String s, Response response) { // try { // if (response.body() != null) { // String body = Util.toString(response.body().asReader()); // Resp req = JSON.parseObject(body, Resp.class); // if (req.getCode() != RespCode.SUCCESS) { // return new BusinessException(req.getCode(), req.getMsg(), null); // } // } // } catch (IOException e) { // return e; // } // return new Exception("UNKOWN ERROR"); // } // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FiegnConfig.java import com.jayqqaa12.jbase.spring.feign.FeignReqInterceptor; import com.jayqqaa12.jbase.spring.feign.ResponseHttpMessageConverter; import com.jayqqaa12.jbase.spring.feign.CustomErrorDecoder; import feign.*; import feign.codec.Decoder; import feign.codec.ErrorDecoder; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.SpringDecoder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; package com.jayqqaa12.jbase.spring.feign; /** * Created by 12 on 2017/12/2. */ @Configuration @ConditionalOnClass({Feign.class}) public class FiegnConfig { @Bean public ErrorDecoder errorDecoder() { return new CustomErrorDecoder(); } @Bean public Decoder feignDecoder() { return new ResponseEntityDecoder(
new SpringDecoder(() -> new HttpMessageConverters(new ResponseHttpMessageConverter())));
jayqqaa12/jbase
jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FiegnConfig.java
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FeignReqInterceptor.java // public class FeignReqInterceptor implements RequestInterceptor { // // @Override // public void apply(RequestTemplate requestTemplate) { // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder // .getRequestAttributes(); // if (attributes == null) { // return; // } // HttpServletRequest request = attributes.getRequest(); // if (request == null) { // return; // } // Enumeration<String> headerNames = request.getHeaderNames(); // if (headerNames != null) { // while (headerNames.hasMoreElements()) { // String name = headerNames.nextElement(); // String values = request.getHeader(name); // requestTemplate.header(name, values); // } // } // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/ResponseHttpMessageConverter.java // public class ResponseHttpMessageConverter extends AbstractHttpMessageConverter<Object> { // // @Override // protected boolean supports(Class<?> clazz) { // return true; // } // // @Override // protected boolean canRead(MediaType mediaType) { // return true; // } // // @Override // protected boolean canWrite(MediaType mediaType) { // return false; // } // // @Override // protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { // // if (clazz.isAssignableFrom(byte[].class)||clazz.isAssignableFrom(Byte[].class)) { // return Util.toByteArray(inputMessage.getBody()); // } // String body = Util.toString(new InputStreamReader(inputMessage.getBody())); // // // JSONObject obj = JSON.parseObject(body); // // Integer code = obj.getInteger("code"); // // if (code != null && code != RespCode.SUCCESS) { // // throw new BusinessException(code); // // } // // return JSON.parseObject(body, clazz); // // } // // @Override // protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // // // } // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/CustomErrorDecoder.java // public class CustomErrorDecoder implements ErrorDecoder { // // @Override // public Exception decode(String s, Response response) { // try { // if (response.body() != null) { // String body = Util.toString(response.body().asReader()); // Resp req = JSON.parseObject(body, Resp.class); // if (req.getCode() != RespCode.SUCCESS) { // return new BusinessException(req.getCode(), req.getMsg(), null); // } // } // } catch (IOException e) { // return e; // } // return new Exception("UNKOWN ERROR"); // } // // // }
import com.jayqqaa12.jbase.spring.feign.FeignReqInterceptor; import com.jayqqaa12.jbase.spring.feign.ResponseHttpMessageConverter; import com.jayqqaa12.jbase.spring.feign.CustomErrorDecoder; import feign.*; import feign.codec.Decoder; import feign.codec.ErrorDecoder; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.SpringDecoder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration;
package com.jayqqaa12.jbase.spring.feign; /** * Created by 12 on 2017/12/2. */ @Configuration @ConditionalOnClass({Feign.class}) public class FiegnConfig { @Bean public ErrorDecoder errorDecoder() { return new CustomErrorDecoder(); } @Bean public Decoder feignDecoder() { return new ResponseEntityDecoder( new SpringDecoder(() -> new HttpMessageConverters(new ResponseHttpMessageConverter()))); } //feign请求把 header带上 @Bean public RequestInterceptor headerInterceptor() {
// Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FeignReqInterceptor.java // public class FeignReqInterceptor implements RequestInterceptor { // // @Override // public void apply(RequestTemplate requestTemplate) { // ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder // .getRequestAttributes(); // if (attributes == null) { // return; // } // HttpServletRequest request = attributes.getRequest(); // if (request == null) { // return; // } // Enumeration<String> headerNames = request.getHeaderNames(); // if (headerNames != null) { // while (headerNames.hasMoreElements()) { // String name = headerNames.nextElement(); // String values = request.getHeader(name); // requestTemplate.header(name, values); // } // } // } // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/ResponseHttpMessageConverter.java // public class ResponseHttpMessageConverter extends AbstractHttpMessageConverter<Object> { // // @Override // protected boolean supports(Class<?> clazz) { // return true; // } // // @Override // protected boolean canRead(MediaType mediaType) { // return true; // } // // @Override // protected boolean canWrite(MediaType mediaType) { // return false; // } // // @Override // protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { // // if (clazz.isAssignableFrom(byte[].class)||clazz.isAssignableFrom(Byte[].class)) { // return Util.toByteArray(inputMessage.getBody()); // } // String body = Util.toString(new InputStreamReader(inputMessage.getBody())); // // // JSONObject obj = JSON.parseObject(body); // // Integer code = obj.getInteger("code"); // // if (code != null && code != RespCode.SUCCESS) { // // throw new BusinessException(code); // // } // // return JSON.parseObject(body, clazz); // // } // // @Override // protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { // // // } // // // // // } // // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/CustomErrorDecoder.java // public class CustomErrorDecoder implements ErrorDecoder { // // @Override // public Exception decode(String s, Response response) { // try { // if (response.body() != null) { // String body = Util.toString(response.body().asReader()); // Resp req = JSON.parseObject(body, Resp.class); // if (req.getCode() != RespCode.SUCCESS) { // return new BusinessException(req.getCode(), req.getMsg(), null); // } // } // } catch (IOException e) { // return e; // } // return new Exception("UNKOWN ERROR"); // } // // // } // Path: jbase-spring/src/main/java/com/jayqqaa12/jbase/spring/feign/FiegnConfig.java import com.jayqqaa12.jbase.spring.feign.FeignReqInterceptor; import com.jayqqaa12.jbase.spring.feign.ResponseHttpMessageConverter; import com.jayqqaa12.jbase.spring.feign.CustomErrorDecoder; import feign.*; import feign.codec.Decoder; import feign.codec.ErrorDecoder; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.cloud.openfeign.support.SpringDecoder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; package com.jayqqaa12.jbase.spring.feign; /** * Created by 12 on 2017/12/2. */ @Configuration @ConditionalOnClass({Feign.class}) public class FiegnConfig { @Bean public ErrorDecoder errorDecoder() { return new CustomErrorDecoder(); } @Bean public Decoder feignDecoder() { return new ResponseEntityDecoder( new SpringDecoder(() -> new HttpMessageConverters(new ResponseHttpMessageConverter()))); } //feign请求把 header带上 @Bean public RequestInterceptor headerInterceptor() {
return new FeignReqInterceptor();
suninformation/ymate-payment-v2
ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/base/WxPayAccountMeta.java
// Path: ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/request/WxPaySandboxSignKey.java // public class WxPaySandboxSignKey extends WxPayBaseRequest<WxPaySandboxSignKey.Response> { // // public WxPaySandboxSignKey(WxPayAccountMeta accountMeta) { // super(accountMeta); // } // // @Override // protected String __doGetRequestURL() { // return "https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey"; // } // // @Override // protected Response __doParseResponse(IHttpResponse httpResponse) throws Exception { // return new Response(httpResponse.getContent()); // } // // /** // * 获取验签环境密钥响应 // */ // public static class Response extends WxPayBaseResponse { // // private String signkey; // // public Response(String protocol) throws Exception { // super(protocol); // this.signkey = BlurObject.bind(this.getResponseParams().get("sandbox_signkey")).toStringValue(); // } // // public String signkey() { // return signkey; // } // } // }
import net.ymate.framework.commons.HttpClientHelper; import net.ymate.payment.wxpay.request.WxPaySandboxSignKey; import net.ymate.platform.core.util.RuntimeUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import java.io.Serializable; import java.net.URL;
/* * Copyright 2007-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.wxpay.base; /** * @author 刘镇 (suninformation@163.com) on 17/6/15 下午1:24 * @version 1.0 */ public class WxPayAccountMeta implements Serializable { private static final Log _LOG = LogFactory.getLog(WxPayAccountMeta.class); /** * 公众帐号APP_ID */ private String appId; /** * 商户号 */ private String mchId; /** * 商号密钥 */ private String mchKey; /** * 证书文件路径 */ private String certFilePath; /** * 是否开启沙箱测试模式, 默认值: false */ private boolean sandboxEnabled; /** * 获取沙箱测试模式下的接口URL地址前缀, 默认值: sandboxnew */ private String sandboxPrefix; private SSLConnectionSocketFactory connectionSocketFactory; /** * 异步通知URL */ private String notifyUrl; public WxPayAccountMeta(String appId, String mchId, String mchKey, String notifyUrl) { this.appId = appId; this.mchId = mchId; this.mchKey = mchKey; this.notifyUrl = notifyUrl; } public WxPayAccountMeta(String appId, String mchId, String mchKey, String certFilePath, String notifyUrl) { this.appId = appId; this.mchId = mchId; this.mchKey = mchKey; this.certFilePath = certFilePath; this.notifyUrl = notifyUrl; } private void __doGetSandboxSignKeyIfNeed() { if (sandboxEnabled) { try {
// Path: ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/request/WxPaySandboxSignKey.java // public class WxPaySandboxSignKey extends WxPayBaseRequest<WxPaySandboxSignKey.Response> { // // public WxPaySandboxSignKey(WxPayAccountMeta accountMeta) { // super(accountMeta); // } // // @Override // protected String __doGetRequestURL() { // return "https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey"; // } // // @Override // protected Response __doParseResponse(IHttpResponse httpResponse) throws Exception { // return new Response(httpResponse.getContent()); // } // // /** // * 获取验签环境密钥响应 // */ // public static class Response extends WxPayBaseResponse { // // private String signkey; // // public Response(String protocol) throws Exception { // super(protocol); // this.signkey = BlurObject.bind(this.getResponseParams().get("sandbox_signkey")).toStringValue(); // } // // public String signkey() { // return signkey; // } // } // } // Path: ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/base/WxPayAccountMeta.java import net.ymate.framework.commons.HttpClientHelper; import net.ymate.payment.wxpay.request.WxPaySandboxSignKey; import net.ymate.platform.core.util.RuntimeUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import java.io.Serializable; import java.net.URL; /* * Copyright 2007-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.wxpay.base; /** * @author 刘镇 (suninformation@163.com) on 17/6/15 下午1:24 * @version 1.0 */ public class WxPayAccountMeta implements Serializable { private static final Log _LOG = LogFactory.getLog(WxPayAccountMeta.class); /** * 公众帐号APP_ID */ private String appId; /** * 商户号 */ private String mchId; /** * 商号密钥 */ private String mchKey; /** * 证书文件路径 */ private String certFilePath; /** * 是否开启沙箱测试模式, 默认值: false */ private boolean sandboxEnabled; /** * 获取沙箱测试模式下的接口URL地址前缀, 默认值: sandboxnew */ private String sandboxPrefix; private SSLConnectionSocketFactory connectionSocketFactory; /** * 异步通知URL */ private String notifyUrl; public WxPayAccountMeta(String appId, String mchId, String mchKey, String notifyUrl) { this.appId = appId; this.mchId = mchId; this.mchKey = mchKey; this.notifyUrl = notifyUrl; } public WxPayAccountMeta(String appId, String mchId, String mchKey, String certFilePath, String notifyUrl) { this.appId = appId; this.mchId = mchId; this.mchKey = mchKey; this.certFilePath = certFilePath; this.notifyUrl = notifyUrl; } private void __doGetSandboxSignKeyIfNeed() { if (sandboxEnabled) { try {
WxPaySandboxSignKey _request = new WxPaySandboxSignKey(this);
suninformation/ymate-payment-v2
ymate-payment-alipay/src/main/java/net/ymate/payment/alipay/IAliPayAccountProvider.java
// Path: ymate-payment-alipay/src/main/java/net/ymate/payment/alipay/base/AliPayAccountMeta.java // public class AliPayAccountMeta implements Serializable { // // /** // * 支付宝分配给开发者的应用ID // */ // private String appId; // // /** // * 同步返回地址,HTTP/HTTPS开头字符串 // */ // private String returnUrl; // // /** // * 支付宝服务器主动通知商户服务器里指定的页面http/https路径 // */ // private String notifyUrl; // // /** // * 返回格式 // */ // private String format; // // /** // * 请求使用的编码格式 // */ // private String charset; // // /** // * 商户生成签名字符串所使用的签名算法类型,目前支持RSA2和RSA,推荐使用RSA2 // */ // private IAliPay.SignType signType; // // /** // * 私钥 // */ // private String privateKey; // // /** // * 公钥 // */ // private String publicKey; // // public AliPayAccountMeta(String appId, String signType, String privateKey, String publicKey) { // if (StringUtils.isBlank(appId)) { // throw new NullArgumentException("app_id"); // } // if (StringUtils.isBlank(signType) || !StringUtils.equalsIgnoreCase(signType, IAliPay.Const.SIGN_TYPE_RSA2) && !StringUtils.equalsIgnoreCase(signType, IAliPay.Const.SIGN_TYPE_RSA)) { // throw new IllegalArgumentException("sign_type"); // } // if (StringUtils.isBlank(privateKey)) { // throw new NullArgumentException("private_key"); // } // if (StringUtils.isBlank(publicKey)) { // throw new NullArgumentException("public_key"); // } // this.appId = appId; // this.signType = IAliPay.SignType.valueOf(signType.toUpperCase()); // this.privateKey = privateKey; // this.publicKey = publicKey; // } // // public AliPayAccountMeta(String appId, String returnUrl, String notifyUrl, String signType, String privateKey, String publicKey) { // this(appId, signType, privateKey, publicKey); // // // this.returnUrl = returnUrl; // this.notifyUrl = notifyUrl; // } // // public String getAppId() { // return appId; // } // // public String getReturnUrl() { // return returnUrl; // } // // public void setReturnUrl(String returnUrl) { // this.returnUrl = returnUrl; // } // // public String getNotifyUrl() { // return notifyUrl; // } // // public void setNotifyUrl(String notifyUrl) { // this.notifyUrl = notifyUrl; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // // public String getCharset() { // return charset; // } // // public void setCharset(String charset) { // this.charset = charset; // } // // public IAliPay.SignType getSignType() { // return signType; // } // // public String getPrivateKey() { // return privateKey; // } // // public String getPublicKey() { // return publicKey; // } // }
import net.ymate.payment.alipay.base.AliPayAccountMeta; import java.util.Collection;
/* * Copyright 2007-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.alipay; /** * @author 刘镇 (suninformation@163.com) on 17/6/8 上午9:02 * @version 1.0 */ public interface IAliPayAccountProvider { void init(IAliPay owner) throws Exception; void destroy() throws Exception;
// Path: ymate-payment-alipay/src/main/java/net/ymate/payment/alipay/base/AliPayAccountMeta.java // public class AliPayAccountMeta implements Serializable { // // /** // * 支付宝分配给开发者的应用ID // */ // private String appId; // // /** // * 同步返回地址,HTTP/HTTPS开头字符串 // */ // private String returnUrl; // // /** // * 支付宝服务器主动通知商户服务器里指定的页面http/https路径 // */ // private String notifyUrl; // // /** // * 返回格式 // */ // private String format; // // /** // * 请求使用的编码格式 // */ // private String charset; // // /** // * 商户生成签名字符串所使用的签名算法类型,目前支持RSA2和RSA,推荐使用RSA2 // */ // private IAliPay.SignType signType; // // /** // * 私钥 // */ // private String privateKey; // // /** // * 公钥 // */ // private String publicKey; // // public AliPayAccountMeta(String appId, String signType, String privateKey, String publicKey) { // if (StringUtils.isBlank(appId)) { // throw new NullArgumentException("app_id"); // } // if (StringUtils.isBlank(signType) || !StringUtils.equalsIgnoreCase(signType, IAliPay.Const.SIGN_TYPE_RSA2) && !StringUtils.equalsIgnoreCase(signType, IAliPay.Const.SIGN_TYPE_RSA)) { // throw new IllegalArgumentException("sign_type"); // } // if (StringUtils.isBlank(privateKey)) { // throw new NullArgumentException("private_key"); // } // if (StringUtils.isBlank(publicKey)) { // throw new NullArgumentException("public_key"); // } // this.appId = appId; // this.signType = IAliPay.SignType.valueOf(signType.toUpperCase()); // this.privateKey = privateKey; // this.publicKey = publicKey; // } // // public AliPayAccountMeta(String appId, String returnUrl, String notifyUrl, String signType, String privateKey, String publicKey) { // this(appId, signType, privateKey, publicKey); // // // this.returnUrl = returnUrl; // this.notifyUrl = notifyUrl; // } // // public String getAppId() { // return appId; // } // // public String getReturnUrl() { // return returnUrl; // } // // public void setReturnUrl(String returnUrl) { // this.returnUrl = returnUrl; // } // // public String getNotifyUrl() { // return notifyUrl; // } // // public void setNotifyUrl(String notifyUrl) { // this.notifyUrl = notifyUrl; // } // // public String getFormat() { // return format; // } // // public void setFormat(String format) { // this.format = format; // } // // public String getCharset() { // return charset; // } // // public void setCharset(String charset) { // this.charset = charset; // } // // public IAliPay.SignType getSignType() { // return signType; // } // // public String getPrivateKey() { // return privateKey; // } // // public String getPublicKey() { // return publicKey; // } // } // Path: ymate-payment-alipay/src/main/java/net/ymate/payment/alipay/IAliPayAccountProvider.java import net.ymate.payment.alipay.base.AliPayAccountMeta; import java.util.Collection; /* * Copyright 2007-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.alipay; /** * @author 刘镇 (suninformation@163.com) on 17/6/8 上午9:02 * @version 1.0 */ public interface IAliPayAccountProvider { void init(IAliPay owner) throws Exception; void destroy() throws Exception;
void registerAccount(AliPayAccountMeta accountMeta);
suninformation/ymate-payment-v2
ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/IWxPayAccountProvider.java
// Path: ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/base/WxPayAccountMeta.java // public class WxPayAccountMeta implements Serializable { // // private static final Log _LOG = LogFactory.getLog(WxPayAccountMeta.class); // // /** // * 公众帐号APP_ID // */ // private String appId; // // /** // * 商户号 // */ // private String mchId; // // /** // * 商号密钥 // */ // private String mchKey; // // /** // * 证书文件路径 // */ // private String certFilePath; // // /** // * 是否开启沙箱测试模式, 默认值: false // */ // private boolean sandboxEnabled; // // /** // * 获取沙箱测试模式下的接口URL地址前缀, 默认值: sandboxnew // */ // private String sandboxPrefix; // // private SSLConnectionSocketFactory connectionSocketFactory; // // /** // * 异步通知URL // */ // private String notifyUrl; // // public WxPayAccountMeta(String appId, String mchId, String mchKey, String notifyUrl) { // this.appId = appId; // this.mchId = mchId; // this.mchKey = mchKey; // this.notifyUrl = notifyUrl; // } // // public WxPayAccountMeta(String appId, String mchId, String mchKey, String certFilePath, String notifyUrl) { // this.appId = appId; // this.mchId = mchId; // this.mchKey = mchKey; // this.certFilePath = certFilePath; // this.notifyUrl = notifyUrl; // } // // private void __doGetSandboxSignKeyIfNeed() { // if (sandboxEnabled) { // try { // WxPaySandboxSignKey _request = new WxPaySandboxSignKey(this); // WxPaySandboxSignKey.Response _response = _request.execute(); // if (_response.checkReturnCode()) { // this.mchKey = _response.signkey(); // } // } catch (Exception e) { // _LOG.error("try get sandbox signkey error: ", RuntimeUtils.unwrapThrow(e)); // } // } // } // // public String getAppId() { // return appId; // } // // public void setAppId(String appId) { // this.appId = appId; // } // // public String getMchId() { // return mchId; // } // // public void setMchId(String mchId) { // this.mchId = mchId; // } // // public String getMchKey() { // return mchKey; // } // // public void setMchKey(String mchKey) { // this.mchKey = mchKey; // } // // public String getCertFilePath() { // return certFilePath; // } // // public void setCertFilePath(String certFilePath) { // this.certFilePath = certFilePath; // } // // public SSLConnectionSocketFactory getConnectionSocketFactory() { // if (connectionSocketFactory == null) { // synchronized (this) { // if (connectionSocketFactory == null && StringUtils.isNotBlank(mchId) && StringUtils.isNotBlank(certFilePath)) { // try { // connectionSocketFactory = HttpClientHelper.createConnectionSocketFactory(new URL(certFilePath), mchId.toCharArray()); // } catch (Exception e) { // _LOG.warn("", RuntimeUtils.unwrapThrow(e)); // } // } // } // } // return connectionSocketFactory; // } // // public void setConnectionSocketFactory(SSLConnectionSocketFactory connectionSocketFactory) { // this.connectionSocketFactory = connectionSocketFactory; // } // // public String getNotifyUrl() { // return notifyUrl; // } // // public void setNotifyUrl(String notifyUrl) { // this.notifyUrl = notifyUrl; // } // // public boolean isSandboxEnabled() { // return sandboxEnabled; // } // // public void setSandboxEnabled(boolean sandboxEnabled) { // this.sandboxEnabled = sandboxEnabled; // // // __doGetSandboxSignKeyIfNeed(); // } // // public String getSandboxPrefix() { // if (sandboxEnabled) { // return sandboxPrefix; // } // return ""; // } // // public void setSandboxPrefix(String sandboxPrefix) { // sandboxPrefix = StringUtils.defaultIfBlank(sandboxPrefix, "sandboxnew"); // if (StringUtils.startsWith(sandboxPrefix, "/")) { // sandboxPrefix = StringUtils.substringAfter(sandboxPrefix, "/"); // } // if (!StringUtils.endsWith(this.sandboxPrefix, "/")) { // sandboxPrefix = sandboxPrefix + "/"; // } // this.sandboxPrefix = sandboxPrefix; // } // }
import net.ymate.payment.wxpay.base.WxPayAccountMeta; import java.util.Collection;
/* * Copyright 2007-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.wxpay; /** * @author 刘镇 (suninformation@163.com) on 16/5/23 下午5:58 * @version 1.0 */ public interface IWxPayAccountProvider { void init(IWxPay owner) throws Exception; void destroy() throws Exception;
// Path: ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/base/WxPayAccountMeta.java // public class WxPayAccountMeta implements Serializable { // // private static final Log _LOG = LogFactory.getLog(WxPayAccountMeta.class); // // /** // * 公众帐号APP_ID // */ // private String appId; // // /** // * 商户号 // */ // private String mchId; // // /** // * 商号密钥 // */ // private String mchKey; // // /** // * 证书文件路径 // */ // private String certFilePath; // // /** // * 是否开启沙箱测试模式, 默认值: false // */ // private boolean sandboxEnabled; // // /** // * 获取沙箱测试模式下的接口URL地址前缀, 默认值: sandboxnew // */ // private String sandboxPrefix; // // private SSLConnectionSocketFactory connectionSocketFactory; // // /** // * 异步通知URL // */ // private String notifyUrl; // // public WxPayAccountMeta(String appId, String mchId, String mchKey, String notifyUrl) { // this.appId = appId; // this.mchId = mchId; // this.mchKey = mchKey; // this.notifyUrl = notifyUrl; // } // // public WxPayAccountMeta(String appId, String mchId, String mchKey, String certFilePath, String notifyUrl) { // this.appId = appId; // this.mchId = mchId; // this.mchKey = mchKey; // this.certFilePath = certFilePath; // this.notifyUrl = notifyUrl; // } // // private void __doGetSandboxSignKeyIfNeed() { // if (sandboxEnabled) { // try { // WxPaySandboxSignKey _request = new WxPaySandboxSignKey(this); // WxPaySandboxSignKey.Response _response = _request.execute(); // if (_response.checkReturnCode()) { // this.mchKey = _response.signkey(); // } // } catch (Exception e) { // _LOG.error("try get sandbox signkey error: ", RuntimeUtils.unwrapThrow(e)); // } // } // } // // public String getAppId() { // return appId; // } // // public void setAppId(String appId) { // this.appId = appId; // } // // public String getMchId() { // return mchId; // } // // public void setMchId(String mchId) { // this.mchId = mchId; // } // // public String getMchKey() { // return mchKey; // } // // public void setMchKey(String mchKey) { // this.mchKey = mchKey; // } // // public String getCertFilePath() { // return certFilePath; // } // // public void setCertFilePath(String certFilePath) { // this.certFilePath = certFilePath; // } // // public SSLConnectionSocketFactory getConnectionSocketFactory() { // if (connectionSocketFactory == null) { // synchronized (this) { // if (connectionSocketFactory == null && StringUtils.isNotBlank(mchId) && StringUtils.isNotBlank(certFilePath)) { // try { // connectionSocketFactory = HttpClientHelper.createConnectionSocketFactory(new URL(certFilePath), mchId.toCharArray()); // } catch (Exception e) { // _LOG.warn("", RuntimeUtils.unwrapThrow(e)); // } // } // } // } // return connectionSocketFactory; // } // // public void setConnectionSocketFactory(SSLConnectionSocketFactory connectionSocketFactory) { // this.connectionSocketFactory = connectionSocketFactory; // } // // public String getNotifyUrl() { // return notifyUrl; // } // // public void setNotifyUrl(String notifyUrl) { // this.notifyUrl = notifyUrl; // } // // public boolean isSandboxEnabled() { // return sandboxEnabled; // } // // public void setSandboxEnabled(boolean sandboxEnabled) { // this.sandboxEnabled = sandboxEnabled; // // // __doGetSandboxSignKeyIfNeed(); // } // // public String getSandboxPrefix() { // if (sandboxEnabled) { // return sandboxPrefix; // } // return ""; // } // // public void setSandboxPrefix(String sandboxPrefix) { // sandboxPrefix = StringUtils.defaultIfBlank(sandboxPrefix, "sandboxnew"); // if (StringUtils.startsWith(sandboxPrefix, "/")) { // sandboxPrefix = StringUtils.substringAfter(sandboxPrefix, "/"); // } // if (!StringUtils.endsWith(this.sandboxPrefix, "/")) { // sandboxPrefix = sandboxPrefix + "/"; // } // this.sandboxPrefix = sandboxPrefix; // } // } // Path: ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/IWxPayAccountProvider.java import net.ymate.payment.wxpay.base.WxPayAccountMeta; import java.util.Collection; /* * Copyright 2007-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.wxpay; /** * @author 刘镇 (suninformation@163.com) on 16/5/23 下午5:58 * @version 1.0 */ public interface IWxPayAccountProvider { void init(IWxPay owner) throws Exception; void destroy() throws Exception;
void registerAccount(WxPayAccountMeta accountMeta);
suninformation/ymate-payment-v2
ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/request/WxPayRedPackSendGroup.java
// Path: ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/base/WxPayAccountMeta.java // public class WxPayAccountMeta implements Serializable { // // private static final Log _LOG = LogFactory.getLog(WxPayAccountMeta.class); // // /** // * 公众帐号APP_ID // */ // private String appId; // // /** // * 商户号 // */ // private String mchId; // // /** // * 商号密钥 // */ // private String mchKey; // // /** // * 证书文件路径 // */ // private String certFilePath; // // /** // * 是否开启沙箱测试模式, 默认值: false // */ // private boolean sandboxEnabled; // // /** // * 获取沙箱测试模式下的接口URL地址前缀, 默认值: sandboxnew // */ // private String sandboxPrefix; // // private SSLConnectionSocketFactory connectionSocketFactory; // // /** // * 异步通知URL // */ // private String notifyUrl; // // public WxPayAccountMeta(String appId, String mchId, String mchKey, String notifyUrl) { // this.appId = appId; // this.mchId = mchId; // this.mchKey = mchKey; // this.notifyUrl = notifyUrl; // } // // public WxPayAccountMeta(String appId, String mchId, String mchKey, String certFilePath, String notifyUrl) { // this.appId = appId; // this.mchId = mchId; // this.mchKey = mchKey; // this.certFilePath = certFilePath; // this.notifyUrl = notifyUrl; // } // // private void __doGetSandboxSignKeyIfNeed() { // if (sandboxEnabled) { // try { // WxPaySandboxSignKey _request = new WxPaySandboxSignKey(this); // WxPaySandboxSignKey.Response _response = _request.execute(); // if (_response.checkReturnCode()) { // this.mchKey = _response.signkey(); // } // } catch (Exception e) { // _LOG.error("try get sandbox signkey error: ", RuntimeUtils.unwrapThrow(e)); // } // } // } // // public String getAppId() { // return appId; // } // // public void setAppId(String appId) { // this.appId = appId; // } // // public String getMchId() { // return mchId; // } // // public void setMchId(String mchId) { // this.mchId = mchId; // } // // public String getMchKey() { // return mchKey; // } // // public void setMchKey(String mchKey) { // this.mchKey = mchKey; // } // // public String getCertFilePath() { // return certFilePath; // } // // public void setCertFilePath(String certFilePath) { // this.certFilePath = certFilePath; // } // // public SSLConnectionSocketFactory getConnectionSocketFactory() { // if (connectionSocketFactory == null) { // synchronized (this) { // if (connectionSocketFactory == null && StringUtils.isNotBlank(mchId) && StringUtils.isNotBlank(certFilePath)) { // try { // connectionSocketFactory = HttpClientHelper.createConnectionSocketFactory(new URL(certFilePath), mchId.toCharArray()); // } catch (Exception e) { // _LOG.warn("", RuntimeUtils.unwrapThrow(e)); // } // } // } // } // return connectionSocketFactory; // } // // public void setConnectionSocketFactory(SSLConnectionSocketFactory connectionSocketFactory) { // this.connectionSocketFactory = connectionSocketFactory; // } // // public String getNotifyUrl() { // return notifyUrl; // } // // public void setNotifyUrl(String notifyUrl) { // this.notifyUrl = notifyUrl; // } // // public boolean isSandboxEnabled() { // return sandboxEnabled; // } // // public void setSandboxEnabled(boolean sandboxEnabled) { // this.sandboxEnabled = sandboxEnabled; // // // __doGetSandboxSignKeyIfNeed(); // } // // public String getSandboxPrefix() { // if (sandboxEnabled) { // return sandboxPrefix; // } // return ""; // } // // public void setSandboxPrefix(String sandboxPrefix) { // sandboxPrefix = StringUtils.defaultIfBlank(sandboxPrefix, "sandboxnew"); // if (StringUtils.startsWith(sandboxPrefix, "/")) { // sandboxPrefix = StringUtils.substringAfter(sandboxPrefix, "/"); // } // if (!StringUtils.endsWith(this.sandboxPrefix, "/")) { // sandboxPrefix = sandboxPrefix + "/"; // } // this.sandboxPrefix = sandboxPrefix; // } // }
import net.ymate.payment.wxpay.base.WxPayAccountMeta; import java.util.Map;
/* * Copyright 2007-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.wxpay.request; /** * 发放裂变红包 * * @author 刘镇 (suninformation@163.com) on 16/6/27 上午12:39 * @version 1.0 */ public class WxPayRedPackSendGroup extends WxPayRedPackSend { /** * 红包金额设置方式 */ private String amtType;
// Path: ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/base/WxPayAccountMeta.java // public class WxPayAccountMeta implements Serializable { // // private static final Log _LOG = LogFactory.getLog(WxPayAccountMeta.class); // // /** // * 公众帐号APP_ID // */ // private String appId; // // /** // * 商户号 // */ // private String mchId; // // /** // * 商号密钥 // */ // private String mchKey; // // /** // * 证书文件路径 // */ // private String certFilePath; // // /** // * 是否开启沙箱测试模式, 默认值: false // */ // private boolean sandboxEnabled; // // /** // * 获取沙箱测试模式下的接口URL地址前缀, 默认值: sandboxnew // */ // private String sandboxPrefix; // // private SSLConnectionSocketFactory connectionSocketFactory; // // /** // * 异步通知URL // */ // private String notifyUrl; // // public WxPayAccountMeta(String appId, String mchId, String mchKey, String notifyUrl) { // this.appId = appId; // this.mchId = mchId; // this.mchKey = mchKey; // this.notifyUrl = notifyUrl; // } // // public WxPayAccountMeta(String appId, String mchId, String mchKey, String certFilePath, String notifyUrl) { // this.appId = appId; // this.mchId = mchId; // this.mchKey = mchKey; // this.certFilePath = certFilePath; // this.notifyUrl = notifyUrl; // } // // private void __doGetSandboxSignKeyIfNeed() { // if (sandboxEnabled) { // try { // WxPaySandboxSignKey _request = new WxPaySandboxSignKey(this); // WxPaySandboxSignKey.Response _response = _request.execute(); // if (_response.checkReturnCode()) { // this.mchKey = _response.signkey(); // } // } catch (Exception e) { // _LOG.error("try get sandbox signkey error: ", RuntimeUtils.unwrapThrow(e)); // } // } // } // // public String getAppId() { // return appId; // } // // public void setAppId(String appId) { // this.appId = appId; // } // // public String getMchId() { // return mchId; // } // // public void setMchId(String mchId) { // this.mchId = mchId; // } // // public String getMchKey() { // return mchKey; // } // // public void setMchKey(String mchKey) { // this.mchKey = mchKey; // } // // public String getCertFilePath() { // return certFilePath; // } // // public void setCertFilePath(String certFilePath) { // this.certFilePath = certFilePath; // } // // public SSLConnectionSocketFactory getConnectionSocketFactory() { // if (connectionSocketFactory == null) { // synchronized (this) { // if (connectionSocketFactory == null && StringUtils.isNotBlank(mchId) && StringUtils.isNotBlank(certFilePath)) { // try { // connectionSocketFactory = HttpClientHelper.createConnectionSocketFactory(new URL(certFilePath), mchId.toCharArray()); // } catch (Exception e) { // _LOG.warn("", RuntimeUtils.unwrapThrow(e)); // } // } // } // } // return connectionSocketFactory; // } // // public void setConnectionSocketFactory(SSLConnectionSocketFactory connectionSocketFactory) { // this.connectionSocketFactory = connectionSocketFactory; // } // // public String getNotifyUrl() { // return notifyUrl; // } // // public void setNotifyUrl(String notifyUrl) { // this.notifyUrl = notifyUrl; // } // // public boolean isSandboxEnabled() { // return sandboxEnabled; // } // // public void setSandboxEnabled(boolean sandboxEnabled) { // this.sandboxEnabled = sandboxEnabled; // // // __doGetSandboxSignKeyIfNeed(); // } // // public String getSandboxPrefix() { // if (sandboxEnabled) { // return sandboxPrefix; // } // return ""; // } // // public void setSandboxPrefix(String sandboxPrefix) { // sandboxPrefix = StringUtils.defaultIfBlank(sandboxPrefix, "sandboxnew"); // if (StringUtils.startsWith(sandboxPrefix, "/")) { // sandboxPrefix = StringUtils.substringAfter(sandboxPrefix, "/"); // } // if (!StringUtils.endsWith(this.sandboxPrefix, "/")) { // sandboxPrefix = sandboxPrefix + "/"; // } // this.sandboxPrefix = sandboxPrefix; // } // } // Path: ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/request/WxPayRedPackSendGroup.java import net.ymate.payment.wxpay.base.WxPayAccountMeta; import java.util.Map; /* * Copyright 2007-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.wxpay.request; /** * 发放裂变红包 * * @author 刘镇 (suninformation@163.com) on 16/6/27 上午12:39 * @version 1.0 */ public class WxPayRedPackSendGroup extends WxPayRedPackSend { /** * 红包金额设置方式 */ private String amtType;
public WxPayRedPackSendGroup(WxPayAccountMeta accountMeta, String mchBillNo, String sendName, String reOpenId, Integer totalAmount, Integer totalNum, String wishing, String clientIp, String actName, String remark) {
WonderBeat/vasilich
alice-src/bitoflife/chatterbean/config/TokenizerConfig.java
// Path: alice-src/bitoflife/chatterbean/text/Tokenizer.java // public class Tokenizer // { // /* // Attribute Section // */ // // private Boolean ignoreWhitespace; // // private String[] splitters; // // private Pattern pattern; // // /* // Constructor Section // */ // // public Tokenizer() // { // } // // public Tokenizer(String... splitters) // { // setIgnoreWhitespace(true); // setSplitters(splitters); // } // // public Tokenizer(TokenizerConfig config) // { // this(config.splitters()); // } // // /* // Event Section // */ // // private void afterSetProperty() // { // if (splitters == null || ignoreWhitespace == null) // return; // // String expression = ""; // for (int i = 0, n = splitters.length;;) // { // expression += escapeRegex(splitters[i]); // if (++i >= n) break; // expression += '|'; // } // // if (ignoreWhitespace) // expression = "(" + expression + ")\\s*|\\s+"; // else // expression = "(" + expression + "|\\s+)"; // // pattern = Pattern.compile(expression); // } // // /* // Method Section // */ // // public List<String> tokenize(String input) // { // List<String> output = new ArrayList<String>(); // Matcher matcher = pattern.matcher(input); // int beginIndex = 0; // // while (matcher.find()) // { // int endIndex = matcher.start(); // String token = input.substring(beginIndex, endIndex); // if (token.length() > 0) // output.add(token); // // String symbol = matcher.group(1); // if (symbol != null) // output.add(symbol); // // String breaker = matcher.group(); // beginIndex = endIndex + breaker.length(); // } // // if (beginIndex < input.length()) // { // String token = input.substring(beginIndex); // output.add(token); // } // // return output; // } // // public String toString(List<String> tokens) // { // String output = ""; // int i = 0, n = tokens.size(); // String next = tokens.get(0); // // for (;;) // { // output += next; // if (++i >= n) break; // next = tokens.get(i); // Matcher matcher = pattern.matcher(next); // if (!matcher.matches()) output += ' '; // } // // return output; // } // // /* // Property Section // */ // // public boolean getIgnoreWhitespace() // { // return ignoreWhitespace; // } // // public void setIgnoreWhitespace(boolean ignore) // { // ignoreWhitespace = ignore; // afterSetProperty(); // } // // public String[] getSplitters() // { // return splitters; // } // // public void setSplitters(String[] splitters) // { // this.splitters = splitters; // afterSetProperty(); // } // }
import bitoflife.chatterbean.text.Tokenizer;
/* Copyleft (C) 2005 Hio Perroni Filho xperroni@yahoo.com ICQ: 2490863 This file is part of ChatterBean. ChatterBean 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 2 of the License, or (at your option) any later version. ChatterBean 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 ChatterBean (look at the Documents/ directory); if not, either write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, or visit (http://www.gnu.org/licenses/gpl.txt). */ package bitoflife.chatterbean.config; public interface TokenizerConfig {
// Path: alice-src/bitoflife/chatterbean/text/Tokenizer.java // public class Tokenizer // { // /* // Attribute Section // */ // // private Boolean ignoreWhitespace; // // private String[] splitters; // // private Pattern pattern; // // /* // Constructor Section // */ // // public Tokenizer() // { // } // // public Tokenizer(String... splitters) // { // setIgnoreWhitespace(true); // setSplitters(splitters); // } // // public Tokenizer(TokenizerConfig config) // { // this(config.splitters()); // } // // /* // Event Section // */ // // private void afterSetProperty() // { // if (splitters == null || ignoreWhitespace == null) // return; // // String expression = ""; // for (int i = 0, n = splitters.length;;) // { // expression += escapeRegex(splitters[i]); // if (++i >= n) break; // expression += '|'; // } // // if (ignoreWhitespace) // expression = "(" + expression + ")\\s*|\\s+"; // else // expression = "(" + expression + "|\\s+)"; // // pattern = Pattern.compile(expression); // } // // /* // Method Section // */ // // public List<String> tokenize(String input) // { // List<String> output = new ArrayList<String>(); // Matcher matcher = pattern.matcher(input); // int beginIndex = 0; // // while (matcher.find()) // { // int endIndex = matcher.start(); // String token = input.substring(beginIndex, endIndex); // if (token.length() > 0) // output.add(token); // // String symbol = matcher.group(1); // if (symbol != null) // output.add(symbol); // // String breaker = matcher.group(); // beginIndex = endIndex + breaker.length(); // } // // if (beginIndex < input.length()) // { // String token = input.substring(beginIndex); // output.add(token); // } // // return output; // } // // public String toString(List<String> tokens) // { // String output = ""; // int i = 0, n = tokens.size(); // String next = tokens.get(0); // // for (;;) // { // output += next; // if (++i >= n) break; // next = tokens.get(i); // Matcher matcher = pattern.matcher(next); // if (!matcher.matches()) output += ' '; // } // // return output; // } // // /* // Property Section // */ // // public boolean getIgnoreWhitespace() // { // return ignoreWhitespace; // } // // public void setIgnoreWhitespace(boolean ignore) // { // ignoreWhitespace = ignore; // afterSetProperty(); // } // // public String[] getSplitters() // { // return splitters; // } // // public void setSplitters(String[] splitters) // { // this.splitters = splitters; // afterSetProperty(); // } // } // Path: alice-src/bitoflife/chatterbean/config/TokenizerConfig.java import bitoflife.chatterbean.text.Tokenizer; /* Copyleft (C) 2005 Hio Perroni Filho xperroni@yahoo.com ICQ: 2490863 This file is part of ChatterBean. ChatterBean 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 2 of the License, or (at your option) any later version. ChatterBean 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 ChatterBean (look at the Documents/ directory); if not, either write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, or visit (http://www.gnu.org/licenses/gpl.txt). */ package bitoflife.chatterbean.config; public interface TokenizerConfig {
public Tokenizer newInstance();
WonderBeat/vasilich
alice-src/bitoflife/chatterbean/aiml/Text.java
// Path: alice-src/bitoflife/chatterbean/Match.java // public class Match implements Serializable // { // /* // Inner Classes // */ // // public enum Section {PATTERN, THAT, TOPIC;} // // /* // Attributes // */ // // /** Version class identifier for the serialization engine. Matches the number of the last revision where the class was created / modified. */ // private static final long serialVersionUID = 8L; // // private final Map<Section, List<String>> sections = new HashMap<Section, List<String>>(); // // private AliceBot callback; // // private Sentence input; // // private Sentence that; // // private Sentence topic; // // private String[] matchPath; // // { // sections.put(Section.PATTERN, new ArrayList<String>(2)); // Pattern wildcards // sections.put(Section.THAT, new ArrayList<String>(2)); // That wildcards // sections.put(Section.TOPIC, new ArrayList<String>(2)); // Topic wildcards // } // // /* // Constructor // */ // // public Match() // { // } // // public Match(AliceBot callback, Sentence input, Sentence that, Sentence topic) // { // this.callback = callback; // this.input = input; // this.that = that; // this.topic = topic; // setUpMatchPath(input.normalized(), that.normalized(), topic.normalized()); // } // // public Match(Sentence input) // { // this(null, input, ASTERISK, ASTERISK); // } // // /* // Methods // */ // // private void appendWildcard(List<String> section, Sentence source, int beginIndex, int endIndex) // { // if (beginIndex == endIndex) // section.add(0, ""); // else try // { // section.add(0, source.original(beginIndex, endIndex)); // } // catch (Exception e) // { // // throw new RuntimeException("Source: {\"" + source.getOriginal() + "\", \"" + source.getNormalized() + "\"}\n" + // // "Begin Index: " + beginIndex + "\n" + // // "End Index: " + endIndex, e); // } // } // // private void setUpMatchPath(String[] pattern, String[] that, String[] topic) // { // int m = pattern.length, n = that.length, o = topic.length; // matchPath = new String[m + 1 + n + 1 + o]; // matchPath[m] = "<THAT>"; // matchPath[m + 1 + n] = "<TOPIC>"; // // System.arraycopy(pattern, 0, matchPath, 0, m); // System.arraycopy(that, 0, matchPath, m + 1, n); // System.arraycopy(topic, 0, matchPath, m + 1 + n + 1, o); // } // // public void appendWildcard(int beginIndex, int endIndex) // { // int inputLength = input.length(); // if (beginIndex <= inputLength) // { // appendWildcard(sections.get(Section.PATTERN), input, beginIndex, endIndex); // return; // } // // beginIndex = beginIndex - (inputLength + 1); // endIndex = endIndex - (inputLength + 1); // // int thatLength = that.length(); // if (beginIndex <= thatLength) // { // appendWildcard(sections.get(Section.THAT), that, beginIndex, endIndex); // return; // } // // beginIndex = beginIndex - (thatLength + 1); // endIndex = endIndex - (thatLength + 1); // // int topicLength = topic.length(); // if (beginIndex < topicLength) // appendWildcard(sections.get(Section.TOPIC), topic, beginIndex, endIndex); // } // // /** // Gets the contents for the (index)th wildcard in the matched section. // */ // public String wildcard(Section section, int index) // { // List<String> wildcards = sections.get(section); // //fixed by lcl // if(wildcards.size() == 0) // return ""; // int i = index - 1; // if(i < wildcards.size() && i > -1) // return wildcards.get(i); // else // return ""; // } // // /* // Properties // */ // // public AliceBot getCallback() // { // return callback; // } // // public void setCallback(AliceBot callback) // { // this.callback = callback; // } // // public String[] getMatchPath() // { // return matchPath; // } // // public String getMatchPath(int index) // { // return matchPath[index]; // } // // public int getMatchPathLength() // { // return matchPath.length; // } // }
import bitoflife.chatterbean.Match;
/* Copyleft (C) 2005 Hio Perroni Filho xperroni@yahoo.com ICQ: 2490863 This file is part of ChatterBean. ChatterBean 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 2 of the License, or (at your option) any later version. ChatterBean 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 ChatterBean (look at the Documents/ directory); if not, either write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, or visit (http://www.gnu.org/licenses/gpl.txt). */ package bitoflife.chatterbean.aiml; public class Text extends TemplateElement { /* Attributes */ private final String value; /* Constructor */ public Text(String value) { this.value = value; } /* Methods */ public boolean equals(Object obj) { if (obj == null) return false; String text = obj.toString(); return (text != null ? text.equals(value) : value == null); } public int hashCode() { return (value == null ? 0 : value.hashCode()); } public String toString() { return value; }
// Path: alice-src/bitoflife/chatterbean/Match.java // public class Match implements Serializable // { // /* // Inner Classes // */ // // public enum Section {PATTERN, THAT, TOPIC;} // // /* // Attributes // */ // // /** Version class identifier for the serialization engine. Matches the number of the last revision where the class was created / modified. */ // private static final long serialVersionUID = 8L; // // private final Map<Section, List<String>> sections = new HashMap<Section, List<String>>(); // // private AliceBot callback; // // private Sentence input; // // private Sentence that; // // private Sentence topic; // // private String[] matchPath; // // { // sections.put(Section.PATTERN, new ArrayList<String>(2)); // Pattern wildcards // sections.put(Section.THAT, new ArrayList<String>(2)); // That wildcards // sections.put(Section.TOPIC, new ArrayList<String>(2)); // Topic wildcards // } // // /* // Constructor // */ // // public Match() // { // } // // public Match(AliceBot callback, Sentence input, Sentence that, Sentence topic) // { // this.callback = callback; // this.input = input; // this.that = that; // this.topic = topic; // setUpMatchPath(input.normalized(), that.normalized(), topic.normalized()); // } // // public Match(Sentence input) // { // this(null, input, ASTERISK, ASTERISK); // } // // /* // Methods // */ // // private void appendWildcard(List<String> section, Sentence source, int beginIndex, int endIndex) // { // if (beginIndex == endIndex) // section.add(0, ""); // else try // { // section.add(0, source.original(beginIndex, endIndex)); // } // catch (Exception e) // { // // throw new RuntimeException("Source: {\"" + source.getOriginal() + "\", \"" + source.getNormalized() + "\"}\n" + // // "Begin Index: " + beginIndex + "\n" + // // "End Index: " + endIndex, e); // } // } // // private void setUpMatchPath(String[] pattern, String[] that, String[] topic) // { // int m = pattern.length, n = that.length, o = topic.length; // matchPath = new String[m + 1 + n + 1 + o]; // matchPath[m] = "<THAT>"; // matchPath[m + 1 + n] = "<TOPIC>"; // // System.arraycopy(pattern, 0, matchPath, 0, m); // System.arraycopy(that, 0, matchPath, m + 1, n); // System.arraycopy(topic, 0, matchPath, m + 1 + n + 1, o); // } // // public void appendWildcard(int beginIndex, int endIndex) // { // int inputLength = input.length(); // if (beginIndex <= inputLength) // { // appendWildcard(sections.get(Section.PATTERN), input, beginIndex, endIndex); // return; // } // // beginIndex = beginIndex - (inputLength + 1); // endIndex = endIndex - (inputLength + 1); // // int thatLength = that.length(); // if (beginIndex <= thatLength) // { // appendWildcard(sections.get(Section.THAT), that, beginIndex, endIndex); // return; // } // // beginIndex = beginIndex - (thatLength + 1); // endIndex = endIndex - (thatLength + 1); // // int topicLength = topic.length(); // if (beginIndex < topicLength) // appendWildcard(sections.get(Section.TOPIC), topic, beginIndex, endIndex); // } // // /** // Gets the contents for the (index)th wildcard in the matched section. // */ // public String wildcard(Section section, int index) // { // List<String> wildcards = sections.get(section); // //fixed by lcl // if(wildcards.size() == 0) // return ""; // int i = index - 1; // if(i < wildcards.size() && i > -1) // return wildcards.get(i); // else // return ""; // } // // /* // Properties // */ // // public AliceBot getCallback() // { // return callback; // } // // public void setCallback(AliceBot callback) // { // this.callback = callback; // } // // public String[] getMatchPath() // { // return matchPath; // } // // public String getMatchPath(int index) // { // return matchPath[index]; // } // // public int getMatchPathLength() // { // return matchPath.length; // } // } // Path: alice-src/bitoflife/chatterbean/aiml/Text.java import bitoflife.chatterbean.Match; /* Copyleft (C) 2005 Hio Perroni Filho xperroni@yahoo.com ICQ: 2490863 This file is part of ChatterBean. ChatterBean 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 2 of the License, or (at your option) any later version. ChatterBean 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 ChatterBean (look at the Documents/ directory); if not, either write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, or visit (http://www.gnu.org/licenses/gpl.txt). */ package bitoflife.chatterbean.aiml; public class Text extends TemplateElement { /* Attributes */ private final String value; /* Constructor */ public Text(String value) { this.value = value; } /* Methods */ public boolean equals(Object obj) { if (obj == null) return false; String text = obj.toString(); return (text != null ? text.equals(value) : value == null); } public int hashCode() { return (value == null ? 0 : value.hashCode()); } public String toString() { return value; }
public String process(Match match)